diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 2074edfc0a..13fc420f42 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -9,7 +9,7 @@ omissions, and create a pull request, or email , if you wish to see changes to this list. * acetheultimate -* Adrian Flethcehr (TD) +* Adrian Fletcher (TD) * agoldvarg * Alberto Arri (R3) * amiracam @@ -108,7 +108,7 @@ see changes to this list. * Lars Stage Thomsen (Danske Bank) * Lee Braine (Barclays) * Lucas Salmen (Itau) -* Maksymillian Pawlak (R3) +* Maksymilian Pawlak (R3) * Marek Scocovsky (ABSA) * marekdapps * Mark Lauer (Westpac) @@ -175,7 +175,8 @@ see changes to this list. * tomconte * Tommy Lillehagen (R3) * tomtau -* Tudor Malene (R3) +* Tudor Malene (R3) +* Tushar Singh Bora * varunkm * verymahler * Viktor Kolomeyko (R3) diff --git a/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt b/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt index bc9b636ab2..57d4d3f3cf 100644 --- a/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt +++ b/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt @@ -340,14 +340,14 @@ object JacksonSupport { mapper.wellKnownPartyFromX500Name(principal) ?: throw JsonParseException(parser, "Could not find a Party with name $principal") } else { val nameMatches = mapper.partiesFromName(parser.text) - if (nameMatches.isEmpty()) { - val publicKey = parser.readValueAs() - mapper.partyFromKey(publicKey) - ?: throw JsonParseException(parser, "Could not find a Party with key ${publicKey.toStringShort()}") - } else if (nameMatches.size == 1) { - nameMatches.first() - } else { - throw JsonParseException(parser, "Ambiguous name match '${parser.text}': could be any of " + + when { + nameMatches.isEmpty() -> { + val publicKey = parser.readValueAs() + mapper.partyFromKey(publicKey) + ?: throw JsonParseException(parser, "Could not find a Party with key ${publicKey.toStringShort()}") + } + nameMatches.size == 1 -> nameMatches.first() + else -> throw JsonParseException(parser, "Ambiguous name match '${parser.text}': could be any of " + nameMatches.map { it.name }.joinToString(" ... or ... ")) } } diff --git a/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt b/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt index a25416e4de..4f952a93a9 100644 --- a/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt +++ b/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt @@ -230,7 +230,7 @@ open class StringToMethodCallParser @JvmOverloads constructor( val paramNames = methodParamNames[name]!! val typeNames = args.parameters.map { it.type.simpleName } val paramTypes = paramNames.zip(typeNames) - paramTypes.map { "${it.first}: ${it.second}" }.joinToString(", ") + paramTypes.joinToString(", ") { "${it.first}: ${it.second}" } } Pair(name, argStr) }.toMap() diff --git a/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt b/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt index 166303e653..24ba7b7c72 100644 --- a/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt +++ b/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt @@ -13,7 +13,6 @@ package net.corda.client.jackson import net.corda.core.crypto.SecureHash import org.junit.Assert.assertArrayEquals import org.junit.Test -import kotlin.reflect.full.primaryConstructor import kotlin.test.assertEquals class StringToMethodCallParserTest { diff --git a/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt b/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt index de3e38557d..7a772e4022 100644 --- a/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt +++ b/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt @@ -121,13 +121,13 @@ class NodeMonitorModelTest : IntegrationTest() { sequence( // TODO : Add test for remove when driver DSL support individual node shutdown. expect { output: NetworkMapCache.MapChange -> - require(output.node.legalIdentities.any { it.name == ALICE_NAME }) { "Expecting : ${ALICE_NAME}, Actual : ${output.node.legalIdentities.map(Party::name)}" } + require(output.node.legalIdentities.any { it.name == ALICE_NAME }) { "Expecting : $ALICE_NAME, Actual : ${output.node.legalIdentities.map(Party::name)}" } }, expect { output: NetworkMapCache.MapChange -> - require(output.node.legalIdentities.any { it.name == BOB_NAME }) { "Expecting : ${BOB_NAME}, Actual : ${output.node.legalIdentities.map(Party::name)}" } + require(output.node.legalIdentities.any { it.name == BOB_NAME }) { "Expecting : $BOB_NAME, Actual : ${output.node.legalIdentities.map(Party::name)}" } }, expect { output: NetworkMapCache.MapChange -> - require(output.node.legalIdentities.any { it.name == CHARLIE_NAME }) { "Expecting : ${CHARLIE_NAME}, Actual : ${output.node.legalIdentities.map(Party::name)}" } + require(output.node.legalIdentities.any { it.name == CHARLIE_NAME }) { "Expecting : $CHARLIE_NAME, Actual : ${output.node.legalIdentities.map(Party::name)}" } } ) } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt index f0c35b48b8..9bda36e4bb 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt @@ -39,24 +39,23 @@ class ContractStateModel { private val cashStatesDiff: Observable> = contractStatesDiff.map { Diff(it.added.filterCashStateAndRefs(), it.removed.filterCashStateAndRefs()) } - val cashStates: ObservableList> = cashStatesDiff.fold(FXCollections.observableArrayList()) { list: MutableList>, statesDiff -> - list.removeIf { it in statesDiff.removed } - list.addAll(statesDiff.added) + val cashStates: ObservableList> = cashStatesDiff.fold(FXCollections.observableArrayList()) { list: MutableList>, (added, removed) -> + list.removeIf { it in removed } + list.addAll(added) }.distinctBy { it.ref } val cash = cashStates.map { it.state.data.amount } companion object { private fun Collection>.filterCashStateAndRefs(): List> { - return this.map { stateAndRef -> + return this.mapNotNull { stateAndRef -> if (stateAndRef.state.data is Cash.State) { // Kotlin doesn't unify here for some reason uncheckedCast, StateAndRef>(stateAndRef) } else { null } - }.filterNotNull() + } } } - } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt index 2f5b11726b..e06f546094 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt @@ -10,16 +10,7 @@ package net.corda.client.jfx.model -import javafx.beans.property.ObjectProperty -import javafx.beans.value.ObservableValue -import javafx.beans.value.WritableValue -import javafx.collections.ObservableList import net.corda.core.internal.uncheckedCast -import org.reactfx.EventSink -import org.reactfx.EventStream -import rx.Observable -import rx.Observer -import rx.subjects.Subject import java.util.* import kotlin.reflect.KClass @@ -84,7 +75,7 @@ object Models { fun initModel(klass: KClass) = modelStore.getOrPut(klass) { klass.java.newInstance() } fun get(klass: KClass, origin: KClass<*>): M { - dependencyGraph.getOrPut(origin) { mutableSetOf>() }.add(klass) + dependencyGraph.getOrPut(origin) { mutableSetOf() }.add(klass) val model = initModel(klass) if (model.javaClass != klass.java) { throw IllegalStateException("Model stored as ${klass.qualifiedName} has type ${model.javaClass}") diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt index d815488ec5..a4bf873789 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt @@ -21,7 +21,6 @@ import org.reactfx.EventStream import rx.Observable import rx.Observer import rx.subjects.Subject -import kotlin.reflect.KClass inline fun observable(noinline observableProperty: (M) -> Observable) = TrackedDelegate.ObservableDelegate(M::class, observableProperty) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt index c4245ae4bb..dbcd55e440 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt @@ -32,7 +32,7 @@ class NetworkIdentityModel { else -> false } } - if(update is MapChange.Modified || update is MapChange.Added){ + if (update is MapChange.Modified || update is MapChange.Added) { list.addAll(update.node) } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt index b8f8486b71..95482e8dfb 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt @@ -95,8 +95,8 @@ class TransactionDataModel { private val transactions by observable(NodeMonitorModel::transactions) private val collectedTransactions = transactions.recordInSequence().distinctBy { it.id } private val vaultUpdates by observable(NodeMonitorModel::vaultUpdates) - private val stateMap = vaultUpdates.fold(FXCollections.observableHashMap>()) { map, update -> - val states = update.consumed + update.produced + private val stateMap = vaultUpdates.fold(FXCollections.observableHashMap>()) { map, (consumed, produced) -> + val states = consumed + produced states.forEach { map[it.ref] = it } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt index 3eb6de6500..383e903694 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt @@ -80,21 +80,25 @@ class AggregatedList( override fun sourceChanged(c: ListChangeListener.Change) { beginChange() while (c.next()) { - if (c.wasPermutated()) { - // Permutation should not change aggregation - } else if (c.wasUpdated()) { - // Update should not change aggregation - } else { - for (removedSourceItem in c.removed) { - val removedPair = removeItem(removedSourceItem) - if (removedPair != null) { - nextRemove(removedPair.first, removedPair.second.value) - } + when { + c.wasPermutated() -> { + // Permutation should not change aggregation } - for (addedItem in c.addedSubList) { - val insertIndex = addItem(addedItem) - if (insertIndex != null) { - nextAdd(insertIndex, insertIndex + 1) + c.wasUpdated() -> { + // Update should not change aggregation + } + else -> { + for (removedSourceItem in c.removed) { + val removedPair = removeItem(removedSourceItem) + if (removedPair != null) { + nextRemove(removedPair.first, removedPair.second.value) + } + } + for (addedItem in c.addedSubList) { + val insertIndex = addItem(addedItem) + if (insertIndex != null) { + nextAdd(insertIndex, insertIndex + 1) + } } } } 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 e5bfc618f7..79839a734c 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 @@ -16,6 +16,7 @@ import javafx.collections.ObservableList import net.corda.client.jfx.model.ExchangeRate import net.corda.core.contracts.Amount import org.fxmisc.easybind.EasyBind +import org.fxmisc.easybind.monadic.MonadicBinding import java.util.* import java.util.stream.Collectors @@ -23,7 +24,7 @@ import java.util.stream.Collectors * Utility bindings for the [Amount] type, similar in spirit to [Bindings] */ object AmountBindings { - fun sum(amounts: ObservableList>, token: T) = EasyBind.map( + fun sum(amounts: ObservableList>, token: T): MonadicBinding> = EasyBind.map( Bindings.createLongBinding({ amounts.stream().collect(Collectors.summingLong { require(it.token == token) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt index 698a3e1c64..6b9b696803 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt @@ -31,35 +31,39 @@ class AssociatedList( init { sourceList.forEach { val key = toKey(it) - backingMap.set(key, Pair(assemble(key, it), Unit)) + backingMap[key] = Pair(assemble(key, it), Unit) } sourceList.addListener { change: ListChangeListener.Change -> while (change.next()) { - if (change.wasPermutated()) { - } else if (change.wasUpdated()) { - } else { - val removedSourceMap = change.removed.associateBy(toKey) - val addedSourceMap = change.addedSubList.associateBy(toKey) - val removedMap = HashMap() - val addedMap = HashMap() - removedSourceMap.forEach { - val removed = backingMap.remove(it.key)?.first - removed ?: throw IllegalStateException("Removed list does not associate") - removedMap.put(it.key, removed) + when { + change.wasPermutated() -> { } - addedSourceMap.forEach { - val oldValue = backingMap.get(it.key) - val newValue = if (oldValue == null) { - assemble(it.key, it.value) - } else { - throw IllegalStateException("Several elements associated with same key") + change.wasUpdated() -> { + } + else -> { + val removedSourceMap = change.removed.associateBy(toKey) + val addedSourceMap = change.addedSubList.associateBy(toKey) + val removedMap = HashMap() + val addedMap = HashMap() + removedSourceMap.forEach { + val removed = backingMap.remove(it.key)?.first + removed ?: throw IllegalStateException("Removed list does not associate") + removedMap.put(it.key, removed) + } + addedSourceMap.forEach { + val oldValue = backingMap.get(it.key) + val newValue = if (oldValue == null) { + assemble(it.key, it.value) + } else { + throw IllegalStateException("Several elements associated with same key") + } + backingMap.put(it.key, Pair(newValue, Unit)) + addedMap.put(it.key, newValue) + } + val keys = removedMap.keys + addedMap.keys + keys.forEach { key -> + fireChange(createMapChange(key, removedMap.get(key), addedMap.get(key))) } - backingMap.put(it.key, Pair(newValue, Unit)) - addedMap.put(it.key, newValue) - } - val keys = removedMap.keys + addedMap.keys - keys.forEach { key -> - fireChange(createMapChange(key, removedMap.get(key), addedMap.get(key))) } } } 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 06a5b027ca..b48076ab83 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 @@ -37,9 +37,7 @@ class ChosenList( private var currentList = chosenListObservable.value - private val listener = object : ListChangeListener { - override fun onChanged(change: ListChangeListener.Change) = fireChange(change) - } + private val listener = ListChangeListener { change -> fireChange(change) } init { chosenListObservable.addListener { _: Observable -> rechoose() } @@ -49,7 +47,7 @@ class ChosenList( endChange() } - override fun get(index: Int) = currentList.get(index) + override fun get(index: Int): E = currentList[index] override val size: Int get() = currentList.size private fun rechoose() { diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt index 44b8508ad4..9eacecd34d 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt @@ -62,10 +62,10 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans } private fun startingOffsetOf(listIndex: Int): Int { - if (listIndex == 0) { - return 0 + return if (listIndex == 0) { + 0 } else { - return nestedIndexOffsets[listIndex - 1] + nestedIndexOffsets[listIndex - 1] } } @@ -84,11 +84,11 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans // firstTouched is the result list index of the beginning of the permutation. val firstTouched = startingOffset + change.from // We first set the non-permuted indices. - for (i in 0..firstTouched - 1) { + for (i in 0 until firstTouched) { permutation[i] = i } // Then the permuted ones. - for (i in firstTouched..startingOffset + change.to - 1) { + for (i in firstTouched until startingOffset + change.to) { permutation[startingOffset + i] = change.getPermutation(i) } nextPermutation(firstTouched, startingOffset + change.to, permutation) @@ -97,7 +97,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans // by the startingOffsetOf the nested list. val listIndex = indexMap[wrapped]!!.first val startingOffset = startingOffsetOf(listIndex) - for (i in change.from..change.to - 1) { + for (i in change.from until change.to) { nextUpdate(startingOffset + i) } } else { @@ -154,7 +154,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans val newSubNestedIndexOffsets = IntArray(change.to - change.from) val firstTouched = if (change.from == 0) 0 else nestedIndexOffsets[change.from - 1] var currentOffset = firstTouched - for (i in 0..change.to - change.from - 1) { + for (i in 0 until change.to - change.from) { currentOffset += source[change.from + i].size newSubNestedIndexOffsets[i] = currentOffset } @@ -162,24 +162,24 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans val concatenatedPermutation = IntArray(newSubNestedIndexOffsets.last()) // Set the non-permuted part var offset = 0 - for (i in 0..change.from - 1) { + for (i in 0 until change.from) { val nestedList = source[i] - for (j in offset..offset + nestedList.size - 1) { + for (j in offset until offset + nestedList.size) { concatenatedPermutation[j] = j } offset += nestedList.size } // Now the permuted part - for (i in 0..newSubNestedIndexOffsets.size - 1) { + for (i in 0 until newSubNestedIndexOffsets.size) { val startingOffset = startingOffsetOf(change.from + i) val permutedListIndex = change.getPermutation(change.from + i) val permutedOffset = (if (permutedListIndex == 0) 0 else newSubNestedIndexOffsets[permutedListIndex - 1]) - for (j in 0..source[permutedListIndex].size - 1) { + for (j in 0 until source[permutedListIndex].size) { concatenatedPermutation[startingOffset + j] = permutedOffset + j } } // Record permuted offsets - for (i in 0..newSubNestedIndexOffsets.size - 1) { + for (i in 0 until newSubNestedIndexOffsets.size) { nestedIndexOffsets[change.from + i] = newSubNestedIndexOffsets[i] } nextPermutation(firstTouched, newSubNestedIndexOffsets.last(), concatenatedPermutation) @@ -248,7 +248,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans if (firstInvalidatedPosition < source.size) { val firstInvalid = firstInvalidatedPosition var offset = if (firstInvalid == 0) 0 else nestedIndexOffsets[firstInvalid - 1] - for (i in firstInvalid..source.size - 1) { + for (i in firstInvalid until source.size) { offset += source[i].size if (i < nestedIndexOffsets.size) { nestedIndexOffsets[i] = offset @@ -266,10 +266,10 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans override val size: Int get() { recalculateOffsets() - if (nestedIndexOffsets.size > 0) { - return nestedIndexOffsets.last() + return if (nestedIndexOffsets.size > 0) { + nestedIndexOffsets.last() } else { - return 0 + 0 } } @@ -283,17 +283,17 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans comparison = { offset -> compareValues(offset, index) } ) - if (listIndex >= 0) { + return if (listIndex >= 0) { var nonEmptyListIndex = listIndex + 1 while (source[nonEmptyListIndex].isEmpty()) { nonEmptyListIndex++ } - return source[nonEmptyListIndex][0] + source[nonEmptyListIndex][0] } else { // The element is in the range of this list val rangeListIndex = -listIndex - 1 val subListOffset = index - startingOffsetOf(rangeListIndex) - return source[rangeListIndex][subListOffset] + source[rangeListIndex][subListOffset] } } 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 9f9e1646e8..b47fd31987 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 @@ -65,7 +65,7 @@ class FlattenedList(val sourceList: ObservableList val from = c.from val to = c.to val permutation = IntArray(to, { c.getPermutation(it) }) - indexMap.replaceAll { _, pair -> Pair(permutation[pair.first], pair.second) } + indexMap.replaceAll { _, (first, second) -> Pair(permutation[first], second) } nextPermutation(from, to, permutation) } else if (c.wasUpdated()) { throw UnsupportedOperationException("FlattenedList doesn't support Update changes") @@ -119,7 +119,7 @@ class FlattenedList(val sourceList: ObservableList assert(sourceList.size == indexMap.size) } - override fun get(index: Int) = sourceList.get(index).value + override fun get(index: Int): A = sourceList[index].value override fun getSourceIndex(index: Int) = index diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt index 074c7d44c1..65c0ee2f46 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt @@ -26,8 +26,8 @@ class LeftOuterJoinedMap( ) : ReadOnlyBackedObservableMapBase>() { init { leftTable.forEach { entry -> - val rightValueProperty = SimpleObjectProperty(rightTable.get(entry.key)) - backingMap.set(entry.key, Pair(assemble(entry.key, entry.value, rightValueProperty), rightValueProperty)) + val rightValueProperty = SimpleObjectProperty(rightTable[entry.key]) + backingMap[entry.key] = Pair(assemble(entry.key, entry.value, rightValueProperty), rightValueProperty) } leftTable.addListener { change: MapChangeListener.Change -> @@ -39,10 +39,10 @@ class LeftOuterJoinedMap( } if (change.wasAdded()) { - val rightValue = rightTable.get(change.key) + val rightValue = rightTable[change.key] val rightValueProperty = SimpleObjectProperty(rightValue) val newValue = assemble(change.key, change.valueAdded, rightValueProperty) - backingMap.set(change.key, Pair(newValue, rightValueProperty)) + backingMap[change.key] = Pair(newValue, rightValueProperty) addedValue = newValue } @@ -50,11 +50,11 @@ class LeftOuterJoinedMap( } rightTable.addListener { change: MapChangeListener.Change -> if (change.wasRemoved() && !change.wasAdded()) { - backingMap.get(change.key)?.second?.set(null) + backingMap[change.key]?.second?.set(null) } if (change.wasAdded()) { - backingMap.get(change.key)?.second?.set(change.valueAdded) + backingMap[change.key]?.second?.set(change.valueAdded) } } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt index 95906337f3..874729bb09 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt @@ -15,7 +15,6 @@ import javafx.collections.ObservableList import javafx.collections.transformation.TransformationList import java.util.* - /** * This is a variant of [EasyBind.map] where the mapped list is backed, therefore the mapping function will only be run * when an element is inserted or updated. 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 d8be074ba2..3afbfc82d2 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 @@ -40,7 +40,7 @@ private fun onError(th: Throwable) { */ fun Observable.foldToObservableValue(initial: B, folderFun: (A, B) -> B): ObservableValue { val result = SimpleObjectProperty(initial) - subscribe ({ + subscribe({ Platform.runLater { result.set(folderFun(it, result.get())) } 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 58f944ba61..a133c823a1 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 @@ -52,10 +52,10 @@ fun ObservableValue.map(function: (A) -> B): ObservableValue = * re-run the function. */ fun ObservableList.map(cached: Boolean = true, function: (A) -> B): ObservableList { - if (cached) { - return MappedList(this, function) + return if (cached) { + MappedList(this, function) } else { - return EasyBind.map(this, function) + EasyBind.map(this, function) } } @@ -130,11 +130,7 @@ fun ObservableList.filter(predicate: ObservableValue<(A) -> Boolean>) */ fun ObservableList.filterNotNull(): ObservableList { //TODO This is a tactical work round for an issue with SAM conversion (https://youtrack.jetbrains.com/issue/ALL-1552) so that the M10 explorer works. - return uncheckedCast(uncheckedCast>(this).filtered(object : Predicate { - override fun test(t: A?): Boolean { - return t != null - } - })) + return uncheckedCast(uncheckedCast>(this).filtered { t -> t != null }) } /** @@ -257,8 +253,8 @@ fun ObservableList.leftOuterJoin( assemble: (A, ObservableList) -> C ): ObservableList { val joinedMap = leftOuterJoin(rightTable, leftToJoinKey, rightToJoinKey) - return joinedMap.getObservableValues().map { pair -> - pair.first.map { assemble(it, pair.second) } + return joinedMap.getObservableValues().map { (first, second) -> + first.map { assemble(it, second) } }.concatenate() } @@ -281,11 +277,9 @@ fun ObservableList.leftOuterJoin( ): ObservableMap, ObservableList>> { val leftTableMap = associateByAggregation(leftToJoinKey) val rightTableMap = rightTable.associateByAggregation(rightToJoinKey) - val joinedMap: ObservableMap, ObservableList>> = - LeftOuterJoinedMap(leftTableMap, rightTableMap) { _, left, rightValue -> - Pair(left, ChosenList(rightValue.map { it ?: FXCollections.emptyObservableList() }, "ChosenList from leftOuterJoin")) - } - return joinedMap + return LeftOuterJoinedMap(leftTableMap, rightTableMap) { _, left, rightValue -> + Pair(left, ChosenList(rightValue.map { it ?: FXCollections.emptyObservableList() }, "ChosenList from leftOuterJoin")) + } } fun ObservableList.getValueAt(index: Int): ObservableValue { diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt index a906248b4d..138f4c0d07 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt @@ -56,7 +56,7 @@ open class ReadOnlyBackedObservableMapBase : ObservableMap { override fun containsValue(value: A) = backingMap.any { it.value.first == value } - override fun get(key: K) = backingMap.get(key)?.first + override fun get(key: K) = backingMap[key]?.first override fun isEmpty() = backingMap.isEmpty() diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt index 139d4e4f27..28ce0ccc22 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt @@ -43,14 +43,14 @@ class ReplayedList(sourceList: ObservableList) : TransformationList( } nextPermutation(from, to, permutation) } else if (c.wasUpdated()) { - for (i in c.from..c.to - 1) { + for (i in c.from until c.to) { replayedList[i] = c.list[i] nextUpdate(i) } } else { if (c.wasRemoved()) { val removePosition = c.from - for (i in 0..c.removedSize - 1) { + for (i in 0 until c.removedSize) { replayedList.removeAt(removePosition) } nextRemove(c.from, c.removed) @@ -58,7 +58,7 @@ class ReplayedList(sourceList: ObservableList) : TransformationList( if (c.wasAdded()) { val addStart = c.from val addEnd = c.to - for (i in addStart..addEnd - 1) { + for (i in addStart until addEnd) { replayedList.add(i, c.list[i]) } nextAdd(addStart, addEnd) diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt index 175068c1d8..75f2540c6f 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt @@ -29,9 +29,10 @@ class ExchangeRateModelTest { private fun assertEquals(one: Amount, another: Amount) { assertEquals(one.token, another.token) - assertTrue("$one != $another", {(one.toDecimal() - another.toDecimal()).abs() < BigDecimal(0.01) }) + assertTrue("$one != $another", { (one.toDecimal() - another.toDecimal()).abs() < BigDecimal(0.01) }) } } + @Test fun `perform fx testing`() { val tenSwissies = Amount(10, BigDecimal.ONE, CHF) diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt index 2e422bb120..d161f1b2c4 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt @@ -19,9 +19,9 @@ import kotlin.test.fail class AggregatedListTest { - lateinit var sourceList: ObservableList - lateinit var aggregatedList: ObservableList>> - lateinit var replayedList: ObservableList>> + private lateinit var sourceList: ObservableList + private lateinit var aggregatedList: ObservableList>> + private lateinit var replayedList: ObservableList>> @Before fun setup() { diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt index 4077d629d7..607851fd42 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt @@ -34,14 +34,13 @@ class ConcatenatedListTest { fun ConcatenatedList.checkInvariants() { assertEquals(nestedIndexOffsets.size, source.size) var currentOffset = 0 - for (i in 0..source.size - 1) { + for (i in 0 until source.size) { currentOffset += source[i].size assertEquals(nestedIndexOffsets[i], currentOffset) } assertEquals(indexMap.size, source.size) - for (entry in indexMap) { - val (wrapped, pair) = entry + for ((wrapped, pair) in indexMap) { val index = pair.first val foundListIndices = ArrayList() source.forEachIndexed { i, list -> @@ -134,11 +133,7 @@ class ConcatenatedListTest { assertEquals(replayedList[2], "b") assertEquals(replayedList[3], "c") - sourceList.sortWith(object : Comparator> { - override fun compare(p0: ObservableList, p1: ObservableList): Int { - return p0.size - p1.size - } - }) + sourceList.sortWith(Comparator> { p0, p1 -> p0.size - p1.size }) concatenatedList.checkInvariants() assertEquals(replayedList.size, 4) assertEquals(replayedList[0], "hello") @@ -147,11 +142,7 @@ class ConcatenatedListTest { assertEquals(replayedList[3], "b") sourceList.add(0, FXCollections.observableArrayList("d", "e", "f")) - sourceList.sortWith(object : Comparator> { - override fun compare(p0: ObservableList, p1: ObservableList): Int { - return p0.size - p1.size - } - }) + sourceList.sortWith(Comparator> { p0, p1 -> p0.size - p1.size }) concatenatedList.checkInvariants() assertEquals(replayedList.size, 7) assertEquals(replayedList[0], "hello") diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt index 2335caf5e8..b09934d2d9 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt @@ -44,7 +44,6 @@ class MappedListTest { assertEquals(replayedList[0], 7) assertEquals(replayedList[1], 5) assertEquals(replayedList[2], 3) - } @Test diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt index 39ec817d88..4ee8679c2f 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt @@ -20,14 +20,14 @@ import kotlin.test.assertEquals class ReplayedMap(sourceMap: ObservableMap) : ReadOnlyBackedObservableMapBase() { init { sourceMap.forEach { - backingMap.set(it.key, Pair(it.value, Unit)) + backingMap[it.key] = Pair(it.value, Unit) } sourceMap.addListener { change: MapChangeListener.Change -> if (change.wasRemoved()) { assertEquals(backingMap.remove(change.key)!!.first, change.valueRemoved) } if (change.wasAdded()) { - backingMap.set(change.key, Pair(change.valueAdded, Unit)) + backingMap[change.key] = Pair(change.valueAdded, Unit) } fireChange(change) } diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt index 61c436939d..c5984172ae 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt @@ -52,5 +52,5 @@ fun CordaRPCOps.drainAndShutdown(): Observable { .doOnError { error -> throw error } - .doOnCompleted { shutdown() }.map { } + .doOnCompleted { shutdown() }.map { } } \ No newline at end of file diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt index 564e378287..867db59306 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt @@ -11,10 +11,6 @@ package net.corda.client.rpc.internal import co.paralleluniverse.common.util.SameThreadExecutor -import com.esotericsoftware.kryo.Kryo -import com.esotericsoftware.kryo.Serializer -import com.esotericsoftware.kryo.io.Input -import com.esotericsoftware.kryo.io.Output import com.github.benmanes.caffeine.cache.Cache import com.github.benmanes.caffeine.cache.Caffeine import com.github.benmanes.caffeine.cache.RemovalCause @@ -44,18 +40,27 @@ import net.corda.nodeapi.internal.DeduplicationChecker import org.apache.activemq.artemis.api.core.ActiveMQException import org.apache.activemq.artemis.api.core.RoutingType import org.apache.activemq.artemis.api.core.SimpleString -import org.apache.activemq.artemis.api.core.client.* import org.apache.activemq.artemis.api.core.client.ActiveMQClient.DEFAULT_ACK_BATCH_SIZE +import org.apache.activemq.artemis.api.core.client.ClientConsumer +import org.apache.activemq.artemis.api.core.client.ClientMessage +import org.apache.activemq.artemis.api.core.client.ClientProducer +import org.apache.activemq.artemis.api.core.client.ClientSession +import org.apache.activemq.artemis.api.core.client.ClientSessionFactory +import org.apache.activemq.artemis.api.core.client.FailoverEventType +import org.apache.activemq.artemis.api.core.client.ServerLocator import rx.Notification import rx.Observable import rx.subjects.UnicastSubject import java.lang.reflect.InvocationHandler import java.lang.reflect.Method -import java.time.Instant import java.util.* -import java.util.concurrent.* +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.ScheduledExecutorService +import java.util.concurrent.ScheduledFuture +import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import kotlin.reflect.jvm.javaMethod @@ -162,7 +167,7 @@ class RPCClientProxyHandler( private val serializationContextWithObservableContext = RpcClientObservableSerializer.createContext(serializationContext, observableContext) private fun createRpcObservableMap(): RpcObservableMap { - val onObservableRemove = RemovalListener>> { key, value, cause -> + val onObservableRemove = RemovalListener>> { key, _, cause -> val observableId = key!! val rpcCallSite = callSiteMap?.remove(observableId) if (cause == RemovalCause.COLLECTED) { @@ -454,7 +459,7 @@ class RPCClientProxyHandler( log.debug("Trying to connect using ${transport.params}") try { - if (serverLocator != null && !serverLocator.isClosed) { + if (!serverLocator.isClosed) { sessionFactory = serverLocator.createSessionFactory(transport) } else { log.warn("Stopping reconnect attempts.") diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt index 6a916cb28b..3b8f7e4fdb 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt @@ -55,7 +55,6 @@ class KryoClientSerializationScheme : AbstractKryoSerializationScheme() { }, if (classLoader != null) AMQP_P2P_CONTEXT.withClassLoader(classLoader) else AMQP_P2P_CONTEXT, rpcClientContext = if (classLoader != null) KRYO_RPC_CLIENT_CONTEXT.withClassLoader(classLoader) else KRYO_RPC_CLIENT_CONTEXT) - } } } \ No newline at end of file diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt index 2a8f6f5283..99749093e2 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt @@ -57,7 +57,7 @@ object RpcClientObservableSerializer : Serializer>() { }.dematerialize() } - private fun Input.readInvocationId() : Trace.InvocationId? { + private fun Input.readInvocationId(): Trace.InvocationId? { val value = readString() ?: return null val timestamp = readLong() diff --git a/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt b/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt index 49171bae25..1828ec0746 100644 --- a/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt +++ b/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt @@ -228,7 +228,7 @@ class StandaloneCordaRPClientTest { flowHandle.returnValue.get() val balance = rpcProxy.getCashBalance(USD) - println("Balance: " + balance) + println("Balance: $balance") assertEquals(629.DOLLARS, balance) } diff --git a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt index 2245f5bea4..72f2cb29a1 100644 --- a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt +++ b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt @@ -59,7 +59,7 @@ class RPCConcurrencyTests : AbstractRPCTest() { override fun newLatch(numberOfDowns: Int): Long { val id = random63BitValue() val latch = CountDownLatch(numberOfDowns) - latches.put(id, latch) + latches[id] = latch return id } diff --git a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt index 0ec213a441..f55a4b012a 100644 --- a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt +++ b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt @@ -68,7 +68,7 @@ class RPCFailureTests { } @Test - fun `unserializable`() = rpc { + fun unserializable() = rpc { assertThatThrownBy { it.getUnserializable() }.isInstanceOf(KryoException::class.java) } diff --git a/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt b/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt index 3d7521a6a9..8ca74715f2 100644 --- a/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt +++ b/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt @@ -16,11 +16,11 @@ class RepeatingBytesInputStream(val bytesToRepeat: ByteArray, val numberOfBytes: private var bytesLeft = numberOfBytes override fun available() = bytesLeft override fun read(): Int { - if (bytesLeft == 0) { - return -1 + return if (bytesLeft == 0) { + -1 } else { bytesLeft-- - return bytesToRepeat[(numberOfBytes - bytesLeft) % bytesToRepeat.size].toInt() + bytesToRepeat[(numberOfBytes - bytesLeft) % bytesToRepeat.size].toInt() } } diff --git a/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt b/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt index d5ce6b4d09..8714f3fd80 100644 --- a/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt +++ b/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt @@ -90,7 +90,7 @@ class SwapIdentitiesFlow(private val otherParty: Party, // TODO: for increased privacy, we should create one anonymous key per output state. val identities = LinkedHashMap() if (serviceHub.myInfo.isLegalIdentity(otherParty)) { - identities.put(otherParty, legalIdentityAnonymous.party.anonymise()) + identities[otherParty] = legalIdentityAnonymous.party.anonymise() } else { val otherSession = initiateFlow(otherParty) val data = buildDataToSign(legalIdentityAnonymous) diff --git a/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt b/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt index 8b9c936faf..c1bb1f7b9b 100644 --- a/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt +++ b/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt @@ -119,7 +119,7 @@ class IdentitySyncFlowTests { * Very lightweight wrapping flow to trigger the counterparty flow that receives the identities. */ @InitiatingFlow - class Initiator(private val otherSide: Party, private val tx: WireTransaction): FlowLogic() { + class Initiator(private val otherSide: Party, private val tx: WireTransaction) : FlowLogic() { @Suspendable override fun call(): Boolean { val session = initiateFlow(otherSide) @@ -130,7 +130,7 @@ class IdentitySyncFlowTests { } @InitiatedBy(IdentitySyncFlowTests.Initiator::class) - class Receive(private val otherSideSession: FlowSession): FlowLogic() { + class Receive(private val otherSideSession: FlowSession) : FlowLogic() { @Suspendable override fun call() { subFlow(IdentitySyncFlow.Receive(otherSideSession)) diff --git a/core/src/main/java/net/corda/core/crypto/Base58.java b/core/src/main/java/net/corda/core/crypto/Base58.java index 1a4f8bc63e..23840eb3f3 100644 --- a/core/src/main/java/net/corda/core/crypto/Base58.java +++ b/core/src/main/java/net/corda/core/crypto/Base58.java @@ -93,7 +93,7 @@ public class Base58 { * @throws AddressFormatException if the given string is not a valid base58 string */ public static byte[] decode(String input) throws AddressFormatException { - if (input.length() == 0) { + if (input.isEmpty()) { return new byte[0]; } // Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits). diff --git a/core/src/main/java/net/corda/core/flows/IdentifiableException.java b/core/src/main/java/net/corda/core/flows/IdentifiableException.java index d440022619..e6d7c78f91 100644 --- a/core/src/main/java/net/corda/core/flows/IdentifiableException.java +++ b/core/src/main/java/net/corda/core/flows/IdentifiableException.java @@ -20,7 +20,8 @@ public interface IdentifiableException { /** * @return the ID of the error, or null if the error doesn't have it set (yet). */ - default @Nullable Long getErrorId() { + @Nullable + default Long getErrorId() { return null; } } diff --git a/core/src/main/kotlin/net/corda/core/CordaOID.kt b/core/src/main/kotlin/net/corda/core/CordaOID.kt index 6056d697db..0682861acd 100644 --- a/core/src/main/kotlin/net/corda/core/CordaOID.kt +++ b/core/src/main/kotlin/net/corda/core/CordaOID.kt @@ -18,10 +18,10 @@ object CordaOID { /** Assigned to R3, see http://www.oid-info.com/cgi-bin/display?oid=1.3.6.1.4.1.50530&action=display */ const val R3_ROOT = "1.3.6.1.4.1.50530" /** OIDs issued for the Corda platform */ - const val CORDA_PLATFORM = R3_ROOT + ".1" + const val CORDA_PLATFORM = "$R3_ROOT.1" /** * Identifier for the X.509 certificate extension specifying the Corda role. See * https://r3-cev.atlassian.net/wiki/spaces/AWG/pages/156860572/Certificate+identity+type+extension for details. */ - const val X509_EXTENSION_CORDA_ROLE = CORDA_PLATFORM + ".1" + const val X509_EXTENSION_CORDA_ROLE = "$CORDA_PLATFORM.1" } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt b/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt index 3fd0e825e3..59451d8134 100644 --- a/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt +++ b/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt @@ -46,12 +46,12 @@ internal fun firstOf(futures: Array>, log: Logger, val winnerChosen = AtomicBoolean() futures.forEach { it.then { - if (winnerChosen.compareAndSet(false, true)) { - resultFuture.capture { handler(it) } - } else if (it.isCancelled) { - // Do nothing. - } else { - it.match({}, { log.error(shortCircuitedTaskFailedMessage, it) }) + when { + winnerChosen.compareAndSet(false, true) -> resultFuture.capture { handler(it) } + it.isCancelled -> { + // Do nothing. + } + else -> it.match({}, { log.error(shortCircuitedTaskFailedMessage, it) }) } } } diff --git a/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt b/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt index a62953a9c0..1ab15ecd8c 100644 --- a/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt +++ b/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt @@ -87,7 +87,6 @@ data class Actor(val id: Id, val serviceId: AuthServiceId, val owningLegalIdenti */ @CordaSerializable data class Id(val value: String) - } /** diff --git a/core/src/main/kotlin/net/corda/core/context/Trace.kt b/core/src/main/kotlin/net/corda/core/context/Trace.kt index e93256da29..de93fa9bd7 100644 --- a/core/src/main/kotlin/net/corda/core/context/Trace.kt +++ b/core/src/main/kotlin/net/corda/core/context/Trace.kt @@ -37,7 +37,7 @@ data class Trace(val invocationId: InvocationId, val sessionId: SessionId) { class InvocationId(value: String, timestamp: Instant) : Id(value, TYPE, timestamp) { companion object { - private val TYPE = "Invocation" + private const val TYPE = "Invocation" /** * Creates an invocation id using a [java.util.UUID] as value and [Instant.now] as timestamp. @@ -54,7 +54,7 @@ data class Trace(val invocationId: InvocationId, val sessionId: SessionId) { class SessionId(value: String, timestamp: Instant) : Id(value, TYPE, timestamp) { companion object { - private val TYPE = "Session" + private const val TYPE = "Session" /** * Creates a session id using a [java.util.UUID] as value and [Instant.now] as timestamp. diff --git a/core/src/main/kotlin/net/corda/core/contracts/Amount.kt b/core/src/main/kotlin/net/corda/core/contracts/Amount.kt index 94799b3253..2794deb617 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/Amount.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/Amount.kt @@ -260,7 +260,7 @@ data class Amount(val quantity: Long, val displayTokenSize: BigDecimal, val residualTokens = quantity - (commonTokensPerPartition * partitions) val splitAmount = Amount(commonTokensPerPartition, displayTokenSize, token) val splitAmountPlusOne = Amount(commonTokensPerPartition + 1L, displayTokenSize, token) - return (0..partitions - 1).map { if (it < residualTokens) splitAmountPlusOne else splitAmount }.toList() + return (0 until partitions).map { if (it < residualTokens) splitAmountPlusOne else splitAmount }.toList() } /** diff --git a/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt b/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt index 2294fec585..01635c169e 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt @@ -20,11 +20,11 @@ import net.corda.core.serialization.CordaSerializable * @property additionalContracts Additional contract names contained within the JAR. */ @CordaSerializable -class ContractAttachment @JvmOverloads constructor (val attachment: Attachment, val contract: ContractClassName, val additionalContracts: Set = emptySet(), val uploader: String? = null) : Attachment by attachment { +class ContractAttachment @JvmOverloads constructor(val attachment: Attachment, val contract: ContractClassName, val additionalContracts: Set = emptySet(), val uploader: String? = null) : Attachment by attachment { val allContracts: Set get() = additionalContracts + contract override fun toString(): String { - return "ContractAttachment(attachment=${attachment.id}, contracts='${allContracts}', uploader='${uploader}')" + return "ContractAttachment(attachment=${attachment.id}, contracts='$allContracts', uploader='$uploader')" } } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt index 6185eb7fa7..0a2c2e28a4 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt @@ -30,7 +30,7 @@ import java.util.* object Requirements { /** Throws [IllegalArgumentException] if the given expression evaluates to false. */ @Suppress("NOTHING_TO_INLINE") // Inlining this takes it out of our committed ABI. - infix inline fun String.using(expr: Boolean) { + inline infix fun String.using(expr: Boolean) { if (!expr) throw IllegalArgumentException("Failed requirement: $this") } } diff --git a/core/src/main/kotlin/net/corda/core/contracts/Structures.kt b/core/src/main/kotlin/net/corda/core/contracts/Structures.kt index e672218ab2..95d58e96f6 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/Structures.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/Structures.kt @@ -206,7 +206,7 @@ data class Command(val value: T, val signers: List) constructor(data: T, key: PublicKey) : this(data, listOf(key)) private fun commandDataToString() = value.toString().let { if (it.contains("@")) it.replace('$', '.').split("@")[0] else it } - override fun toString() = "${commandDataToString()} with pubkeys ${signers.map { it.toStringShort() }.joinToString()}" + override fun toString() = "${commandDataToString()} with pubkeys ${signers.joinToString { it.toStringShort() }}" } /** A common move command for contract states which can change owner. */ diff --git a/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt b/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt index 3bda4ab022..b97104fad2 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt @@ -52,7 +52,7 @@ sealed class TransactionVerificationException(val txId: SecureHash, message: Str * @property contractClass The fully qualified class name of the failing contract. */ class ContractRejection(txId: SecureHash, val contractClass: String, cause: Throwable) : TransactionVerificationException(txId, "Contract verification failed: ${cause.message}, contract: $contractClass", cause) { - constructor(txId: SecureHash, contract: Contract, cause: Throwable) : this(txId, contract.javaClass.name, cause) + constructor(txId: SecureHash, contract: Contract, cause: Throwable) : this(txId, contract.javaClass.name, cause) } /** @@ -118,8 +118,10 @@ sealed class TransactionVerificationException(val txId: SecureHash, message: Str /** Whether the inputs or outputs list contains an encumbrance issue, see [TransactionMissingEncumbranceException]. */ @CordaSerializable enum class Direction { - /** Issue in the inputs list */ INPUT, - /** Issue in the outputs list */ OUTPUT + /** Issue in the inputs list */ + INPUT, + /** Issue in the outputs list */ + OUTPUT } // We could revisit and throw this more appropriate type in a future release that uses targetVersion to diff --git a/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt b/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt index c46714ebfd..d2f2a4ba51 100644 --- a/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt +++ b/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt @@ -43,7 +43,7 @@ interface Cordapp { val contractClassNames: List val initiatedFlows: List>> val rpcFlows: List>> - val serviceFlows: List>> + val serviceFlows: List>> val schedulableFlows: List>> val services: List> val serializationWhitelists: List diff --git a/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt b/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt index a36106daee..64ee55f798 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt @@ -110,7 +110,7 @@ class CompositeKey private constructor(val threshold: Int, children: List() - visitedMap.put(this, true) + visitedMap[this] = true cycleDetection(visitedMap) // Graph cycle testing on the root node. checkConstraints() for ((node, _) in children) { @@ -281,15 +281,17 @@ class CompositeKey private constructor(val threshold: Int, children: List 0) val n = children.size - return if (n > 1) - CompositeKey(threshold ?: children.map { (_, weight) -> weight }.sum(), children) - else if (n == 1) { - require(threshold == null || threshold == children.first().weight) - { "Trying to build invalid CompositeKey, threshold value different than weight of single child node." } - // Returning the only child node which is [PublicKey] itself. We need to avoid single-key [CompositeKey] instances, - // as there are scenarios where developers expected the underlying key and its composite versions to be equivalent. - children.first().node - } else throw IllegalStateException("Trying to build CompositeKey without child nodes.") + return when { + n > 1 -> CompositeKey(threshold ?: children.map { (_, weight) -> weight }.sum(), children) + n == 1 -> { + require(threshold == null || threshold == children.first().weight) + { "Trying to build invalid CompositeKey, threshold value different than weight of single child node." } + // Returning the only child node which is [PublicKey] itself. We need to avoid single-key [CompositeKey] instances, + // as there are scenarios where developers expected the underlying key and its composite versions to be equivalent. + children.first().node + } + else -> throw IllegalStateException("Trying to build CompositeKey without child nodes.") + } } } } diff --git a/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt b/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt index 57fc19df79..850d4c5cf2 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt @@ -58,8 +58,8 @@ sealed class MerkleTree { * @return Tree root. */ private tailrec fun buildMerkleTree(lastNodesList: List): MerkleTree { - if (lastNodesList.size == 1) { - return lastNodesList[0] // Root reached. + return if (lastNodesList.size == 1) { + lastNodesList[0] // Root reached. } else { val newLevelHashes: MutableList = ArrayList() val n = lastNodesList.size @@ -71,7 +71,7 @@ sealed class MerkleTree { val combined = Node(newHash, left, right) newLevelHashes.add(combined) } - return buildMerkleTree(newLevelHashes) + buildMerkleTree(newLevelHashes) } } } diff --git a/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt b/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt index 142b19b9ac..2bd1b81586 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt @@ -28,5 +28,4 @@ object NullKeys { /** A signature with a key and value of zero. Useful when you want a signature object that you know won't ever be used. */ val NULL_SIGNATURE = TransactionSignature(ByteArray(32), NullPublicKey, SignatureMetadata(1, -1)) - } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt b/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt index b7885ad166..4bb8b5d3b7 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt @@ -46,7 +46,7 @@ open class SignedData(val raw: SerializedBytes, val sig: DigitalSign * @throws IllegalArgumentException if the data is invalid. */ @Throws(IllegalArgumentException::class) - open protected fun verifyData(data: T) { + protected open fun verifyData(data: T) { // By default we accept anything } } diff --git a/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt b/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt index ac8d815af6..354a8d71f0 100644 --- a/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt +++ b/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt @@ -80,7 +80,7 @@ abstract class AbstractStateReplacementFlow { val finalTx = stx + signatures serviceHub.recordTransactions(finalTx) - return stx.resolveBaseTransaction(serviceHub).outRef(0) + return stx.resolveBaseTransaction(serviceHub).outRef(0) } /** @@ -88,7 +88,7 @@ abstract class AbstractStateReplacementFlow { * * @return the transaction */ - abstract protected fun assembleTx(): UpgradeTx + protected abstract fun assembleTx(): UpgradeTx /** * Initiate sessions with parties we want signatures from. @@ -186,7 +186,7 @@ abstract class AbstractStateReplacementFlow { * The proposal is returned if acceptable, otherwise a [StateReplacementException] is thrown. */ @Throws(StateReplacementException::class) - abstract protected fun verifyProposal(stx: SignedTransaction, proposal: Proposal) + protected abstract fun verifyProposal(stx: SignedTransaction, proposal: Proposal) private fun checkMySignatureRequired(stx: SignedTransaction) { // TODO: use keys from the keyManagementService instead diff --git a/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt b/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt index d72e2d054e..7f1ae98290 100644 --- a/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt +++ b/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt @@ -88,7 +88,8 @@ class CollectSignaturesFlow @JvmOverloads constructor(val partiallySignedTx: Sig } - @Suspendable override fun call(): SignedTransaction { + @Suspendable + override fun call(): SignedTransaction { // Check the signatures which have already been provided and that the transaction is valid. // Usually just the Initiator and possibly an oracle would have signed at this point. val myKeys: Iterable = myOptionalKeys ?: listOf(ourIdentity.owningKey) @@ -216,7 +217,8 @@ abstract class SignTransactionFlow(val otherSideSession: FlowSession, fun tracker() = ProgressTracker(RECEIVING, VERIFYING, SIGNING) } - @Suspendable override fun call(): SignedTransaction { + @Suspendable + override fun call(): SignedTransaction { progressTracker.currentStep = RECEIVING // Receive transaction and resolve dependencies, check sufficient signatures is disabled as we don't have all signatures. val stx = subFlow(ReceiveTransactionFlow(otherSideSession, checkSufficientSignatures = false)) @@ -253,12 +255,13 @@ abstract class SignTransactionFlow(val otherSideSession: FlowSession, return stx + mySignatures } - @Suspendable private fun checkSignatures(stx: SignedTransaction) { + @Suspendable + private fun checkSignatures(stx: SignedTransaction) { // We set `ignoreUnrecognisedParties` to `true` in `groupPublicKeysByWellKnownParty`. This is because we don't // need to recognise all keys, but just the initiator's. val signingWellKnownIdentities = groupPublicKeysByWellKnownParty(serviceHub, stx.sigs.map(TransactionSignature::by), true) require(otherSideSession.counterparty in signingWellKnownIdentities) { - "The Initiator of CollectSignaturesFlow must have signed the transaction. Found ${signingWellKnownIdentities}, expected ${otherSideSession}" + "The Initiator of CollectSignaturesFlow must have signed the transaction. Found $signingWellKnownIdentities, expected $otherSideSession" } val signed = stx.sigs.map { it.by } val allSigners = stx.tx.requiredSigningKeys @@ -288,9 +291,10 @@ abstract class SignTransactionFlow(val otherSideSession: FlowSession, */ @Suspendable @Throws(FlowException::class) - abstract protected fun checkTransaction(stx: SignedTransaction) + protected abstract fun checkTransaction(stx: SignedTransaction) - @Suspendable private fun checkMySignaturesRequired(stx: SignedTransaction, signingKeys: Iterable) { + @Suspendable + private fun checkMySignaturesRequired(stx: SignedTransaction, signingKeys: Iterable) { require(signingKeys.all { it in stx.tx.requiredSigningKeys }) { "A signature was requested for a key that isn't part of the required signing keys for transaction ${stx.id}" } diff --git a/core/src/main/kotlin/net/corda/core/flows/FlowException.kt b/core/src/main/kotlin/net/corda/core/flows/FlowException.kt index 6b12775f20..ccc50081dd 100644 --- a/core/src/main/kotlin/net/corda/core/flows/FlowException.kt +++ b/core/src/main/kotlin/net/corda/core/flows/FlowException.kt @@ -36,6 +36,7 @@ open class FlowException(message: String?, cause: Throwable?) : constructor(message: String?) : this(message, null) constructor(cause: Throwable?) : this(cause?.toString(), cause) constructor() : this(null, null) + var originalErrorId: Long? = null override fun getErrorId(): Long? = originalErrorId } @@ -50,5 +51,6 @@ class UnexpectedFlowEndException(message: String, cause: Throwable?, val origina CordaRuntimeException(message, cause), IdentifiableException { constructor(message: String, cause: Throwable?) : this(message, cause, null) constructor(message: String) : this(message, null) + override fun getErrorId(): Long? = originalErrorId } diff --git a/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt b/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt index 7b7b627155..99d70063cc 100644 --- a/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt +++ b/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt @@ -60,20 +60,21 @@ sealed class FlowInitiator : Principal { * class hierarchy (which is now deprecated). The returned object has less information than it could have, so * prefer to use fetch an invocation context directly if you can (e.g. in [net.corda.core.messaging.StateMachineInfo]) */ - val invocationContext: InvocationContext get() { - val unknownName = CordaX500Name("UNKNOWN", "UNKNOWN", "GB") - var actor: Actor? = null - val origin: InvocationOrigin - when (this) { - is FlowInitiator.RPC -> { - actor = Actor(Actor.Id(this.username), AuthServiceId("UNKNOWN"), unknownName) - origin = InvocationOrigin.RPC(actor) + val invocationContext: InvocationContext + get() { + val unknownName = CordaX500Name("UNKNOWN", "UNKNOWN", "GB") + var actor: Actor? = null + val origin: InvocationOrigin + when (this) { + is FlowInitiator.RPC -> { + actor = Actor(Actor.Id(this.username), AuthServiceId("UNKNOWN"), unknownName) + origin = InvocationOrigin.RPC(actor) + } + is FlowInitiator.Peer -> origin = InvocationOrigin.Peer(this.party.name) + is FlowInitiator.Service -> origin = InvocationOrigin.Service(this.serviceClassName, unknownName) + FlowInitiator.Shell -> origin = InvocationOrigin.Shell + is FlowInitiator.Scheduled -> origin = InvocationOrigin.Scheduled(this.scheduledState) } - is FlowInitiator.Peer -> origin = InvocationOrigin.Peer(this.party.name) - is FlowInitiator.Service -> origin = InvocationOrigin.Service(this.serviceClassName, unknownName) - FlowInitiator.Shell -> origin = InvocationOrigin.Shell - is FlowInitiator.Scheduled -> origin = InvocationOrigin.Scheduled(this.scheduledState) + return InvocationContext.newInstance(origin = origin, actor = actor) } - return InvocationContext.newInstance(origin = origin, actor = actor) - } } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt b/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt index a860bb6867..57b80a45ba 100644 --- a/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt +++ b/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt @@ -128,9 +128,10 @@ data class CordaX500Name(val commonName: String?, private var _x500Principal: X500Principal? = null /** Return the [X500Principal] equivalent of this name. */ - val x500Principal: X500Principal get() { - return _x500Principal ?: X500Principal(this.x500Name.encoded).also { _x500Principal = it } - } + val x500Principal: X500Principal + get() { + return _x500Principal ?: X500Principal(this.x500Name.encoded).also { _x500Principal = it } + } override fun toString(): String = x500Principal.toString() } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/internal/Emoji.kt b/core/src/main/kotlin/net/corda/core/internal/Emoji.kt index c1c377a4d0..17268d86f5 100644 --- a/core/src/main/kotlin/net/corda/core/internal/Emoji.kt +++ b/core/src/main/kotlin/net/corda/core/internal/Emoji.kt @@ -60,7 +60,6 @@ object Emoji { @JvmStatic val CODE_WARNING_SIGN: String = codePointsString(0x26A0, 0xFE0F) - /** * When non-null, toString() methods are allowed to use emoji in the output as we're going to render them to a * sufficiently capable text surface. diff --git a/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt b/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt index f9784dc3dd..f007d56767 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt @@ -145,7 +145,6 @@ sealed class FetchDataFlow( } } - /** * Given a set of hashes either loads from from local storage or requests them from the other peer. Downloaded * attachments are saved to local storage automatically. diff --git a/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt b/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt index 0fe2971033..620a649712 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt @@ -61,7 +61,8 @@ sealed class FlowIORequest { val shouldRetrySend: Boolean ) : FlowIORequest>>() { override fun toString() = "SendAndReceive(${sessionToMessage.mapValues { (key, value) -> - "$key=${value.hash}" }}, shouldRetrySend=$shouldRetrySend)" + "$key=${value.hash}" + }}, shouldRetrySend=$shouldRetrySend)" } /** diff --git a/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt b/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt index c9e39513e2..37b9be94e0 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt @@ -13,10 +13,12 @@ package net.corda.core.internal import co.paralleluniverse.fibers.Suspendable import net.corda.core.DoNotImplement import net.corda.core.concurrent.CordaFuture -import net.corda.core.flows.* -import net.corda.core.identity.Party -import net.corda.core.identity.PartyAndCertificate import net.corda.core.context.InvocationContext +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.FlowSession +import net.corda.core.flows.FlowStackSnapshot +import net.corda.core.flows.StateMachineRunId +import net.corda.core.identity.Party import net.corda.core.node.ServiceHub import org.slf4j.Logger diff --git a/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt b/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt index e4a2ccba91..e44a14d16f 100644 --- a/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt +++ b/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt @@ -49,10 +49,10 @@ class LazyPool( lifeCycle.requireState(State.STARTED) poolSemaphore.acquire() val pooled = poolQueue.poll() - if (pooled == null) { - return newInstance() + return if (pooled == null) { + newInstance() } else { - return clearIfNeeded(pooled) + clearIfNeeded(pooled) } } diff --git a/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt b/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt index e34c66f699..81e9955b49 100644 --- a/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt +++ b/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt @@ -76,6 +76,6 @@ class LazyStickyPool( } fun close(): Iterable { - return boxes.map { it.instance?.poll() }.filterNotNull() + return boxes.mapNotNull { it.instance?.poll() } } } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt b/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt index d83226a0fa..6f281cacdc 100644 --- a/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt +++ b/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt @@ -10,4 +10,4 @@ package net.corda.core.internal -val STRUCTURAL_STEP_PREFIX = "Structural step change in child of " \ No newline at end of file +const val STRUCTURAL_STEP_PREFIX = "Structural step change in child of " \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt b/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt index a76e72d385..41f0ff07bf 100644 --- a/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt +++ b/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt @@ -39,7 +39,7 @@ class X509EdDSAEngine : Signature { override fun engineInitVerify(publicKey: PublicKey) { val parsedKey = try { publicKey as? EdDSAPublicKey ?: EdDSAPublicKey(X509EncodedKeySpec(publicKey.encoded)) - } catch(e: Exception) { + } catch (e: Exception) { throw (InvalidKeyException(e.message)) } engine.initVerify(parsedKey) @@ -53,9 +53,9 @@ class X509EdDSAEngine : Signature { override fun engineGetParameters(): AlgorithmParameters = engine.parameters override fun engineSetParameter(params: AlgorithmParameterSpec) = engine.setParameter(params) - @Suppress("DEPRECATION") + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun engineGetParameter(param: String): Any = engine.getParameter(param) - @Suppress("DEPRECATION") + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun engineSetParameter(param: String, value: Any?) = engine.setParameter(param, value) } diff --git a/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt b/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt index dae69c05e8..467b65285e 100644 --- a/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt +++ b/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt @@ -152,7 +152,7 @@ interface OpenFuture : ValueOrException, CordaFuture internal class CordaFutureImpl(private val impl: CompletableFuture = CompletableFuture()) : Future by impl, OpenFuture { companion object { private val defaultLog = contextLogger() - internal val listenerFailedMessage = "Future listener failed:" + internal const val listenerFailedMessage = "Future listener failed:" } override fun set(value: V) = impl.complete(value) diff --git a/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt b/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt index ee6ba046c2..f121e155c0 100644 --- a/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt +++ b/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt @@ -23,7 +23,7 @@ data class CordappImpl( override val contractClassNames: List, override val initiatedFlows: List>>, override val rpcFlows: List>>, - override val serviceFlows: List>>, + override val serviceFlows: List>>, override val schedulableFlows: List>>, override val services: List>, override val serializationWhitelists: List, diff --git a/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt b/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt index 7c4421c30e..1caae11f1d 100644 --- a/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt +++ b/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt @@ -64,7 +64,6 @@ interface FlowProgressHandle : FlowHandle { override fun close() } - @CordaSerializable data class FlowHandleImpl( override val id: StateMachineRunId, diff --git a/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt b/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt index c7842a5d1d..f0931bd94d 100644 --- a/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt +++ b/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt @@ -36,5 +36,4 @@ interface AppServiceHub : ServiceHub { * TODO it is assumed here that the flow object has an appropriate classloader. */ fun startTrackedFlow(flow: FlowLogic): FlowProgressHandle - } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt b/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt index 700e166f2f..5549fa5110 100644 --- a/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt +++ b/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt @@ -41,7 +41,8 @@ data class NodeInfo(val addresses: List, require(platformVersion > 0) { "Platform version must be at least 1" } } - @Transient private var _legalIdentities: List? = null + @Transient + private var _legalIdentities: List? = null /** * An ordered list of legal identities supported by this node. The node will always have at least one, so if you diff --git a/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt b/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt index 08e719a232..d2d4a31170 100644 --- a/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt +++ b/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt @@ -253,7 +253,7 @@ object Builder { fun Field.functionPredicate(predicate: ColumnPredicate, groupByColumns: List>? = null, orderBy: Sort.Direction? = null) = info().functionPredicate(predicate, groupByColumns, orderBy) fun FieldInfo.functionPredicate(predicate: ColumnPredicate, groupByColumns: List>? = null, orderBy: Sort.Direction? = null) - = CriteriaExpression.AggregateFunctionExpression(Column(this), predicate, groupByColumns, orderBy) + = CriteriaExpression.AggregateFunctionExpression(Column(this), predicate, groupByColumns, orderBy) fun > KProperty1.comparePredicate(operator: BinaryComparisonOperator, value: R) = predicate(compare(operator, value)) @Deprecated("Does not support fields from a MappedSuperclass. Use equivalent on a FieldInfo.") @@ -377,7 +377,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.sum(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.SUM), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.SUM), groupByColumns?.map { Column(it) }, orderBy) fun KProperty1.count() = functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.COUNT)) @JvmStatic @@ -397,7 +397,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.avg(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.AVG), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.AVG), groupByColumns?.map { Column(it) }, orderBy) fun KProperty1.min(groupByColumns: List>? = null, orderBy: Sort.Direction? = null) = functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MIN), groupByColumns?.map { Column(it) }, orderBy) @@ -410,7 +410,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.min(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MIN), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MIN), groupByColumns?.map { Column(it) }, orderBy) fun KProperty1.max(groupByColumns: List>? = null, orderBy: Sort.Direction? = null) = functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MAX), groupByColumns?.map { Column(it) }, orderBy) @@ -423,7 +423,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.max(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MAX), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MAX), groupByColumns?.map { Column(it) }, orderBy) private fun Field.info(): FieldInfo = FieldInfo(name, declaringClass) } diff --git a/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt b/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt index eeca466447..e16a7b8d42 100644 --- a/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt +++ b/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt @@ -31,7 +31,7 @@ object CommonSchemaV1 : MappedSchema(schemaFamily = CommonSchema.javaClass, vers override val migrationResource = "common.changelog-master" @MappedSuperclass - open class LinearState( + class LinearState( /** [ContractState] attributes */ /** X500Name of participant parties **/ @@ -56,7 +56,7 @@ object CommonSchemaV1 : MappedSchema(schemaFamily = CommonSchema.javaClass, vers } @MappedSuperclass - open class FungibleState( + class FungibleState( /** [ContractState] attributes */ /** X500Name of participant parties **/ diff --git a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt index 1b08092484..84fa3f6d7f 100644 --- a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt +++ b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt @@ -89,7 +89,8 @@ open class MappedSchema(schemaFamily: Class<*>, * [StateRef] will be set to the correct value by the framework (there's no need to set during mapping generation by the state itself). */ @MappedSuperclass -@CordaSerializable open class PersistentState(@EmbeddedId var stateRef: PersistentStateRef? = null) : StatePersistable +@CordaSerializable +class PersistentState(@EmbeddedId var stateRef: PersistentStateRef? = null) : StatePersistable /** * Embedded [StateRef] representation used in state mapping. diff --git a/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt b/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt index 985504c404..53954e68f1 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt @@ -24,11 +24,11 @@ interface SerializationCustomSerializer { * Should facilitate the conversion of the third party object into the serializable * local class specified by [PROXY] */ - fun toProxy(obj: OBJ) : PROXY + fun toProxy(obj: OBJ): PROXY /** * Should facilitate the conversion of the proxy object into a new instance of the * unserializable type */ - fun fromProxy(proxy: PROXY) : OBJ + fun fromProxy(proxy: PROXY): OBJ } diff --git a/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt b/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt index 5006ff190f..bf7e8ca9f9 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt @@ -222,17 +222,17 @@ data class ContractUpgradeLedgerTransaction( * Outputs are computed by running the contract upgrade logic on input states. This is done eagerly so that the * transaction is verified during construction. */ - override val outputs: List> = inputs.map { input -> + override val outputs: List> = inputs.map { (state) -> // TODO: if there are encumbrance states in the inputs, just copy them across without modifying - val upgradedState = upgradedContract.upgrade(input.state.data) - val inputConstraint = input.state.constraint + val upgradedState = upgradedContract.upgrade(state.data) + val inputConstraint = state.constraint val outputConstraint = when (inputConstraint) { is HashAttachmentConstraint -> HashAttachmentConstraint(upgradedContractAttachment.id) WhitelistedByZoneAttachmentConstraint -> WhitelistedByZoneAttachmentConstraint else -> throw IllegalArgumentException("Unsupported input contract constraint $inputConstraint") } // TODO: re-map encumbrance pointers - input.state.copy( + state.copy( data = upgradedState, contract = upgradedContractClassName, constraint = outputConstraint 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 fa9767b835..d561d99da5 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt @@ -116,7 +116,7 @@ class WireTransaction(componentGroups: List, val privacySalt: Pr resolveIdentity: (PublicKey) -> Party?, resolveAttachment: (SecureHash) -> Attachment?, resolveStateRef: (StateRef) -> TransactionState<*>?, - resolveContractAttachment: (TransactionState) -> AttachmentId? + @SuppressWarnings("unused") resolveContractAttachment: (TransactionState) -> AttachmentId? ): LedgerTransaction { return toLedgerTransactionInternal(resolveIdentity, resolveAttachment, resolveStateRef, null) } diff --git a/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt b/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt index 21c9eb953c..e303e54b66 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt @@ -41,7 +41,6 @@ fun ByteArray.toBase64(): String = Base64.getEncoder().encodeToString(this) /** Convert a byte array to a hex (Base16) capitalized encoded [String]. */ fun ByteArray.toHex(): String = DatatypeConverter.printHexBinary(this) - // [String] encoders and decoders /** Base58-String to the actual real [String], i.e. "JxF12TrwUP45BMd" -> "Hello World". */ @@ -60,7 +59,6 @@ fun String.base64ToByteArray(): ByteArray = Base64.getDecoder().decode(this) /** Hex-String to [ByteArray]. Accept any hex form (capitalized, lowercase, mixed). */ fun String.hexToByteArray(): ByteArray = DatatypeConverter.parseHexBinary(this) - // Encoding changers /** Encoding changer. Base58-[String] to Base64-[String], i.e. "SGVsbG8gV29ybGQ=" -> JxF12TrwUP45BMd" */ diff --git a/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt b/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt index 4f327a4a57..1300e2cf9c 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt @@ -116,8 +116,10 @@ interface VariablePropertyDelegate : PropertyDelegate { @CordaSerializable private class TransientProperty internal constructor(private val initialiser: () -> T) : PropertyDelegate { - @Transient private var initialised = false - @Transient private var value: T? = null + @Transient + private var initialised = false + @Transient + private var value: T? = null @Synchronized override operator fun getValue(thisRef: Any?, property: KProperty<*>): T { diff --git a/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt b/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt index ee470315d7..662b03e387 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt @@ -71,11 +71,11 @@ class ProgressTracker(vararg steps: Step) { // Sentinel objects. Overrides equals() to survive process restarts and serialization. object UNSTARTED : Step("Unstarted") { - override fun equals(other: Any?) = other is UNSTARTED + override fun equals(other: Any?) = other === UNSTARTED } object DONE : Step("Done") { - override fun equals(other: Any?) = other is DONE + override fun equals(other: Any?) = other === DONE } @CordaSerializable diff --git a/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt b/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt index 13af1fd61e..a240dbb662 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt @@ -50,7 +50,6 @@ fun SerializedBytes.checkPayloadIs(type: Class): Untrustworthy } catch (ex: Exception) { throw IllegalArgumentException("Payload invalid", ex) } - return type.castIfPossible(payloadData)?.let { UntrustworthyData(it) } ?: - throw IllegalArgumentException("We were expecting a ${type.name} but we instead got a " + - "${payloadData.javaClass.name} (${payloadData})") + return type.castIfPossible(payloadData)?.let { UntrustworthyData(it) } ?: throw IllegalArgumentException("We were expecting a ${type.name} but we instead got a " + + "${payloadData.javaClass.name} ($payloadData)") } diff --git a/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt b/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt index 2993526281..c024e3dbca 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt @@ -15,6 +15,6 @@ import java.util.* class UuidGenerator { companion object { - fun next() : UUID = UUID.randomUUID() + fun next(): UUID = UUID.randomUUID() } } \ No newline at end of file diff --git a/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java b/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java index 4eb8bfb3d3..1090297ea1 100644 --- a/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java +++ b/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java @@ -35,7 +35,7 @@ public class FlowsInJavaTest { private Party bob; @Before - public void setUp() throws Exception { + public void setUp() { aliceNode = mockNet.createPartyNode(TestConstants.ALICE_NAME); bobNode = mockNet.createPartyNode(TestConstants.BOB_NAME); bob = singleIdentity(bobNode.getInfo()); @@ -134,7 +134,7 @@ public class FlowsInJavaTest { @Suspendable @Override - public Void call() throws FlowException { + public Void call() { FlowSession session = initiateFlow(otherParty); session.receive(Primitives.unwrap(receiveType)); return null; diff --git a/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt b/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt index 7b256fef65..62c2b36751 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt @@ -51,7 +51,6 @@ class AttachmentTest { } assertEquals(1, closeCalls) } - } class UniqueIdentifierTests { @@ -83,5 +82,4 @@ class UniqueIdentifierTests { assertEquals(ids[1], ids[2]) assertEquals(ids[1].hashCode(), ids[2].hashCode()) } - } \ No newline at end of file diff --git a/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt b/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt index 4303efb324..ce3b0ad5ee 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt @@ -186,9 +186,9 @@ class EdDSATests { /** A test vector object for digital signature schemes. */ private data class SignatureTestVector(val privateKeyHex: String, - val publicKeyHex: String, - val messageToSignHex: String, - val signatureOutputHex: String) + val publicKeyHex: String, + val messageToSignHex: String, + val signatureOutputHex: String) // Required to implement a custom doSign function, because Corda's Crypto.doSign does not allow empty messages (testVector1). private fun doSign(privateKey: PrivateKey, clearData: ByteArray): ByteArray { diff --git a/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt b/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt index 8718d3d89b..a2603c3c15 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt @@ -136,6 +136,5 @@ class X509NameConstraintsTest { pathValidator.validate(certPath, params) true } - } } diff --git a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt index 555d105a0e..e7b4895c81 100644 --- a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt @@ -13,7 +13,6 @@ package net.corda.core.flows import co.paralleluniverse.fibers.Suspendable import net.corda.core.contracts.Attachment import net.corda.core.crypto.SecureHash -import net.corda.core.crypto.sha256 import net.corda.core.identity.Party import net.corda.core.internal.FetchAttachmentsFlow import net.corda.core.internal.FetchDataFlow @@ -92,7 +91,7 @@ class AttachmentTests { } @Test - fun `missing`() { + fun missing() { val aliceNode = mockNet.createPartyNode(ALICE_NAME) val bobNode = mockNet.createPartyNode(BOB_NAME) aliceNode.registerInitiatedFlow(FetchAttachmentsResponse::class.java) diff --git a/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt b/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt index febe2315d2..ea4cb0b161 100644 --- a/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt @@ -23,7 +23,11 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.getOrThrow import net.corda.node.internal.StartedNode import net.corda.testing.contracts.DummyContract -import net.corda.testing.core.* +import net.corda.testing.core.ALICE_NAME +import net.corda.testing.core.BOB_NAME +import net.corda.testing.core.CHARLIE_NAME +import net.corda.testing.core.TestIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.internal.InternalMockNetwork @@ -32,7 +36,6 @@ import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test -import kotlin.reflect.KClass import kotlin.test.assertFailsWith class CollectSignaturesFlowTests { @@ -86,9 +89,11 @@ class CollectSignaturesFlowTests { @InitiatedBy(TestFlow.Initiator::class) class Responder(private val otherSideSession: FlowSession) : FlowLogic() { - @Suspendable override fun call() { + @Suspendable + override fun call() { val signFlow = object : SignTransactionFlow(otherSideSession) { - @Suspendable override fun checkTransaction(stx: SignedTransaction) = requireThat { + @Suspendable + override fun checkTransaction(stx: SignedTransaction) = requireThat { val tx = stx.tx val ltx = tx.toLedgerTransaction(serviceHub) "There should only be one output state" using (tx.outputs.size == 1) diff --git a/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt b/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt index 410a13c601..b12698031b 100644 --- a/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt +++ b/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt @@ -33,7 +33,7 @@ class PartyAndCertificateTest { @Test fun `reject a path with no roles`() { - val path = X509Utilities.buildCertPath(DEV_ROOT_CA.certificate) + val path = X509Utilities.buildCertPath(DEV_ROOT_CA.certificate) assertFailsWith { PartyAndCertificate(path) } } diff --git a/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt b/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt index 2543a7c4f3..4b2579d164 100644 --- a/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt +++ b/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt @@ -19,7 +19,7 @@ import kotlin.test.assertNotEquals class PartyTest { @Test - fun `equality`() { + fun equality() { val key = entropyToKeyPair(BigInteger.valueOf(20170207L)).public val differentKey = entropyToKeyPair(BigInteger.valueOf(7201702L)).public val anonymousParty = AnonymousParty(key) diff --git a/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt b/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt index 84cdec6a5a..5ef2b0aaee 100644 --- a/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt +++ b/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt @@ -21,7 +21,6 @@ import org.junit.Test import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths -import kotlin.streams.toList import kotlin.test.assertEquals class AbstractAttachmentTest { diff --git a/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt b/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt index f13c32aaaf..d2333c270b 100644 --- a/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt +++ b/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt @@ -71,7 +71,7 @@ class LegalNameValidatorTest { } // Latin capital letter turned m assertFailsWith { - LegalNameValidator.validateOrganization( "Test\u019CLtd", LegalNameValidator.Validation.FULL) + LegalNameValidator.validateOrganization("Test\u019CLtd", LegalNameValidator.Validation.FULL) } // Latin small letter turned e assertFailsWith { @@ -94,7 +94,7 @@ class LegalNameValidatorTest { } // Latin capital letter turned m assertFailsWith { - LegalNameValidator.validateNameAttribute( "Test\u019CLtd", LegalNameValidator.Validation.FULL) + LegalNameValidator.validateNameAttribute("Test\u019CLtd", LegalNameValidator.Validation.FULL) } // Latin small letter turned e assertFailsWith { diff --git a/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt b/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt index 32bbc282ba..b4410b1278 100644 --- a/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt +++ b/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt @@ -24,7 +24,7 @@ import kotlin.test.assertFailsWith class VaultUpdateTests { private companion object { - val DUMMY_PROGRAM_ID = "net.corda.core.node.VaultUpdateTests.DummyContract" + const val DUMMY_PROGRAM_ID = "net.corda.core.node.VaultUpdateTests.DummyContract" val DUMMY_NOTARY = TestIdentity(DUMMY_NOTARY_NAME, 20).party val emptyUpdate = Vault.Update(emptySet(), emptySet(), type = Vault.UpdateType.GENERAL) } @@ -68,7 +68,7 @@ class VaultUpdateTests { @Test fun `nothing plus something is something`() { val before = emptyUpdate - val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef2, stateAndRef3)) + val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef2, stateAndRef3)) val expected = Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef2, stateAndRef3)) assertEquals(expected, after) } @@ -76,7 +76,7 @@ class VaultUpdateTests { @Test fun `something plus consume state 0 is something without state 0 output`() { val before = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1)) - val after = before + Vault.Update(setOf(stateAndRef0), setOf()) + val after = before + Vault.Update(setOf(stateAndRef0), setOf()) val expected = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef1)) assertEquals(expected, after) } @@ -84,7 +84,7 @@ class VaultUpdateTests { @Test fun `something plus produce state 4 is something with additional state 4 output`() { val before = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1)) - val after = before + Vault.Update(setOf(), setOf(stateAndRef4)) + val after = before + Vault.Update(setOf(), setOf(stateAndRef4)) val expected = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1, stateAndRef4)) assertEquals(expected, after) } @@ -92,7 +92,7 @@ class VaultUpdateTests { @Test fun `something plus consume states 0 and 1, and produce state 4, is something without state 0 and 1 outputs and only state 4 output`() { val before = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1)) - val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef4)) + val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef4)) val expected = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef4)) assertEquals(expected, after) } diff --git a/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt b/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt index 18e2ecbc1b..314b66a9aa 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt @@ -52,6 +52,7 @@ private fun createAttachmentData(content: String) = ByteArrayOutputStream().appl private fun Attachment.extractContent() = ByteArrayOutputStream().apply { extractFile("content", this) }.toString(UTF_8.name()) +@SuppressWarnings("deprecation") private fun StartedNode<*>.saveAttachment(content: String) = database.transaction { attachments.importAttachment(createAttachmentData(content).inputStream()) } diff --git a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt index 66e1bd38ac..c53794b82b 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt @@ -93,7 +93,7 @@ class TransactionSerializationTests { stx.verifyRequiredSignatures() // Corrupt the data and ensure the signature catches the problem. - val bytesField = stx.id::bytes.javaField?.apply { setAccessible(true) } + val bytesField = stx.id::bytes.javaField?.apply { isAccessible = true } val bytes = bytesField?.get(stx.id) as ByteArray bytes[5] = bytes[5].inc() diff --git a/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt b/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt index 3057f443bd..a7b0950e5c 100644 --- a/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt +++ b/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt @@ -62,12 +62,12 @@ class CompatibleTransactionTests { // Do not add attachments (empty list). private val componentGroupsA by lazy { listOf( - inputGroup, - outputGroup, - commandGroup, - notaryGroup, - timeWindowGroup, - signersGroup + inputGroup, + outputGroup, + commandGroup, + notaryGroup, + timeWindowGroup, + signersGroup ) } private val wireTransactionA by lazy { WireTransaction(componentGroups = componentGroupsA, privacySalt = privacySalt) } @@ -134,7 +134,8 @@ class CompatibleTransactionTests { @Test fun `WireTransaction constructors and compatibility`() { - val wireTransactionOldConstructor = WireTransaction(inputs, attachments, outputs, commands, notary, timeWindow, privacySalt) + val groups = WireTransaction.createComponentGroups(inputs, outputs, commands, attachments, notary, timeWindow) + val wireTransactionOldConstructor = WireTransaction(groups, privacySalt) assertEquals(wireTransactionA, wireTransactionOldConstructor) // Malformed tx - attachments is not List. For this example, we mistakenly added input-state (StateRef) serialised objects with ATTACHMENTS_GROUP.ordinal. @@ -396,7 +397,7 @@ class CompatibleTransactionTests { assertFailsWith { WireTransaction(componentGroups = componentGroupsLessSigners, privacySalt = PrivacySalt()) } // Test if there is no command to sign. - val commandsNoKey1= listOf(dummyCommand(DUMMY_KEY_2.public)) + val commandsNoKey1 = listOf(dummyCommand(DUMMY_KEY_2.public)) val componentGroupsNoKey1ToSign = listOf( inputGroup, @@ -409,7 +410,7 @@ class CompatibleTransactionTests { ) val wtxNoKey1 = WireTransaction(componentGroups = componentGroupsNoKey1ToSign, privacySalt = PrivacySalt()) - val allCommandsNoKey1Ftx= wtxNoKey1.buildFilteredTransaction(Predicate(::filterCommandsOnly)) + val allCommandsNoKey1Ftx = wtxNoKey1.buildFilteredTransaction(Predicate(::filterCommandsOnly)) allCommandsNoKey1Ftx.checkCommandVisibility(DUMMY_KEY_1.public) // This will pass, because there are indeed no commands to sign in the original transaction. } @@ -500,7 +501,7 @@ class CompatibleTransactionTests { // Remove both last signer (KEY1) and related command. // Update partial Merkle tree for signers. val updatedFilteredComponentsNoLastCommandAndSigners = listOf(noLastCommandDataGroup, noLastSignerGroup) - val ftxNoLastCommandAndSigners = ftxConstructor.invoke(key1CommandsFtx.id, updatedFilteredComponentsNoLastCommandAndSigners, key1CommandsFtx.groupHashes) as FilteredTransaction + val ftxNoLastCommandAndSigners = ftxConstructor.invoke(key1CommandsFtx.id, updatedFilteredComponentsNoLastCommandAndSigners, key1CommandsFtx.groupHashes) // verify() will pass as the transaction is well-formed. ftxNoLastCommandAndSigners.verify() // checkCommandVisibility() will not pass, because checkAllComponentsVisible(ComponentGroupEnum.SIGNERS_GROUP) will fail. @@ -509,7 +510,7 @@ class CompatibleTransactionTests { // Remove last signer for which there is no pointer from a visible commandData. This is the case of Key2. // Do not change partial Merkle tree for signers. // This time the object can be constructed as there is no pointer mismatch. - val ftxNoLastSigner = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2SamePMT, key2CommandsFtx.groupHashes) as FilteredTransaction + val ftxNoLastSigner = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2SamePMT, key2CommandsFtx.groupHashes) // verify() will fail as we didn't change the partial Merkle tree. assertFailsWith { ftxNoLastSigner.verify() } // checkCommandVisibility() will not pass. @@ -517,7 +518,7 @@ class CompatibleTransactionTests { // Remove last signer for which there is no pointer from a visible commandData. This is the case of Key2. // Update partial Merkle tree for signers. - val ftxNoLastSignerB = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2, key2CommandsFtx.groupHashes) as FilteredTransaction + val ftxNoLastSignerB = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2, key2CommandsFtx.groupHashes) // verify() will pass, the transaction is well-formed. ftxNoLastSignerB.verify() // But, checkAllComponentsVisible() will not pass. @@ -542,14 +543,14 @@ class CompatibleTransactionTests { val alterFilteredComponents = listOf(key1CommandsFtx.filteredComponentGroups[0], alterSignerGroup) // Do not update groupHashes. - val ftxAlterSigner = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes) as FilteredTransaction + val ftxAlterSigner = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes) // Visible components in signers group cannot be verified against their partial Merkle tree. assertFailsWith { ftxAlterSigner.verify() } // Also, checkAllComponentsVisible() will not pass (groupHash matching will fail). assertFailsWith { ftxAlterSigner.checkCommandVisibility(DUMMY_KEY_1.public) } // Update groupHashes. - val ftxAlterSignerB = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes.subList(0, 6) + alterMTree.hash) as FilteredTransaction + val ftxAlterSignerB = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes.subList(0, 6) + alterMTree.hash) // Visible components in signers group cannot be verified against their partial Merkle tree. assertFailsWith { ftxAlterSignerB.verify() } // Also, checkAllComponentsVisible() will not pass (top level Merkle tree cannot be verified against transaction's id). diff --git a/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt b/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt index 762adca127..693b54294f 100644 --- a/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt +++ b/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt @@ -32,7 +32,7 @@ import org.junit.Test import java.time.Instant import java.time.temporal.ChronoUnit -val TEST_TIMELOCK_ID = "net.corda.core.transactions.TransactionEncumbranceTests\$DummyTimeLock" +const val TEST_TIMELOCK_ID = "net.corda.core.transactions.TransactionEncumbranceTests\$DummyTimeLock" class TransactionEncumbranceTests { private companion object { diff --git a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java index bdefa9633f..3fa5e553f0 100644 --- a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java +++ b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java @@ -476,7 +476,7 @@ public class FlowCookbookJava { subFlow(new SendStateAndRefFlow(counterpartySession, dummyStates)); // On the receive side ... - List> resolvedStateAndRef = subFlow(new ReceiveStateAndRefFlow(counterpartySession)); + List> resolvedStateAndRef = subFlow(new ReceiveStateAndRefFlow<>(counterpartySession)); // DOCEND 14 try { diff --git a/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java b/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java index 00aae7b9f3..3052ac8dd4 100644 --- a/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java +++ b/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java @@ -60,7 +60,7 @@ public class CommercialPaper implements Contract { requireThat(require -> { require.using("the paper must have matured", time.isAfter(input.getMaturityDate())); require.using("the received amount equals the face value", received == input.getFaceValue()); - require.using("the paper must be destroyed", outputs.size() == 0); + require.using("the paper must be destroyed", outputs.isEmpty()); require.using("the transaction is signed by the owner of the CP", cmd.getSigners().contains(input.getOwner().getOwningKey())); return null; }); diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt index d6d0878220..a9941ce997 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt @@ -153,9 +153,8 @@ object TopupIssuerFlow { // now invoke Cash subflow to Move issued assetType to issue requester progressTracker.currentStep = TRANSFERRING val moveCashFlow = CashPaymentFlow(amount, issueTo, anonymous = false) - val moveTx = subFlow(moveCashFlow) // NOTE: CashFlow PayCash calls FinalityFlow which performs a Broadcast (which stores a local copy of the txn to the ledger) - return moveTx + return subFlow(moveCashFlow) } } } diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt index a35acdee37..58eca77fd2 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt @@ -33,7 +33,7 @@ enum class WorkflowState { REJECTED } -val TRADE_APPROVAL_PROGRAM_ID = "net.corda.docs.TradeApprovalContract" +const val TRADE_APPROVAL_PROGRAM_ID = "net.corda.docs.TradeApprovalContract" /** * Minimal contract to encode a simple workflow with one initial state and two possible eventual states. diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt index e3148e5729..744deb1cb0 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt @@ -14,7 +14,7 @@ import net.corda.core.contracts.CommandData import net.corda.core.contracts.Contract import net.corda.core.transactions.LedgerTransaction -val TEMPLATE_CONTRACT_ID = "com.template.TemplateContract" +const val TEMPLATE_CONTRACT_ID = "com.template.TemplateContract" open class TemplateContract : Contract { // A transaction is considered valid if the verify() function of the contract of each of the transaction's input diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt index 21253c4aa9..8edd96ecf5 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt @@ -18,20 +18,12 @@ import net.corda.core.flows.FlowSession import net.corda.core.flows.InitiatedBy import net.corda.core.flows.InitiatingFlow import net.corda.core.identity.Party -import net.corda.core.messaging.MessageRecipients -import net.corda.core.serialization.deserialize -import net.corda.core.serialization.serialize -import net.corda.core.utilities.OpaqueBytes -import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.unwrap -import net.corda.node.services.messaging.Message -import net.corda.node.services.statemachine.DataSessionMessage -import net.corda.node.services.statemachine.ExistingSessionMessage -import net.corda.testing.node.* +import net.corda.testing.node.MockNetwork +import net.corda.testing.node.StartedMockNode import org.junit.After import org.junit.Before import org.junit.Rule -import org.junit.Test import org.junit.rules.ExpectedException class TutorialMockNetwork { @@ -63,9 +55,9 @@ class TutorialMockNetwork { } } - lateinit private var mockNet: MockNetwork - lateinit private var nodeA: StartedMockNode - lateinit private var nodeB: StartedMockNode + private lateinit var mockNet: MockNetwork + private lateinit var nodeA: StartedMockNode + private lateinit var nodeB: StartedMockNode @Rule @JvmField @@ -86,8 +78,8 @@ class TutorialMockNetwork { // @Test // fun `fail if initiated doesn't send back 1 on first result`() { - // DOCSTART 1 - // TODO: Fix this test - accessing the MessagingService directly exposes internal interfaces + // DOCSTART 1 + // TODO: Fix this test - accessing the MessagingService directly exposes internal interfaces // nodeB.setMessagingServiceSpy(object : MessagingServiceSpy(nodeB.network) { // override fun send(message: Message, target: MessageRecipients, retryId: Long?, sequenceKey: Any, additionalHeaders: Map) { // val messageData = message.data.deserialize() as? ExistingSessionMessage @@ -101,7 +93,7 @@ class TutorialMockNetwork { // } // } // }) - // DOCEND 1 + // DOCEND 1 // val initiatingReceiveFlow = nodeA.startFlow(FlowA(nodeB.info.legalIdentities.first())) // diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt index 1c51a353b8..ce935be1ae 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt @@ -19,7 +19,7 @@ import net.corda.core.transactions.LedgerTransaction import net.corda.core.contracts.* // Replace IOUContract's contract ID and definition with: -val IOU_CONTRACT_ID = "com.template.IOUContract" +const val IOU_CONTRACT_ID = "com.template.IOUContract" class IOUContract : Contract { // Our Create command. diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt index a82f6c1987..ebf3032ceb 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt @@ -14,19 +14,15 @@ package net.corda.docs.tutorial.twoparty import co.paralleluniverse.fibers.Suspendable import net.corda.core.contracts.Command import net.corda.core.contracts.StateAndContract -import net.corda.core.flows.* +import net.corda.core.flows.CollectSignaturesFlow +import net.corda.core.flows.FinalityFlow +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.InitiatingFlow +import net.corda.core.flows.StartableByRPC import net.corda.core.identity.Party -import net.corda.core.messaging.CordaRPCOps -import net.corda.core.serialization.SerializationWhitelist import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.ProgressTracker -import net.corda.webserver.services.WebServerPluginRegistry -import java.util.function.Function -import javax.ws.rs.GET -import javax.ws.rs.Path -import javax.ws.rs.Produces -import javax.ws.rs.core.MediaType -import javax.ws.rs.core.Response + // DOCEND 01 @InitiatingFlow diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt index 7453acb750..05958da0da 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt @@ -34,7 +34,6 @@ import net.corda.node.services.vault.VaultSchemaV1 import net.corda.testing.core.singleIdentity import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode -import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.After import org.junit.Assert @@ -115,12 +114,12 @@ class CustomVaultQueryTest { val balancesNodesA = nodeA.transaction { nodeA.services.getCashBalances() } - println("BalanceA\n" + balancesNodesA) + println("BalanceA\n$balancesNodesA") val balancesNodesB = nodeB.transaction { nodeB.services.getCashBalances() } - println("BalanceB\n" + balancesNodesB) + println("BalanceB\n$balancesNodesB") return Pair(balancesNodesA, balancesNodesB) } diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt index 2b9e43b09a..de8ec023e6 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt @@ -14,9 +14,13 @@ import net.corda.core.identity.Party import net.corda.core.toFuture import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.getOrThrow -import net.corda.finance.* +import net.corda.finance.DOLLARS +import net.corda.finance.GBP +import net.corda.finance.POUNDS +import net.corda.finance.USD import net.corda.finance.contracts.getCashBalances import net.corda.finance.flows.CashIssueFlow +import net.corda.finance.issuedBy import net.corda.testing.core.singleIdentity import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode @@ -80,8 +84,8 @@ class FxTransactionBuildTutorialTest { nodeB.services.getCashBalances() } - println("BalanceA\n" + balancesA) - println("BalanceB\n" + balancesB) + println("BalanceA\n$balancesA") + println("BalanceB\n$balancesB") // Verify the transfers occurred as expected assertEquals(POUNDS(100), balancesA[GBP]) assertEquals(DOLLARS(1000 - 200), balancesA[USD]) diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt index b070178b41..2986e8ef39 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt @@ -13,7 +13,6 @@ package net.corda.docs.tutorial.testdsl import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.whenever import net.corda.core.contracts.TransactionVerificationException -import net.corda.core.crypto.generateKeyPair import net.corda.core.identity.CordaX500Name import net.corda.core.node.services.IdentityService import net.corda.core.utilities.days @@ -24,11 +23,14 @@ import net.corda.finance.contracts.CommercialPaper import net.corda.finance.contracts.ICommercialPaperState import net.corda.finance.contracts.asset.CASH import net.corda.finance.contracts.asset.Cash -import net.corda.testing.core.* +import net.corda.testing.core.ALICE_NAME +import net.corda.testing.core.BOB_NAME +import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.core.SerializationEnvironmentRule +import net.corda.testing.core.TestIdentity import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.ledger -import net.corda.testing.node.makeTestIdentityService import net.corda.testing.node.transaction import org.junit.Rule import org.junit.Test diff --git a/docs/source/tut-two-party-flow.rst b/docs/source/tut-two-party-flow.rst index 4b6e1c3cda..aefa3cfb96 100644 --- a/docs/source/tut-two-party-flow.rst +++ b/docs/source/tut-two-party-flow.rst @@ -52,7 +52,7 @@ In the original CorDapp, we automated the process of notarising a transaction an by invoking a built-in flow called ``FinalityFlow`` as a subflow. We're going to use another pre-defined flow, ``CollectSignaturesFlow``, to gather the borrower's signature. -First, we need to update the command. We are now using ``IOUContract.Commands.Create``, rather than +First, we need to update the command. We are now using ``IOUContract.Create``, rather than ``TemplateContract.Commands.Action``. We also want to make the borrower a required signer, as per the contract constraints. This is as simple as adding the borrower's public key to the transaction's command. @@ -149,4 +149,4 @@ You should now be ready to develop your own CorDapps. You can also find a list o :doc:`Corda API `. If you get stuck at any point, please reach out on `Slack `_ or -`Stack Overflow `_. \ No newline at end of file +`Stack Overflow `_. diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt index d535888c9f..7e13004ecf 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt @@ -19,5 +19,4 @@ open class DatabaseConfigurationTemplate { protected open val config: (DatabaseConfiguration) -> String = { "" } fun generate(config: DatabaseConfiguration) = config(config).trimMargin() - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt index 1f1aa0a250..46edf25296 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt @@ -27,8 +27,8 @@ class DatabaseConnection( fun open(): Connection { try { val connectionProps = Properties() - connectionProps.put("user", config.username) - connectionProps.put("password", config.password) + connectionProps["user"] = config.username + connectionProps["password"] = config.password retry (5) { conn = DriverManager.getConnection(connectionString, connectionProps) } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt index 71ebc0f91a..c57c8c05aa 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt @@ -73,5 +73,4 @@ class DatabaseSettings { val template: DatabaseConfigurationTemplate get() = databaseConfigTemplate - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt index 5c52237362..e2e97ee7d0 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt @@ -66,7 +66,5 @@ enum class DatabaseType(val settings: DatabaseSettings) { "postgresql" -> POSTGRES else -> null } - } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt index a03e9bfac2..f7d66f2206 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt @@ -24,5 +24,4 @@ class H2ConfigurationTemplate : DatabaseConfigurationTemplate() { |h2port=${it.port} """ } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt b/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt index 9629984759..d997b1779e 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt @@ -37,7 +37,7 @@ class LogSource( val logFiles = directory.list { it.filter { (!filePatternUsedForExclusion && it.fileName.toString().matches(fileRegex)) || - (filePatternUsedForExclusion && !it.fileName.toString().matches(fileRegex)) + (filePatternUsedForExclusion && !it.fileName.toString().matches(fileRegex)) }.toList() } val result = mutableListOf() @@ -53,5 +53,4 @@ class LogSource( } return result } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt index e540885ffe..79f5c5db69 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt @@ -22,7 +22,7 @@ class ConjunctiveWatch( override fun ready() = left.ready() && right.ready() override fun await(timeout: Duration): Boolean { - val countDownLatch = CountDownLatch(2) + val countDownLatch = CountDownLatch(2) listOf(left, right).parallelStream().forEach { if (it.await(timeout)) { countDownLatch.countDown() @@ -30,5 +30,4 @@ class ConjunctiveWatch( } return countDownLatch.await(timeout) } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt index 7257076838..c257330c6b 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt @@ -11,7 +11,6 @@ package net.corda.behave.monitoring import net.corda.behave.await -import rx.Observable import java.time.Duration import java.util.concurrent.CountDownLatch @@ -23,7 +22,7 @@ class DisjunctiveWatch( override fun ready() = left.ready() || right.ready() override fun await(timeout: Duration): Boolean { - val countDownLatch = CountDownLatch(1) + val countDownLatch = CountDownLatch(1) listOf(left, right).parallelStream().forEach { if (it.await(timeout)) { countDownLatch.countDown() @@ -31,6 +30,5 @@ class DisjunctiveWatch( } return countDownLatch.await(timeout) } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt index aaed374eac..990b867d93 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt @@ -23,6 +23,7 @@ interface Watch { operator fun times(other: Watch): Watch { return ConjunctiveWatch(this, other) } + operator fun div(other: Watch): Watch { return DisjunctiveWatch(this, other) } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt index eff9eb020d..a98847dc89 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt @@ -128,10 +128,10 @@ class Distribution private constructor( */ fun fromArtifactory(type: Type, version: String): Distribution { val url = - when (type) { - Type.CORDA -> URL("https://ci-artifactory.corda.r3cev.com/artifactory/corda-releases/net/corda/corda/$version/corda-$version.jar") - Type.R3_CORDA -> URL("https://ci-artifactory.corda.r3cev.com/artifactory/r3-corda-releases/com/r3/corda/corda/$version/corda-$version.jar") - } + when (type) { + Type.CORDA -> URL("https://ci-artifactory.corda.r3cev.com/artifactory/corda-releases/net/corda/corda/$version/corda-$version.jar") + Type.R3_CORDA -> URL("https://ci-artifactory.corda.r3cev.com/artifactory/r3-corda-releases/com/r3/corda/corda/$version/corda-$version.jar") + } log.info("Artifactory URL: $url\n") val distribution = Distribution(type, version, url = url) distributions.add(distribution) @@ -167,8 +167,8 @@ class Distribution private constructor( * @param version The version of the Corda distribution */ fun fromVersionString(version: String): Distribution = when (version) { - "master" -> MASTER - "r3-master" -> R3_MASTER + "master" -> MASTER + "r3-master" -> R3_MASTER "corda-3.0" -> fromArtifactory(Type.CORDA, version) "corda-3.1" -> fromArtifactory(Type.CORDA, version) "R3.CORDA-3.0.0-DEV-PREVIEW-3" -> fromArtifactory(Type.R3_CORDA, version) diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt index 42bb277775..93f18c7886 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt @@ -66,5 +66,4 @@ class Configuration( private val log = contextLogger() const val DEFAULT_PASSWORD = "S0meS3cretW0rd" } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt index e0e2714a8d..281ed98383 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt @@ -15,5 +15,4 @@ open class ConfigurationTemplate { protected open val config: (Configuration) -> String = { "" } fun generate(config: Configuration) = config(config).trimMargin() - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt index 82292c8d91..1faa928a17 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt @@ -34,5 +34,4 @@ class CordappConfiguration(var apps: List = emptyList(), val includeFina private fun formatApp(config: Configuration, app: String): String { return "\"${app.replace("CORDA_VERSION", config.distribution.version)}\"" } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt index 9b7ebc7cd6..f88ccbf1e6 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt @@ -26,5 +26,4 @@ class CurrencyConfiguration(private val issuableCurrencies: List) : Conf """ } } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt index fef5767d81..b9cd3ef8fb 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt @@ -23,5 +23,4 @@ data class DatabaseConfiguration( ) { fun config() = type.settings.config(this) - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt index 265cab404f..0514ed8565 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt @@ -65,12 +65,9 @@ data class NetworkInterface( val s = Socket("localhost", portNumber) s.close() true - } catch (_: Exception) { false } } - } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt index 42ba7c11ee..f3aa638739 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt @@ -22,5 +22,4 @@ class NotaryConfiguration(val notaryType: NotaryType = NotaryType.NONE) : Config "notary { validating = true }" } } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt index 8878c462d4..e04eb4372a 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt @@ -15,7 +15,6 @@ enum class NotaryType { NONE, VALIDATING, NON_VALIDATING - } fun String.toNotaryType(): NotaryType? { diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt index 444487b3f1..5398d37b34 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt @@ -43,5 +43,4 @@ class UserConfiguration : ConfigurationTemplate(), Iterable } fun use(action: (Command) -> Unit): Int { - try { + use { start() action(this) - } finally { - close() } return exitCode } fun use(subscriber: Subscriber, action: (Command, Observable) -> Unit = { _, _ -> }): Int { - try { + use { output.subscribe(subscriber) start() action(this, output) - } finally { - close() } return exitCode } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt b/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt index f72cf88f67..256f56a1f2 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt @@ -33,12 +33,10 @@ class JarCommand( companion object { private fun extraArguments(enableRemoteDebugging: Boolean) = - if (enableRemoteDebugging) { - arrayOf("-Dcapsule.jvm.args=-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005") - } else { - arrayOf() - } - + if (enableRemoteDebugging) { + arrayOf("-Dcapsule.jvm.args=-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005") + } else { + arrayOf() + } } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt b/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt index 46c1e6b1a9..61874722e9 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt @@ -15,5 +15,4 @@ interface OutputListener { fun onNewLine(line: String) fun onEndOfStream() - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt b/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt index 721018c3a0..c218ec514e 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt @@ -69,7 +69,7 @@ abstract class Service( override fun toString() = "Service(name = $name, port = $port)" - protected open fun checkPrerequisites() { } + protected open fun checkPrerequisites() {} protected open fun startService() = true @@ -78,5 +78,4 @@ abstract class Service( protected open fun verify() = true protected open fun waitUntilStarted() = true - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt index 552bc8bd8c..6e39ec2dbc 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt @@ -19,10 +19,8 @@ class H2Service( companion object { - val database = "node" - val schema = "dbo" - val username = "sa" - + const val database = "node" + const val schema = "dbo" + const val username = "sa" } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt index 728d3a5155..be9950b141 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt @@ -51,11 +51,10 @@ class PostgreSQLService( } companion object { - val host = "localhost" - val database = "postgres" - val schema = "public" - val username = "postgres" - val driver = "postgresql-42.1.4.jar" + const val host = "localhost" + const val database = "postgres" + const val schema = "public" + const val username = "postgres" + const val driver = "postgresql-42.1.4.jar" } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt b/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt index eb0d03d594..3072054841 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt @@ -63,10 +63,8 @@ class MonitoringSSHClient( } fun use(action: (MonitoringSSHClient) -> Unit) { - try { + use { action(this) - } finally { - close() } } @@ -75,5 +73,4 @@ class MonitoringSSHClient( fun write(charSequence: CharSequence) = client.write(charSequence) fun writeLine(string: String) = client.writeLine(string) - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/Scenarios.kt b/experimental/behave/src/scenario/kotlin/Scenarios.kt index c24809a43b..cd13b32d3d 100644 --- a/experimental/behave/src/scenario/kotlin/Scenarios.kt +++ b/experimental/behave/src/scenario/kotlin/Scenarios.kt @@ -14,8 +14,8 @@ import org.junit.runner.RunWith @RunWith(Cucumber::class) @CucumberOptions( - glue = arrayOf("net.corda.behave.scenarios"), - plugin = arrayOf("pretty") + glue = ["net.corda.behave.scenarios"], + plugin = ["pretty"] ) @Suppress("KDocMissingDocumentation") class CucumberTest diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt index 62f7bf0680..4f811c8b90 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt @@ -1,4 +1,5 @@ @file:JvmName("ScenarioRunner") + package net.corda.behave.scenarios import joptsimple.OptionParser @@ -7,15 +8,15 @@ import kotlin.system.exitProcess fun main(args: Array) { val parser = OptionParser() val featurePath = parser.accepts("path").withRequiredArg().required().ofType(String::class.java) - .describedAs("Path location of .feature specifications") + .describedAs("Path location of .feature specifications") val glue = parser.accepts("glue").withOptionalArg().ofType(String::class.java) - .describedAs("location of additional step definitions, hooks and plugins") - .defaultsTo("net.corda.behave.scenarios") + .describedAs("location of additional step definitions, hooks and plugins") + .defaultsTo("net.corda.behave.scenarios") val plugin = parser.accepts("plugin").withOptionalArg().ofType(String::class.java) - .describedAs("register additional plugins (see https://cucumber.io/docs/reference/jvm)") - .defaultsTo("pretty") + .describedAs("register additional plugins (see https://cucumber.io/docs/reference/jvm)") + .defaultsTo("pretty") val tags = parser.accepts("tags").withOptionalArg().ofType(String::class.java) - .describedAs("only run scenarios marked as @") + .describedAs("only run scenarios marked as @") val dryRun = parser.accepts("d") val options = try { @@ -27,14 +28,14 @@ fun main(args: Array) { } val cliArgs = listOf("--glue", - options.valueOf(glue), - "--plugin", - options.valueOf(plugin), - options.valueOf(featurePath)) + - (if (options.hasArgument("tags")) - listOf("--tags", options.valueOf(tags)) - else emptyList()) + - if (options.has(dryRun)) listOf("-d") else emptyList() + options.valueOf(glue), + "--plugin", + options.valueOf(plugin), + options.valueOf(featurePath)) + + (if (options.hasArgument("tags")) + listOf("--tags", options.valueOf(tags)) + else emptyList()) + + if (options.has(dryRun)) listOf("-d") else emptyList() println("Cucumber CLI scenario runner args: $cliArgs") cucumber.api.cli.Main.main(cliArgs.toTypedArray()) diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt index 2efb6ee4ed..135eebf4e5 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt @@ -32,7 +32,7 @@ class ScenarioState { error(message) } - fun error(message: String, ex: Throwable? = null): T { + fun error(message: String, ex: Throwable? = null): T { this.network?.signalFailure(message, ex) if (ex != null) { throw Exception(message, ex) @@ -103,7 +103,7 @@ class ScenarioState { network.stop() } - private fun nodeName(name: String) = "$name" + private fun nodeName(name: String) = name private fun newNode(name: String): Node.Builder { val builder = Node.new() @@ -111,5 +111,4 @@ class ScenarioState { nodes.add(builder) return builder } - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt index 3f0a5a3830..92788ccffa 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt @@ -22,7 +22,7 @@ import net.corda.core.utilities.loggerFor class StepsContainer(val state: ScenarioState) : En { companion object { - val stepsProviders: List by lazy { + val stepsProviders: List by lazy { FastClasspathScanner().addClassLoader(this::class.java.classLoader).scan() .getNamesOfClassesImplementing(StepsProvider::class.java) .mapNotNull { this::class.java.classLoader.loadClass(it).asSubclass(StepsProvider::class.java) } diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt index 2ecfbe8d86..d0ea0179f4 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt @@ -43,7 +43,7 @@ class Cash(state: ScenarioState) : Substeps(state) { } } - fun issueCash(issueToNode: String, amount: Long, currency: String): SignedTransaction { + fun issueCash(issueToNode: String, amount: Long, currency: String): SignedTransaction { return withClient(issueToNode) { try { val notaryList = it.notaryIdentities() @@ -58,10 +58,10 @@ class Cash(state: ScenarioState) : Substeps(state) { } } - fun transferCash(senderNode: String, sendToNode: String, amount: Long, currency: String): SignedTransaction { + fun transferCash(senderNode: String, sendToNode: String, amount: Long, currency: String): SignedTransaction { return withClient(senderNode) { try { - val sendToX500Name = node(sendToNode).config.cordaX500Name + val sendToX500Name = node(sendToNode).config.cordaX500Name val sendToParty = node(senderNode).rpc { it.wellKnownPartyFromX500Name(sendToX500Name) ?: throw IllegalStateException("Unable to locate $sendToX500Name in Network Map Service") } @@ -72,5 +72,4 @@ class Cash(state: ScenarioState) : Substeps(state) { } } } - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt index 2ac4e78351..5b8c6e7d35 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt @@ -29,5 +29,4 @@ class Database(state: ScenarioState) : Substeps(state) { assertThat(latch.await(10.seconds)).isTrue() } } - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt index a788e3acc5..eee4325120 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt @@ -49,5 +49,4 @@ class Ssh(state: ScenarioState) : Substeps(state) { state.fail("Unable to find SSH start-up message for node $nodeName") } } - } \ No newline at end of file diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt index 3fbee8e96a..9fe06b9490 100644 --- a/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt +++ b/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt @@ -70,5 +70,4 @@ class MonitoringTests { val aggregate = watch1 / watch2 / watch3 assertThat(aggregate.await(1.seconds)).isFalse() } - } \ No newline at end of file diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt index 113c3489a7..275b64a19b 100644 --- a/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt +++ b/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt @@ -114,5 +114,4 @@ class NetworkTests { it.keepAlive(30.seconds) } } - } \ No newline at end of file diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt index e69de29bb2..a8d690afd0 100644 --- a/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt +++ b/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt @@ -0,0 +1,18 @@ +package net.corda.behave.service + +import net.corda.behave.service.database.PostgreSQLService +import org.assertj.core.api.Assertions.assertThat +import org.junit.Ignore +import org.junit.Test + +class PostreSQLServiceTests { + + @Ignore + @Test + fun `postgres can be started and stopped`() { + val service = PostgreSQLService("test-postgres", 12345, "postgres") + val didStart = service.start() + service.stop() + assertThat(didStart).isTrue() + } +} \ No newline at end of file diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt index 8a30c2319f..6bc15cd304 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt @@ -49,7 +49,7 @@ fun String.simplifyClass(): String { return if (this.endsWith('>')) { val templateStart = this.indexOf('<') val clazz = (this.substring(0, templateStart)) - val params = this.substring(templateStart+1, this.length-1).split(',').map { it.simplifyClass() }.joinToString() + val params = this.substring(templateStart+1, this.length-1).split(',').joinToString { it.simplifyClass() } "${clazz.simplifyClass()} <$params>" } @@ -108,20 +108,22 @@ class ListProperty( private val values: MutableList = mutableListOf()) : Property(name, type) { override fun stringify(sb: IndentingStringBuilder) { sb.apply { - if (values.isEmpty()) { - appendln("$name : $type : [ << EMPTY LIST >> ]") - } else if (values.first() is Stringify) { - appendln("$name : $type : [") - values.forEach { - (it as Stringify).stringify(this) + when { + values.isEmpty() -> appendln("$name : $type : [ << EMPTY LIST >> ]") + values.first() is Stringify -> { + appendln("$name : $type : [") + values.forEach { + (it as Stringify).stringify(this) + } + appendln("]") } - appendln("]") - } else { - appendln("$name : $type : [") - values.forEach { - appendln(it.toString()) + else -> { + appendln("$name : $type : [") + values.forEach { + appendln(it.toString()) + } + appendln("]") } - appendln("]") } } } diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt index a027249079..c831665036 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt @@ -25,9 +25,9 @@ class InMemoryBlobHandler(config_: Config) : BlobHandler(config_) { /** * */ -abstract class BlobHandler (val config: Config) { +abstract class BlobHandler(val config: Config) { companion object { - fun make(config: Config) : BlobHandler { + fun make(config: Config): BlobHandler { return when (config.mode) { Mode.file -> FileBlobHandler(config) Mode.inMem -> InMemoryBlobHandler(config) @@ -35,6 +35,6 @@ abstract class BlobHandler (val config: Config) { } } - abstract fun getBytes() : ByteArray + abstract fun getBytes(): ByteArray } diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt index 48d81a8eb7..1ec7fe6557 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt @@ -9,7 +9,7 @@ package net.corda.blobinspector * currently being added to the string. * @property indent How deeply the next line should be offset from the first column */ -class IndentingStringBuilder(s : String = "", private val offset : Int = 4) { +class IndentingStringBuilder(s: String = "", private val offset: Int = 4) { private val sb = StringBuilder(s) private var indenting = true private var indent = 0 @@ -21,18 +21,17 @@ class IndentingStringBuilder(s : String = "", private val offset : Int = 4) { appender(ln) - if (ln.endsWith("{") || ln.endsWith("[")){ + if (ln.endsWith("{") || ln.endsWith("[")) { indent += offset } } fun appendln(ln: String) { - wrap(ln) { s -> sb.appendln("${"".padStart(if (indenting) indent else 0, ' ')}$s") } + wrap(ln) { s -> sb.appendln("${"".padStart(if (indenting) indent else 0, ' ')}$s") } indenting = true } - fun append(ln: String) { indenting = false diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt index 0e13b9e087..9abe288afa 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt @@ -21,7 +21,7 @@ private fun modeOption() = Option("m", "mode", true, "mode, file is the default" * @return An instantiated but unpopulated [Config] object instance suitable for the mode into * which we've been placed. This Config object should be populated via [loadModeSpecificOptions] */ -fun getMode(args: Array) : Config { +fun getMode(args: Array): Config { // For now we only care what mode we're being put in, we can build the rest of the args and parse them // later val options = Options().apply { @@ -31,7 +31,7 @@ fun getMode(args: Array) : Config { val cmd = try { DefaultParser().parse(options, args, true) } catch (e: org.apache.commons.cli.ParseException) { - println (e) + println(e) HelpFormatter().printHelp("blobinspector", options) throw IllegalArgumentException("OH NO!!!") } @@ -56,10 +56,10 @@ fun loadModeSpecificOptions(config: Config, args: Array) { addOption(modeOption()) } - populate (try { + populate(try { DefaultParser().parse(modeSpecificOptions, args, false) } catch (e: org.apache.commons.cli.ParseException) { - println ("Error: ${e.message}") + println("Error: ${e.message}") HelpFormatter().printHelp("blobinspector", modeSpecificOptions) System.exit(1) return @@ -71,7 +71,7 @@ fun loadModeSpecificOptions(config: Config, args: Array) { * Executable entry point */ fun main(args: Array) { - println ("<<< WARNING: this tool is experimental and under active development >>>") + println("<<< WARNING: this tool is experimental and under active development >>>") getMode(args).let { mode -> loadModeSpecificOptions(mode, args) BlobHandler.make(mode) diff --git a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt index a018baaf49..c0a87a667e 100644 --- a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt +++ b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt @@ -5,13 +5,12 @@ import java.net.URI import org.junit.Test import net.corda.testing.common.internal.ProjectStructure.projectRootDir - class FileParseTests { @Suppress("UNUSED") - var localPath : URI = projectRootDir.toUri().resolve( + var localPath: URI = projectRootDir.toUri().resolve( "tools/blobinspector/src/test/resources/net/corda/blobinspector") - fun setupArgsWithFile(path: String) = Array(5) { + fun setupArgsWithFile(path: String) = Array(5) { when (it) { 0 -> "-m" 1 -> "file" @@ -22,7 +21,7 @@ class FileParseTests { } } - private val filesToTest = listOf ( + private val filesToTest = listOf( "FileParseTests.1Int", "FileParseTests.2Int", "FileParseTests.3Int", @@ -33,9 +32,9 @@ class FileParseTests { "FileParseTests.StringList", "FileParseTests.MapIntString", "FileParseTests.MapIntClass" - ) + ) - fun testFile(file : String) { + fun testFile(file: String) { val path = FileParseTests::class.java.getResource(file) val args = setupArgsWithFile(path.toString()) @@ -67,9 +66,15 @@ class FileParseTests { val args = verbose.let { if (it) - Array(4) { when (it) { 0 -> "-f" ; 1 -> path.toString(); 2 -> "-d"; 3 -> "-vs"; else -> "error" } } + Array(4) { + when (it) { 0 -> "-f"; 1 -> path.toString(); 2 -> "-d"; 3 -> "-vs"; else -> "error" + } + } else - Array(3) { when (it) { 0 -> "-f" ; 1 -> path.toString(); 2 -> "-d"; else -> "error" } } + Array(3) { + when (it) { 0 -> "-f"; 1 -> path.toString(); 2 -> "-d"; else -> "error" + } + } } val handler = getMode(args).let { mode -> @@ -78,7 +83,5 @@ class FileParseTests { } inspectBlob(handler.config, handler.getBytes()) - } - } diff --git a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt index 9b69363386..80560576a4 100644 --- a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt +++ b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt @@ -8,7 +8,7 @@ import kotlin.test.assertFalse class ModeParse { @Test fun fileIsSetToFile() { - val opts1 = Array(2) { + val opts1 = Array(2) { when (it) { 0 -> "-m" 1 -> "file" @@ -21,14 +21,14 @@ class ModeParse { @Test fun nothingIsSetToFile() { - val opts1 = Array(0) { "" } + val opts1 = Array(0) { "" } assertEquals(Mode.file, getMode(opts1).mode) } @Test fun filePathIsSet() { - val opts1 = Array(4) { + val opts1 = Array(4) { when (it) { 0 -> "-m" 1 -> "file" @@ -39,7 +39,7 @@ class ModeParse { } val config = getMode(opts1) - assertTrue (config is FileConfig) + assertTrue(config is FileConfig) assertEquals(Mode.file, config.mode) assertEquals("unset", (config as FileConfig).file) @@ -50,28 +50,34 @@ class ModeParse { @Test fun schemaIsSet() { - Array(2) { when (it) { 0 -> "-f"; 1 -> "path/to/file"; else -> "error" } }.let { options -> + Array(2) { + when (it) { 0 -> "-f"; 1 -> "path/to/file"; else -> "error" + } + }.let { options -> getMode(options).apply { loadModeSpecificOptions(this, options) - assertFalse (schema) + assertFalse(schema) } } - Array(3) { when (it) { 0 -> "--schema"; 1 -> "-f"; 2 -> "path/to/file"; else -> "error" } }.let { + Array(3) { + when (it) { 0 -> "--schema"; 1 -> "-f"; 2 -> "path/to/file"; else -> "error" + } + }.let { getMode(it).apply { loadModeSpecificOptions(this, it) - assertTrue (schema) + assertTrue(schema) } } - Array(3) { when (it) { 0 -> "-f"; 1 -> "path/to/file"; 2 -> "-s"; else -> "error" } }.let { + Array(3) { + when (it) { 0 -> "-f"; 1 -> "path/to/file"; 2 -> "-s"; else -> "error" + } + }.let { getMode(it).apply { loadModeSpecificOptions(this, it) - assertTrue (schema) + assertTrue(schema) } } - } - - } \ No newline at end of file diff --git a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt index 10d470685b..3dcafbc88d 100644 --- a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt +++ b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt @@ -8,8 +8,8 @@ class SimplifyClassTests { fun test1() { data class A(val a: Int) - println (A::class.java.name) - println (A::class.java.name.simplifyClass()) + println(A::class.java.name) + println(A::class.java.name.simplifyClass()) } @Test diff --git a/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt b/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt index 3dee28dbee..6cc530aeaf 100644 --- a/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt +++ b/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt @@ -23,7 +23,7 @@ import java.util.concurrent.ConcurrentHashMap class KryoHookAgent { companion object { @JvmStatic - fun premain(argumentsString: String?, instrumentation: Instrumentation) { + fun premain(@SuppressWarnings("unused") argumentsString: String?, instrumentation: Instrumentation) { Runtime.getRuntime().addShutdownHook(Thread { val statsTrees = KryoHook.events.values.flatMap { readTrees(it, 0).second @@ -61,9 +61,9 @@ fun prettyStatsTree(indent: Int, statsTree: StatsTree, builder: StringBuilder) { * Later we "parse" these lists into a tree. */ object KryoHook : ClassFileTransformer { - val classPool = ClassPool.getDefault() + val classPool = ClassPool.getDefault()!! - val hookClassName = javaClass.name + val hookClassName = javaClass.name!! override fun transform( loader: ClassLoader?, @@ -105,14 +105,14 @@ object KryoHook : ClassFileTransformer { val events = ConcurrentHashMap>() @JvmStatic - fun writeEnter(kryo: Kryo, output: Output, obj: Any) { + fun writeEnter(@SuppressWarnings("unused") kryo: Kryo, output: Output, obj: Any) { events.getOrPut(Strand.currentStrand().id) { ArrayList() }.add( StatsEvent.Enter(obj.javaClass.name, output.total()) ) } @JvmStatic - fun writeExit(kryo: Kryo, output: Output, obj: Any) { - events.get(Strand.currentStrand().id)!!.add( + fun writeExit(@SuppressWarnings("unused") kryo: Kryo, output: Output, obj: Any) { + events[Strand.currentStrand().id]!!.add( StatsEvent.Exit(obj.javaClass.name, output.total()) ) } diff --git a/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt b/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt index 787a2f7c4a..4e43987ede 100644 --- a/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt +++ b/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt @@ -154,9 +154,9 @@ class QuasarInstrumentationHookAgent { } object QuasarInstrumentationHook : ClassFileTransformer { - val classPool = ClassPool.getDefault() + val classPool = ClassPool.getDefault()!! - val hookClassName = "net.corda.quasarhook.QuasarInstrumentationHookKt" + const val hookClassName = "net.corda.quasarhook.QuasarInstrumentationHookKt" val instrumentMap = mapOf Unit>( "co/paralleluniverse/fibers/Stack" to { clazz -> @@ -208,10 +208,10 @@ object QuasarInstrumentationHook : ClassFileTransformer { data class Glob(val parts: List, val isFull: Boolean) { override fun toString(): String { - if (isFull) { - return parts.joinToString(".") + return if (isFull) { + parts.joinToString(".") } else { - return "${parts.joinToString(".")}**" + "${parts.joinToString(".")}**" } } } @@ -239,8 +239,8 @@ data class PackageTree(val branches: Map) { * Truncate the tree below [other]. */ fun truncate(other: PackageTree): PackageTree { - if (other.isEmpty()) { - return empty + return if (other.isEmpty()) { + empty } else { val truncatedBranches = HashMap(branches) other.branches.forEach { (key, tree) -> @@ -248,7 +248,7 @@ data class PackageTree(val branches: Map) { previousTree?.truncate(tree) ?: empty } } - return PackageTree(truncatedBranches) + PackageTree(truncatedBranches) } } diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java b/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java index fbc91767b6..c742cee8c8 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java @@ -65,7 +65,7 @@ public class CandidacyStatus { * @return true if the input was absent from the underlying map */ public boolean putIfAbsent(final String methodSignature) { - return null == candidateMethods.putIfAbsent(methodSignature, CandidateMethod.of(methodSignature)); + return candidateMethods.putIfAbsent(methodSignature, CandidateMethod.of(methodSignature)) == null; } /** @@ -176,10 +176,10 @@ public class CandidacyStatus { public Set getDisallowedMethods() { final Set out = new HashSet<>(); - for (final String candidateName : candidateMethods.keySet()) { - final CandidateMethod candidate = candidateMethods.get(candidateName); + for (final Map.Entry stringCandidateMethodEntry : candidateMethods.entrySet()) { + final CandidateMethod candidate = stringCandidateMethodEntry.getValue(); if (candidate.getCurrentState() == CandidateMethod.State.DISALLOWED) { - out.add(candidateName); + out.add(stringCandidateMethodEntry.getKey()); } } diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java b/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java index e9cc8dc8ab..9df01b5919 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java @@ -61,7 +61,8 @@ public final class SandboxAwareClassWriter extends ClassWriter { } public String getCommonSuperClassBorrowed(final String type1, final String type2) throws ClassNotFoundException { - Class c, d; + Class c; + Class d; try { c = Class.forName(type1.replace('/', '.'), false, loader); d = Class.forName(type2.replace('/', '.'), false, loader); diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java b/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java index d9993730af..d5be161248 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java @@ -18,9 +18,9 @@ import java.util.regex.Pattern; */ public final class Utils { - public final static String SANDBOX_PREFIX_INTERNAL = "sandbox/"; + public static final String SANDBOX_PREFIX_INTERNAL = "sandbox/"; - public final static String CLASSFILE_NAME_SUFFIX = "^(.*)\\.class$"; + public static final String CLASSFILE_NAME_SUFFIX = "^(.*)\\.class$"; public static final Pattern JAVA_LANG_PATTERN_INTERNAL = Pattern.compile("^java/lang/(.*)"); @@ -151,7 +151,7 @@ public final class Utils { return remaining; final StringBuilder out = new StringBuilder(); - while (remaining.length() > 0) { + while (!remaining.isEmpty()) { final Matcher refTypeFound = REFTYPE_PATTERN_INTERNAL.matcher(remaining); if (refTypeFound.find()) { final int startOfType = refTypeFound.start(); diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java b/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java index e1e44e0d73..fa34c1cab5 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java @@ -325,9 +325,9 @@ public final class WhitelistClassLoader extends ClassLoader { try (final FileSystem zfs = FileSystems.newFileSystem(zipUri, env)) { final Path jarRoot = zfs.getRootDirectories().iterator().next(); - for (final String newName : transformedClasses.keySet()) { - final byte[] newClassDef = transformedClasses.get(newName); - final String relativePathName = Utils.convertQualifiedClassNameToInternalForm(newName) + ".class"; + for (final Map.Entry stringEntry : transformedClasses.entrySet()) { + final byte[] newClassDef = stringEntry.getValue(); + final String relativePathName = Utils.convertQualifiedClassNameToInternalForm(stringEntry.getKey()) + ".class"; final Path outPath = jarRoot.resolve(relativePathName); Files.createDirectories(outPath.getParent()); diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java b/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java index 6cb16bcff6..06487859db 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java @@ -22,33 +22,13 @@ public class RuntimeCostAccounter { private static Thread primaryThread; - private static final ThreadLocal allocationCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal allocationCost = ThreadLocal.withInitial(() -> 0L); - private static final ThreadLocal jumpCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal jumpCost = ThreadLocal.withInitial(() -> 0L); - private static final ThreadLocal invokeCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal invokeCost = ThreadLocal.withInitial(() -> 0L); - private static final ThreadLocal throwCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal throwCost = ThreadLocal.withInitial(() -> 0L); private static final long BASELINE_ALLOC_KILL_THRESHOLD = 1024 * 1024; diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java b/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java index fcc575cd52..44d0232046 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java @@ -41,7 +41,7 @@ public final class SandboxCreator { private final WhitelistClassLoader wlcl; private final boolean hasInputJar; - private final static OptionParser parser = new OptionParser(); + private static final OptionParser parser = new OptionParser(); private static void usage() { System.err.println(USAGE_STRING); diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java b/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java index 652f7f3bd3..8b48746c25 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java @@ -21,8 +21,8 @@ import static org.junit.Assert.assertEquals; public class CandidateMethodTest { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(CandidateMethodTest.class); - private final static String OBJECT_INIT_METHOD = "java/lang/Object.:()V"; - private final static String SYSTEM_OUT_PRINTLN = "java/io/PrintStream.println:(Ljava/lang/String;)V"; + private static final String OBJECT_INIT_METHOD = "java/lang/Object.:()V"; + private static final String SYSTEM_OUT_PRINTLN = "java/io/PrintStream.println:(Ljava/lang/String;)V"; private CandidateMethod candidateMethod; diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java b/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java index bb9c713a72..fda7f308ee 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java @@ -11,11 +11,11 @@ package net.corda.sandbox; class Constants { - public final static String INVALID_CLASS = "foobar"; - public final static String BASE_DETERMINISTIC_METHODS = "resource/CallObjectMethods"; - public final static String SYSTEM_OUT_PRINTLN_CLASS = "resource/CallPrintln"; - public final static String INVOKEDYNAMIC_METHOD_CLASS = "resource/UseLambdaToForceInvokeDynamic"; - public final static String NATIVE_METHOD_CLASS = "resource/CallNative"; - public final static String BASIC_COLLECTIONS_CLASS = "resource/UseBasicCollections"; - public final static String FINALIZER_CLASS = "resource/UseFinalizer"; + public static final String INVALID_CLASS = "foobar"; + public static final String BASE_DETERMINISTIC_METHODS = "resource/CallObjectMethods"; + public static final String SYSTEM_OUT_PRINTLN_CLASS = "resource/CallPrintln"; + public static final String INVOKEDYNAMIC_METHOD_CLASS = "resource/UseLambdaToForceInvokeDynamic"; + public static final String NATIVE_METHOD_CLASS = "resource/CallNative"; + public static final String BASIC_COLLECTIONS_CLASS = "resource/UseBasicCollections"; + public static final String FINALIZER_CLASS = "resource/UseFinalizer"; } diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java b/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java index 77925be595..348cf3e4c6 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java @@ -10,21 +10,24 @@ package net.corda.sandbox; -import net.corda.sandbox.costing.*; -import org.junit.*; +import net.corda.sandbox.costing.RuntimeCostAccounter; +import org.junit.Assert; -import javax.xml.bind.*; -import java.io.*; -import java.nio.file.FileSystem; +import javax.xml.bind.DatatypeConverter; +import java.io.IOException; +import java.io.InputStream; import java.nio.file.*; -import java.nio.file.attribute.*; -import java.util.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; public class TestUtils { - private static ArrayList tmpFileSystems = new ArrayList<>(); + private static List tmpFileSystems = new ArrayList<>(); private static Path jarFSDir = null; private static Path tmpdir; diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java b/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java index bfabda662e..4e3ab755b6 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java @@ -12,8 +12,6 @@ package net.corda.sandbox; import static org.junit.Assert.*; -import org.junit.Test; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java b/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java index 1e3d3ea76b..4fb4aa4a45 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java @@ -105,7 +105,7 @@ public class SandboxedRewritingTest { final Object o = clz.newInstance(); final Method m = clz.getMethod("makeObject"); final Object ret = m.invoke(o); - assertTrue(Object.class == ret.getClass()); + assertTrue(ret.getClass() == Object.class); checkAllCosts(1, 0, 2, 0); } diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt index 36c064d62c..71ddcb122e 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt @@ -174,7 +174,7 @@ fun arrange(init: ContractBuilder.() -> Unit): Arrangement { data class Parameter(val initialValue: T) : Perceivable -fun variable(v: T) = Parameter(v) +fun variable(v: T) = Parameter(v) class RollOutBuilder(val startDate: LocalDate, val endDate: LocalDate, val frequency: Frequency, val vars: T) : ContractBuilder() { override fun final() = diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt index 85465bd04f..722cc064d7 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt @@ -44,7 +44,7 @@ data class Const(val value: T) : Perceivable { if (value is BigDecimal && other.value is BigDecimal) { return this.value.compareTo(other.value) == 0 } - return value.equals(other.value) + return value == other.value } return false } @@ -92,7 +92,7 @@ data class ActorPerceivable(val actor: Party) : Perceivable fun signedBy(actor: Party) : Perceivable = ActorPerceivable(actor) fun signedByOneOf(actors: Collection): Perceivable = - if (actors.size == 0) + if (actors.isEmpty()) const(true) else actors.drop(1).fold(signedBy(actors.first())) { total, next -> total or signedBy(next) } diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt index 993b432900..a23b91e0ce 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt @@ -67,7 +67,7 @@ private class PrettyPrint(arr : Arrangement) { camelName += "_" + partyMap.size.toString() } - partyMap.put(party.owningKey, camelName) + partyMap[party.owningKey] = camelName usedPartyNames.add(camelName) return camelName diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt index 23eae50e9c..f3fe1fdbfc 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt @@ -126,12 +126,12 @@ class UniversalContract : Contract { val arr = replaceStartEnd(rollOut.template, start.toInstant(), nextStart.toInstant()) - if (nextStart < end) { + return if (nextStart < end) { // TODO: we may have to save original start date in order to roll out correctly val newRollOut = RollOut(nextStart, end, rollOut.frequency, rollOut.template) - return replaceNext(arr, newRollOut) + replaceNext(arr, newRollOut) } else { - return removeNext(arr) + removeNext(arr) } } @@ -142,7 +142,7 @@ class UniversalContract : Contract { is EndDate -> uncheckedCast(const(end)) is StartDate -> uncheckedCast(const(start)) is UnaryPlus -> UnaryPlus(replaceStartEnd(p.arg, start, end)) - is PerceivableOperation -> PerceivableOperation(replaceStartEnd(p.left, start, end), p.op, replaceStartEnd(p.right, start, end)) + is PerceivableOperation -> PerceivableOperation(replaceStartEnd(p.left, start, end), p.op, replaceStartEnd(p.right, start, end)) is Interest -> uncheckedCast(Interest(replaceStartEnd(p.amount, start, end), p.dayCountConvention, replaceStartEnd(p.interest, start, end), replaceStartEnd(p.start, start, end), replaceStartEnd(p.end, start, end))) is Fixing -> uncheckedCast(Fixing(p.source, replaceStartEnd(p.date, start, end), p.tenor)) is PerceivableAnd -> uncheckedCast(replaceStartEnd(p.left, start, end) and replaceStartEnd(p.right, start, end)) @@ -231,7 +231,7 @@ class UniversalContract : Contract { 1 -> { val outState = tx.outputsOfType().single() requireThat { - "output state must match action result state" using (arrangement.equals(outState.details)) + "output state must match action result state" using (arrangement == outState.details) "output state must match action result state" using (rest == zero) } } @@ -240,7 +240,7 @@ class UniversalContract : Contract { val allContracts = And(tx.outputsOfType().map { it.details }.toSet()) requireThat { - "output states must match action result state" using (arrangement.equals(allContracts)) + "output states must match action result state" using (arrangement == allContracts) } } @@ -260,7 +260,7 @@ class UniversalContract : Contract { "the transaction is signed by all liable parties" using (liableParties(outState.details).all { it in cmd.signers }) "output state does not reflect move command" using - (replaceParty(inState.details, value.from, value.to).equals(outState.details)) + (replaceParty(inState.details, value.from, value.to) == outState.details) } } is Commands.Fix -> { @@ -279,7 +279,7 @@ class UniversalContract : Contract { requireThat { "relevant fixing must be included" using unusedFixes.isEmpty() "output state does not reflect fix command" using - (expectedArr.equals(outState.details)) + (expectedArr == outState.details) } } else -> throw IllegalArgumentException("Unrecognised command") diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt index d2fc151a58..cbb9fb0a27 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt @@ -30,7 +30,7 @@ private fun signingParties(perceivable: Perceivable) : ImmutableSet ImmutableSet.of() is TerminalEvent -> ImmutableSet.of( perceivable.reference ) is PerceivableComparison<*> -> ImmutableSet.of() // todo - else -> throw IllegalArgumentException("signingParties " + perceivable) + else -> throw IllegalArgumentException("signingParties $perceivable") } private fun liablePartiesVisitor(arrangement: Arrangement): ImmutableSet = @@ -43,7 +43,7 @@ private fun liablePartiesVisitor(arrangement: Arrangement): ImmutableSet(), { builder, k -> builder.addAll(liablePartiesVisitor(k)) }).build() is RollOut -> liablePartiesVisitor(arrangement.template) is Continuation -> ImmutableSet.of() - else -> throw IllegalArgumentException("liableParties " + arrangement) + else -> throw IllegalArgumentException("liableParties $arrangement") } private fun liablePartiesVisitor(action: Action): ImmutableSet { @@ -86,7 +86,7 @@ fun replaceParty(perceivable: Perceivable, from: Party, to: Party): Per is PerceivableAnd -> replaceParty(perceivable.left, from, to) and replaceParty(perceivable.right, from, to) is PerceivableOr -> replaceParty(perceivable.left, from, to) or replaceParty(perceivable.right, from, to) is TimePerceivable -> perceivable - else -> throw IllegalArgumentException("replaceParty " + perceivable) + else -> throw IllegalArgumentException("replaceParty $perceivable") } fun replaceParty(action: Action, from: Party, to: Party): Action = diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt index 2ffff5ae7d..383d8a1480 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt @@ -77,7 +77,7 @@ class Caplet { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, stateFixed) output(UNIVERSAL_PROGRAM_ID, stateFinal) @@ -93,7 +93,7 @@ class Caplet { } @Test - fun `fixing`() { + fun fixing() { transaction { input(UNIVERSAL_PROGRAM_ID, stateStart) output(UNIVERSAL_PROGRAM_ID, stateFixed) diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt index 76530a9e8e..928d237e39 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt @@ -24,17 +24,14 @@ val highStreetBank = TestIdentity(CordaX500Name("MegaCorp", "London", "GB")).par val momAndPop = TestIdentity(CordaX500Name("MiniCorp", "London", "GB")).party val acmeCorporationHasDefaulted = TerminalEvent(acmeCorp, generateKeyPair().public) - // Currencies val USD: Currency = Currency.getInstance("USD") val GBP: Currency = Currency.getInstance("GBP") val EUR: Currency = Currency.getInstance("EUR") val KRW: Currency = Currency.getInstance("KRW") - class ContractDefinition { - val cds_contract = arrange { actions { acmeCorp may { @@ -50,7 +47,6 @@ class ContractDefinition { } } - val american_fx_option = arrange { actions { acmeCorp may { @@ -67,7 +63,6 @@ class ContractDefinition { } } - val european_fx_option = arrange { actions { acmeCorp may { @@ -90,7 +85,6 @@ class ContractDefinition { } } - /* @Test fun `builder problem - should not compile`() { val arr = arrange { @@ -138,5 +132,4 @@ class ContractDefinition { assertEquals(1, arr.actions.size) } } - } diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt index c88ade6bed..ca9c1d0bc3 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt @@ -70,7 +70,7 @@ class FXSwap { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, inState) output(UNIVERSAL_PROGRAM_ID, outState1) diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt index 367e8214c9..682abad839 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt @@ -36,7 +36,6 @@ class RollOutTests { } } - val contract2 = arrange { rollOut("2016-09-01".ld, "2017-09-01".ld, Frequency.Monthly) { actions { @@ -167,7 +166,7 @@ class RollOutTests { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, stateStart) output(UNIVERSAL_PROGRAM_ID, stateStep1a) @@ -182,5 +181,4 @@ class RollOutTests { this.verifies() } } - } diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt index dbcd55f33c..71cfefcbcc 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt @@ -82,10 +82,9 @@ class Swaption { } } - @Test @Ignore + @Test + @Ignore fun `pretty print`() { - println ( prettyPrint(contractInitial) ) + println(prettyPrint(contractInitial)) } - - } diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt index f036bf93d5..34d3ee3c67 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt @@ -56,7 +56,6 @@ class ZeroCouponBond { assertEquals(Zero(), Zero()) } - @Test fun `issue - signature`() { transaction { @@ -71,7 +70,7 @@ class ZeroCouponBond { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, inState) output(UNIVERSAL_PROGRAM_ID, outState) @@ -115,21 +114,20 @@ class ZeroCouponBond { tweak { output(UNIVERSAL_PROGRAM_ID, outStateMove) command(acmeCorp.owningKey, - UniversalContract.Commands.Move(acmeCorp, momAndPop)) + UniversalContract.Commands.Move(acmeCorp, momAndPop)) this `fails with` "the transaction is signed by all liable parties" } tweak { output(UNIVERSAL_PROGRAM_ID, inState) command(listOf(acmeCorp.owningKey, momAndPop.owningKey, highStreetBank.owningKey), - UniversalContract.Commands.Move(acmeCorp, momAndPop)) + UniversalContract.Commands.Move(acmeCorp, momAndPop)) this `fails with` "output state does not reflect move command" } output(UNIVERSAL_PROGRAM_ID, outStateMove) command(listOf(acmeCorp.owningKey, momAndPop.owningKey, highStreetBank.owningKey), - UniversalContract.Commands.Move(acmeCorp, momAndPop)) + UniversalContract.Commands.Move(acmeCorp, momAndPop)) this.verifies() } } - } diff --git a/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java b/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java index aea9cd4948..30bcfe8f34 100644 --- a/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java +++ b/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java @@ -204,7 +204,7 @@ public class JavaCommercialPaper implements Contract { if (!cmd.getSigners().contains(input.getOwner().getOwningKey())) throw new IllegalStateException("Failed requirement: the transaction is signed by the owner of the CP"); - final Instant time = null == timeWindow + final Instant time = timeWindow == null ? null : timeWindow.getUntilTime(); final Amount> received = StateSumming.sumCashBy(tx.getOutputStates(), input.getOwner()); diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt b/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt index ca63fd69a4..3c483b3b11 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt @@ -52,7 +52,7 @@ import java.util.* * to do this in the Apache BVal project). */ -val CP_PROGRAM_ID = "net.corda.finance.contracts.CommercialPaper" +const val CP_PROGRAM_ID = "net.corda.finance.contracts.CommercialPaper" // TODO: Generalise the notion of an owned instrument into a superclass/supercontract. Consider composition vs inheritance. class CommercialPaper : Contract { diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt b/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt index 6327e39551..cf263e9008 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt @@ -97,9 +97,8 @@ data class Tenor(val name: String) { } // Move date to the closest business day when it falls on a weekend/holiday val adjustedMaturityDate = calendar.applyRollConvention(maturityDate, DateRollConvention.ModifiedFollowing) - val daysToMaturity = BusinessCalendar.calculateDaysBetween(startDate, adjustedMaturityDate, DayCountBasisYear.Y360, DayCountBasisDay.DActual) - return daysToMaturity + return BusinessCalendar.calculateDaysBetween(startDate, adjustedMaturityDate, DayCountBasisYear.Y360, DayCountBasisDay.DActual) } override fun toString(): String = name diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt index 0726495352..80a6ad48d3 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt @@ -56,7 +56,7 @@ private fun rowsToAmount(currency: Currency, rows: Vault.Page>) private fun rowsToBalances(rows: List): Map> { val balances = LinkedHashMap>() - for (index in 0..rows.size - 1 step 2) { + for (index in 0 until rows.size step 2) { val ccy = Currency.getInstance(rows[index + 1] as String) balances[ccy] = Amount(rows[index] as Long, ccy) } diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt index 83f7b0b700..44ec6b8fc7 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt @@ -56,7 +56,7 @@ import java.util.* */ class Cash : OnLedgerAsset() { override fun extractCommands(commands: Collection>): List> - = commands.select() + = commands.select() // DOCSTART 1 /** A state representing a cash claim against some party. */ @@ -169,7 +169,7 @@ class Cash : OnLedgerAsset() { // If we want to remove cash from the ledger, that must be signed for by the issuer. // A mis-signed or duplicated exit command will just be ignored here and result in the exit amount being zero. val exitKeys: Set = inputs.flatMap { it.exitKeys }.toSet() - val exitCommand = tx.commands.select(parties = null, signers = exitKeys).filter { it.value.amount.token == key }.singleOrNull() + val exitCommand = tx.commands.select(parties = null, signers = exitKeys).singleOrNull { it.value.amount.token == key } val amountExitingLedger = exitCommand?.value?.amount ?: Amount(0, Issued(issuer, currency)) requireThat { diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt index 0bd48f233c..f66c84567e 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt @@ -156,7 +156,7 @@ class CommodityContract : OnLedgerAsset>): List> - = commands.select() + = commands.select() /** * Puts together an issuance transaction from the given template, that starts out being owned by the given pubkey. diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt index ab408a2736..ca09385609 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt @@ -10,11 +10,23 @@ package net.corda.finance.contracts.asset -import net.corda.core.contracts.* -import net.corda.finance.contracts.NetCommand -import net.corda.finance.contracts.NetType -import net.corda.finance.contracts.NettableState -import net.corda.finance.contracts.asset.Obligation.Lifecycle.NORMAL +import net.corda.core.contracts.Amount +import net.corda.core.contracts.CommandAndState +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.CommandWithParties +import net.corda.core.contracts.Contract +import net.corda.core.contracts.ContractClassName +import net.corda.core.contracts.ContractState +import net.corda.core.contracts.FungibleAsset +import net.corda.core.contracts.InsufficientBalanceException +import net.corda.core.contracts.Issued +import net.corda.core.contracts.MoveCommand +import net.corda.core.contracts.StateAndRef +import net.corda.core.contracts.TransactionState +import net.corda.core.contracts.TypeOnlyCommandData +import net.corda.core.contracts.requireThat +import net.corda.core.contracts.select +import net.corda.core.contracts.verifyMoveCommand import net.corda.core.crypto.SecureHash import net.corda.core.identity.AbstractParty import net.corda.core.identity.AnonymousParty @@ -26,6 +38,10 @@ import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.NonEmptySet import net.corda.core.utilities.seconds +import net.corda.finance.contracts.NetCommand +import net.corda.finance.contracts.NetType +import net.corda.finance.contracts.NettableState +import net.corda.finance.contracts.asset.Obligation.Lifecycle.NORMAL import net.corda.finance.utils.sumFungibleOrNull import net.corda.finance.utils.sumObligations import net.corda.finance.utils.sumObligationsOrNull @@ -169,12 +185,12 @@ class Obligation

: Contract { val netB = other.bilateralNetState require(netA == netB) { "net substates of the two state objects must be identical" } - if (obligor.owningKey == other.obligor.owningKey) { + return if (obligor.owningKey == other.obligor.owningKey) { // Both sides are from the same obligor to beneficiary - return copy(quantity = quantity + other.quantity) + copy(quantity = quantity + other.quantity) } else { // Issuer and beneficiary are backwards - return copy(quantity = quantity - other.quantity) + copy(quantity = quantity - other.quantity) } } @@ -275,7 +291,7 @@ class Obligation

: Contract { // If we want to remove obligations from the ledger, that must be signed for by the issuer. // A mis-signed or duplicated exit command will just be ignored here and result in the exit amount being zero. val exitKeys: Set = inputs.flatMap { it.exitKeys }.toSet() - val exitCommand = tx.commands.select>(parties = null, signers = exitKeys).filter { it.value.amount.token == key }.singleOrNull() + val exitCommand = tx.commands.select>(parties = null, signers = exitKeys).singleOrNull { it.value.amount.token == key } val amountExitingLedger = exitCommand?.value?.amount ?: Amount(0, Issued(issuer, terms)) requireThat { @@ -322,7 +338,7 @@ class Obligation

: Contract { groupingKey: Issued>) { val obligor = groupingKey.issuer.party val template = groupingKey.product - val inputAmount: Amount>> = inputs.sumObligationsOrNull

() ?: throw IllegalArgumentException("there is at least one obligation input for this group") + val inputAmount: Amount>> = inputs.sumObligationsOrNull() ?: throw IllegalArgumentException("there is at least one obligation input for this group") val outputAmount: Amount>> = outputs.sumObligationsOrZero(groupingKey) // Sum up all asset state objects that are moving and fulfil our requirements @@ -512,12 +528,14 @@ class Obligation

: Contract { */ @Suppress("unused") fun generateExit(tx: TransactionBuilder, amountIssued: Amount>>, - assetStates: List>>): Set - = OnLedgerAsset.generateExit(tx, amountIssued, assetStates, - deriveState = { state, amount, owner -> state.copy(data = state.data.withNewOwnerAndAmount(amount, owner)) }, - generateMoveCommand = { -> Commands.Move() }, - generateExitCommand = { amount -> Commands.Exit(amount) } - ) + assetStates: List>>): Set { + val changeOwner = assetStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amountIssued) + return OnLedgerAsset.generateExit(tx, amountIssued, assetStates, changeOwner, + deriveState = { state, amount, owner -> state.copy(data = state.data.withNewOwnerAndAmount(amount, owner)) }, + generateMoveCommand = { Commands.Move() }, + generateExitCommand = { amount -> Commands.Exit(amount) } + ) + } /** * Puts together an issuance transaction for the specified currency obligation amount that starts out being owned by @@ -578,7 +596,7 @@ class Obligation

: Contract { val signers = states.map { it.beneficiary }.union(states.map { it.obligor }).toSet() // Create a lookup table of the party that each public key represents. - states.map { it.obligor }.forEach { partyLookup.put(it.owningKey, it) } + states.map { it.obligor }.forEach { partyLookup[it.owningKey] = it } // Suppress compiler warning as 'groupStates' is an unused variable when destructuring 'groups'. @Suppress("UNUSED_VARIABLE") @@ -676,15 +694,15 @@ class Obligation

: Contract { val assetState = ref.state.data val amount = Amount(assetState.amount.quantity, assetState.amount.token.product) - if (obligationRemaining >= amount) { + obligationRemaining -= if (obligationRemaining >= amount) { tx.addOutputState(assetState.withNewOwnerAndAmount(assetState.amount, obligationOwner), PROGRAM_ID, notary) - obligationRemaining -= amount + amount } else { val change = Amount(obligationRemaining.quantity, assetState.amount.token) // Split the state in two, sending the change back to the previous beneficiary tx.addOutputState(assetState.withNewOwnerAndAmount(change, obligationOwner), PROGRAM_ID, notary) tx.addOutputState(assetState.withNewOwnerAndAmount(assetState.amount - change, assetState.owner), PROGRAM_ID, notary) - obligationRemaining -= Amount(0L, obligationRemaining.token) + Amount(0L, obligationRemaining.token) } assetSigners.add(assetState.owner) } diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt index bd20bf7414..8086daab42 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt @@ -40,7 +40,7 @@ data class PartyAndAmount(val party: AbstractParty, val amount: Amount< * At the same time, other contracts that just want assets and don't care much who is currently holding it can ignore * the issuer/depositRefs and just examine the amount fields. */ -abstract class OnLedgerAsset> : Contract { +abstract class OnLedgerAsset> : Contract { companion object { private val log = contextLogger() /** @@ -84,8 +84,6 @@ abstract class OnLedgerAsset> : C * * @param tx A builder, which may contain inputs, outputs and commands already. The relevant components needed * to move the cash will be added on top. - * @param amount How much currency to send. - * @param to a key of the recipient. * @param acceptableStates a list of acceptable input states to use. * @param payChangeTo party to pay any change to; this is normally a confidential identity of the calling * party. We use a new confidential identity here so that the recipient is not identifiable. @@ -240,11 +238,11 @@ abstract class OnLedgerAsset> : C @Throws(InsufficientBalanceException::class) @JvmStatic @Deprecated("Replaced with generateExit() which takes in a party to pay change to") - fun , T: Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, - assetStates: List>, - deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, - generateMoveCommand: () -> CommandData, - generateExitCommand: (Amount>) -> CommandData): Set { + fun , T : Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, + assetStates: List>, + deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, + generateMoveCommand: () -> CommandData, + generateExitCommand: (Amount>) -> CommandData): Set { val owner = assetStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amountIssued) return generateExit(tx, amountIssued, assetStates, owner, deriveState, generateMoveCommand, generateExitCommand) } @@ -262,16 +260,16 @@ abstract class OnLedgerAsset> : C */ @Throws(InsufficientBalanceException::class) @JvmStatic - fun , T: Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, - assetStates: List>, - payChangeTo: AbstractParty, - deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, - generateMoveCommand: () -> CommandData, - generateExitCommand: (Amount>) -> CommandData): Set { + fun , T : Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, + assetStates: List>, + payChangeTo: AbstractParty, + deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, + generateMoveCommand: () -> CommandData, + generateExitCommand: (Amount>) -> CommandData): Set { require(assetStates.isNotEmpty()) { "List of states to exit cannot be empty." } val currency = amountIssued.token.product val amount = Amount(amountIssued.quantity, currency) - var acceptableCoins = assetStates.filter { ref -> ref.state.data.amount.token == amountIssued.token } + var acceptableCoins = assetStates.filter { (state) -> state.data.amount.token == amountIssued.token } tx.notary = acceptableCoins.firstOrNull()?.state?.notary // TODO: We should be prepared to produce multiple transactions exiting inputs from // different notaries, or at least group states by notary and take the set with the @@ -328,20 +326,20 @@ abstract class OnLedgerAsset> : C * @param amountIssued the amount to be exited, represented as a quantity of issued currency. * @param assetStates the asset states to take funds from. No checks are done about ownership of these states, it is * the responsibility of the caller to check that they do not exit funds held by others. - * @param payChangeTo party to pay any change to; this is normally a confidential identity of the calling - * party. * @return the public keys which must sign the transaction for it to be valid. */ @Throws(InsufficientBalanceException::class) @Deprecated("Replaced with generateExit() which takes in a party to pay change to") fun generateExit(tx: TransactionBuilder, amountIssued: Amount>, assetStates: List>): Set { + val changeOwner = assetStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amountIssued) return generateExit( tx, amountIssued, assetStates, + changeOwner, deriveState = { state, amount, owner -> deriveState(state, amount, owner) }, - generateMoveCommand = { -> generateMoveCommand() }, + generateMoveCommand = { generateMoveCommand() }, generateExitCommand = { amount -> generateExitCommand(amount) } ) } @@ -365,7 +363,7 @@ abstract class OnLedgerAsset> : C assetStates, payChangeTo, deriveState = { state, amount, owner -> deriveState(state, amount, owner) }, - generateMoveCommand = { -> generateMoveCommand() }, + generateMoveCommand = { generateMoveCommand() }, generateExitCommand = { amount -> generateExitCommand(amount) } ) } diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt index 9b764ea445..7f7ecea797 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt @@ -18,6 +18,7 @@ import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowLogic import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.node.ServiceHub import net.corda.core.node.services.StatesNotAvailableException import net.corda.core.utilities.* @@ -45,13 +46,13 @@ abstract class AbstractCashSelection(private val maxRetries : Int = 8, private v fun getInstance(metadata: () -> java.sql.DatabaseMetaData): AbstractCashSelection { return instance.get() ?: { - val _metadata = metadata() + val metadataLocal = metadata() val cashSelectionAlgos = ServiceLoader.load(AbstractCashSelection::class.java, this::class.java.classLoader).toList() - val cashSelectionAlgo = cashSelectionAlgos.firstOrNull { it.isCompatible(_metadata) } + val cashSelectionAlgo = cashSelectionAlgos.firstOrNull { it.isCompatible(metadataLocal) } cashSelectionAlgo?.let { instance.set(cashSelectionAlgo) cashSelectionAlgo - } ?: throw ClassNotFoundException("\nUnable to load compatible cash selection algorithm implementation for JDBC driver name '${_metadata.driverName}'." + + } ?: throw ClassNotFoundException("\nUnable to load compatible cash selection algorithm implementation for JDBC driver name '${metadataLocal.driverName}'." + "\nPlease specify an implementation in META-INF/services/${AbstractCashSelection::class.qualifiedName}." + "\nAvailable implementations: $cashSelectionAlgos") }.invoke() @@ -73,7 +74,6 @@ abstract class AbstractCashSelection(private val maxRetries : Int = 8, private v /** * A vendor specific query(ies) to gather Cash states that are available. - * @param statement The service hub to allow access to the database session * @param amount The amount of currency desired (ignoring issues, but specifying the currency) * @param lockId The FlowLogic.runId.uuid of the flow, which is used to soft reserve the states. * Also, previous outputs of the flow will be eligible as they are implicitly locked with this id until the flow completes. @@ -156,7 +156,7 @@ abstract class AbstractCashSelection(private val maxRetries : Int = 8, private v if (stateRefs.isNotEmpty()) { // TODO: future implementation to retrieve contract states from a Vault BLOB store - stateAndRefs.addAll(services.loadStates(stateRefs) as Collection>) + stateAndRefs.addAll(uncheckedCast(services.loadStates(stateRefs))) } val success = stateAndRefs.isNotEmpty() && totalPennies >= amount.quantity diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt index 33053ddabf..19b6ad192d 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt @@ -80,7 +80,7 @@ class CashSelectionPostgreSQLImpl : AbstractCashSelection() { paramOffset += 1 } withIssuerRefs.map { it.bytes }.forEach { - statement.setBytes( 3 + paramOffset, it) + statement.setBytes(3 + paramOffset, it) paramOffset += 1 } statement.setLong(3 + paramOffset, amount.quantity) diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt b/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt index 00a49cb107..5327933458 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt @@ -110,7 +110,7 @@ class CubicSplineInterpolator(private val xs: DoubleArray, private val ys: Doubl val segmentMap = TreeMap() for (i in 0 until n) { val coefficients = doubleArrayOf(ys[i], b[i], c[i], d[i]) - segmentMap.put(xs[i], Polynomial(coefficients)) + segmentMap[xs[i]] = Polynomial(coefficients) } return SplineFunction(segmentMap) } diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt index d232afc6d3..2b242e568d 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt @@ -43,7 +43,7 @@ class ConfigHolder(services: AppServiceHub) : SingletonSerializeAsToken() { // Warning!! You are about to see a major hack! val baseDirectory = services.declaredField("serviceHub").value .let { it.javaClass.getMethod("getConfiguration").apply { isAccessible = true }.invoke(it) } - .let { it.javaClass.getMethod("getBaseDirectory").apply { isAccessible = true }.invoke(it)} + .let { it.javaClass.getMethod("getBaseDirectory").apply { isAccessible = true }.invoke(it) } .let { it.javaClass.getMethod("toString").apply { isAccessible = true }.invoke(it) as String } var issuableCurrenciesValue: List @@ -62,7 +62,6 @@ class ConfigHolder(services: AppServiceHub) : SingletonSerializeAsToken() { } } - /** * Flow to obtain cash cordapp app configuration. */ diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt index c6e85be18a..dfa3e6788e 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt @@ -25,9 +25,6 @@ import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.ProgressTracker import net.corda.finance.contracts.asset.Cash import net.corda.finance.contracts.asset.cash.selection.AbstractCashSelection -import net.corda.finance.flows.AbstractCashFlow.Companion.FINALISING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.finance.issuedBy import java.util.* @@ -63,10 +60,12 @@ class CashExitFlow(private val amount: Amount, .getInstance { serviceHub.jdbcSession().metaData } .unconsumedCashStatesForSpending(serviceHub, amount, setOf(issuer.party), builder.notary, builder.lockId, setOf(issuer.reference)) val signers = try { + val changeOwner = exitStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amount) Cash().generateExit( builder, amount.issuedBy(issuer), - exitStates) + exitStates, + changeOwner) } catch (e: InsufficientBalanceException) { throw CashException("Exiting more cash than exists", e) } diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt index 15222ffbc8..2028be75f6 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt @@ -37,7 +37,7 @@ class CashIssueAndPaymentFlow(val amount: Amount, val anonymous: Boolean, val notary: Party, progressTracker: ProgressTracker) : AbstractCashFlow(progressTracker) { - constructor(amount: Amount, + constructor(amount: Amount, issueRef: OpaqueBytes, recipient: Party, anonymous: Boolean, diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt index 8614ca1318..13018f69d0 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt @@ -19,9 +19,6 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.ProgressTracker import net.corda.finance.contracts.asset.Cash -import net.corda.finance.flows.AbstractCashFlow.Companion.FINALISING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.finance.issuedBy import java.util.* diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt index 4f5b785e9a..7c809bcc65 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt @@ -21,10 +21,6 @@ import net.corda.core.serialization.CordaSerializable import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.ProgressTracker import net.corda.finance.contracts.asset.Cash -import net.corda.finance.flows.AbstractCashFlow.Companion.FINALISING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_ID -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.SIGNING_TX import java.util.* /** diff --git a/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt b/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt index 0ddf6108ba..6049e3525c 100644 --- a/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt +++ b/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt @@ -21,7 +21,7 @@ import com.fasterxml.jackson.databind.module.SimpleModule import net.corda.finance.contracts.BusinessCalendar import java.time.LocalDate -fun registerFinanceJSONMappers(objectMapper: ObjectMapper): Unit { +fun registerFinanceJSONMappers(objectMapper: ObjectMapper) { val financeModule = SimpleModule("finance").apply { addSerializer(BusinessCalendar::class.java, CalendarSerializer) addDeserializer(BusinessCalendar::class.java, CalendarDeserializer) diff --git a/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt b/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt index 53c5832b15..8feffb9f7e 100644 --- a/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt +++ b/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt @@ -72,13 +72,10 @@ fun Iterable.sumCommoditiesOrZero(currency: Issued) = * Sums the obligation states in the list, throwing an exception if there are none. All state objects in the * list are presumed to be nettable. */ -fun

Iterable.sumObligations(): Amount>> - = filterIsInstance>().map { it.amount }.sumOrThrow() +fun

Iterable.sumObligations(): Amount>> = filterIsInstance>().map { it.amount }.sumOrThrow() /** Sums the obligation states in the list, returning null if there are none. */ -fun

Iterable.sumObligationsOrNull(): Amount>>? - = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrNull() +fun

Iterable.sumObligationsOrNull(): Amount>>? = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrNull() /** Sums the obligation states in the list, returning zero of the given product if there are none. */ -fun

Iterable.sumObligationsOrZero(issuanceDef: Issued>): Amount>> - = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrZero(issuanceDef) +fun

Iterable.sumObligationsOrZero(issuanceDef: Issued>): Amount>> = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrZero(issuanceDef) diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt index 9c7493f973..da44948651 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt @@ -29,7 +29,7 @@ import java.util.* class DummyFungibleContract : OnLedgerAsset() { override fun extractCommands(commands: Collection>): List> - = commands.select() + = commands.select() data class State( override val amount: Amount>, @@ -119,7 +119,7 @@ class DummyFungibleContract : OnLedgerAsset = inputs.flatMap { it.exitKeys }.toSet() - val exitCommand = tx.commands.select(parties = null, signers = exitKeys).filter { it.value.amount.token == key }.singleOrNull() + val exitCommand = tx.commands.select(parties = null, signers = exitKeys).singleOrNull { it.value.amount.token == key } val amountExitingLedger = exitCommand?.value?.amount ?: Amount(0, Issued(issuer, currency)) requireThat { diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt index ed7c9af8c3..0149760736 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt @@ -618,8 +618,8 @@ class ObligationTests { val futureTestTime = TEST_TX_TIME + 7.days transaction { attachments(Obligation.PROGRAM_ID) - input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` futureTestTime) - output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` futureTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) + input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at futureTestTime) + output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at futureTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) command(BOB_PUBKEY, Obligation.Commands.SetLifecycle(Lifecycle.DEFAULTED)) timeWindow(TEST_TX_TIME) this `fails with` "the due date has passed" @@ -629,8 +629,8 @@ class ObligationTests { ledgerServices.ledger(DUMMY_NOTARY) { transaction { attachments(Obligation.PROGRAM_ID) - input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` pastTestTime) - output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` pastTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) + input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at pastTestTime) + output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at pastTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) command(BOB_PUBKEY, Obligation.Commands.SetLifecycle(Lifecycle.DEFAULTED)) timeWindow(TEST_TX_TIME) this.verifies() diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt b/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt index aa7303fc6a..07975e2e92 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt @@ -41,13 +41,11 @@ class InterpolatorsTest { @Test fun `linear interpolator interpolates missing values correctly`() { val xs = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0) - val ys = xs val toInterpolate = doubleArrayOf(1.5, 2.5, 2.8, 3.3, 3.7, 4.3, 4.7) - val expected = toInterpolate - val interpolator = LinearInterpolator(xs, ys) + val interpolator = LinearInterpolator(xs, xs) val actual = toInterpolate.map { interpolator.interpolate(it) }.toDoubleArray() - Assert.assertArrayEquals(expected, actual, 0.01) + Assert.assertArrayEquals(toInterpolate, actual, 0.01) } @Test diff --git a/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt b/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt index a485d76909..c82d0b7c83 100644 --- a/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt @@ -38,7 +38,7 @@ class CashIssueFlowTests { servicePeerAllocationStrategy = RoundRobin(), cordappPackages = listOf("net.corda.finance.contracts.asset", "net.corda.finance.schemas")) bankOfCordaNode = mockNet.createPartyNode(BOC_NAME) - bankOfCorda = bankOfCordaNode.info.identityFromX500Name(BOC_NAME) + bankOfCorda = bankOfCordaNode.info.identityFromX500Name(BOC_NAME) notary = mockNet.defaultNotaryIdentity } diff --git a/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt b/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt index 239c70459f..0ec686e5dd 100644 --- a/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt +++ b/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt @@ -39,7 +39,7 @@ object SampleCashSchemaV2 : MappedSchema(schemaFamily = CashSchema.javaClass, ve @ElementCollection @Column(name = "participants") - @CollectionTable(name="cash_states_v2_participants", joinColumns = [JoinColumn(name = "output_index", referencedColumnName = "output_index"), JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")]) + @CollectionTable(name = "cash_states_v2_participants", joinColumns = [JoinColumn(name = "output_index", referencedColumnName = "output_index"), JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")]) override var participants: MutableSet? = null } } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt index a5cdeb1207..98dd29e455 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt @@ -113,7 +113,7 @@ class ArtemisTcpTransport { direction: ConnectionDirection, hostAndPortList: List, config: SSLConfiguration?, - enableSSL: Boolean = true): List{ + enableSSL: Boolean = true): List { val tcpTransports = ArrayList(hostAndPortList.size) hostAndPortList.forEach { tcpTransports.add(tcpTransport(direction, it, config, enableSSL)) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt b/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt index d8389cf60f..5abb190eca 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt @@ -258,22 +258,22 @@ object RPCApi { } } -private val TAG_FIELD_NAME = "tag" -private val RPC_ID_FIELD_NAME = "rpc-id" -private val RPC_ID_TIMESTAMP_FIELD_NAME = "rpc-id-timestamp" -private val RPC_SESSION_ID_FIELD_NAME = "rpc-session-id" -private val RPC_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-session-id-timestamp" -private val RPC_EXTERNAL_ID_FIELD_NAME = "rpc-external-id" -private val RPC_EXTERNAL_ID_TIMESTAMP_FIELD_NAME = "rpc-external-id-timestamp" -private val RPC_EXTERNAL_SESSION_ID_FIELD_NAME = "rpc-external-session-id" -private val RPC_EXTERNAL_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-external-session-id-timestamp" -private val RPC_IMPERSONATED_ACTOR_ID = "rpc-impersonated-actor-id" -private val RPC_IMPERSONATED_ACTOR_STORE_ID = "rpc-impersonated-actor-store-id" -private val RPC_IMPERSONATED_ACTOR_OWNING_LEGAL_IDENTITY = "rpc-impersonated-actor-owningLegalIdentity" -private val DEDUPLICATION_IDENTITY_FIELD_NAME = "deduplication-identity" -private val OBSERVABLE_ID_FIELD_NAME = "observable-id" -private val OBSERVABLE_ID_TIMESTAMP_FIELD_NAME = "observable-id-timestamp" -private val METHOD_NAME_FIELD_NAME = "method-name" +private const val TAG_FIELD_NAME = "tag" +private const val RPC_ID_FIELD_NAME = "rpc-id" +private const val RPC_ID_TIMESTAMP_FIELD_NAME = "rpc-id-timestamp" +private const val RPC_SESSION_ID_FIELD_NAME = "rpc-session-id" +private const val RPC_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-session-id-timestamp" +private const val RPC_EXTERNAL_ID_FIELD_NAME = "rpc-external-id" +private const val RPC_EXTERNAL_ID_TIMESTAMP_FIELD_NAME = "rpc-external-id-timestamp" +private const val RPC_EXTERNAL_SESSION_ID_FIELD_NAME = "rpc-external-session-id" +private const val RPC_EXTERNAL_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-external-session-id-timestamp" +private const val RPC_IMPERSONATED_ACTOR_ID = "rpc-impersonated-actor-id" +private const val RPC_IMPERSONATED_ACTOR_STORE_ID = "rpc-impersonated-actor-store-id" +private const val RPC_IMPERSONATED_ACTOR_OWNING_LEGAL_IDENTITY = "rpc-impersonated-actor-owningLegalIdentity" +private const val DEDUPLICATION_IDENTITY_FIELD_NAME = "deduplication-identity" +private const val OBSERVABLE_ID_FIELD_NAME = "observable-id" +private const val OBSERVABLE_ID_TIMESTAMP_FIELD_NAME = "observable-id-timestamp" +private const val METHOD_NAME_FIELD_NAME = "method-name" fun ClientMessage.replyId(): InvocationId { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt index 50dad2c62d..606e2e63c6 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt @@ -59,7 +59,6 @@ class ArtemisMessagingComponent { */ val bridgedCertificateSubject = SimpleString("sender-subject-name") - object Type { const val KEY = "corda_p2p_message_type" const val SESSION_INIT_VALUE = "session_init" @@ -138,5 +137,4 @@ class ArtemisMessagingComponent { override val queueName: String = "$P2P_PREFIX${identity.toStringShort()}" } - } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt index 0b8657600b..f395bc84cc 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt @@ -70,6 +70,7 @@ inline fun NodeInfo.sign(signer: (PublicKey, SerializedBytes) -> Digit class NodeInfoAndSigned private constructor(val nodeInfo: NodeInfo, val signed: SignedNodeInfo) { constructor(nodeInfo: NodeInfo, signer: (PublicKey, SerializedBytes) -> DigitalSignature) : this(nodeInfo, nodeInfo.sign(signer)) constructor(signedNodeInfo: SignedNodeInfo) : this(signedNodeInfo.verified(), signedNodeInfo) + operator fun component1(): NodeInfo = nodeInfo operator fun component2(): SignedNodeInfo = signed } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt index 398ff0f16e..88ce5a2442 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt @@ -48,7 +48,7 @@ import kotlin.concurrent.withLock * The Netty thread pool used by the AMQPBridges is also shared and managed by the AMQPBridgeManager. */ @VisibleForTesting -class AMQPBridgeManager(config: NodeSSLConfiguration, private val socksProxyConfig: SocksProxyConfig? = null, val artemisMessageClientFactory: () -> ArtemisSessionProvider) : BridgeManager { +class AMQPBridgeManager(config: NodeSSLConfiguration, private val socksProxyConfig: SocksProxyConfig? = null, private val artemisMessageClientFactory: () -> ArtemisSessionProvider) : BridgeManager { private val lock = ReentrantLock() private val bridgeNameToBridgeMap = mutableMapOf() diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt index df273842a6..2029a47923 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt @@ -16,6 +16,6 @@ data class User( val password: String, val permissions: Set) { override fun toString(): String = "${javaClass.simpleName}($username, permissions=$permissions)" - @Deprecated("Use toConfig().root().unwrapped() instead") + @Deprecated("Use toConfig().root().unwrapped() instead", ReplaceWith("toConfig().root().unwrapped()")) fun toMap(): Map = toConfig().root().unwrapped() } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt index bc49c77ad0..4f568bdca8 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt @@ -23,7 +23,6 @@ import net.corda.nodeapi.internal.crypto.X509Utilities import java.security.cert.X509Certificate import java.time.Instant - const val NETWORK_PARAMS_FILE_NAME = "network-parameters" const val NETWORK_PARAMS_UPDATE_FILE_NAME = "network-parameters-update" @@ -81,6 +80,7 @@ fun SignedDataWithCert.verifiedNetworkMapCert(rootCert: X509Certifi class NetworkMapAndSigned private constructor(val networkMap: NetworkMap, val signed: SignedNetworkMap) { constructor(networkMap: NetworkMap, signer: (SerializedBytes) -> DigitalSignatureWithCert) : this(networkMap, networkMap.signWithCert(signer)) constructor(signed: SignedNetworkMap) : this(signed.verified(), signed) + operator fun component1(): NetworkMap = networkMap operator fun component2(): SignedNetworkMap = signed } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt index 18135fa042..a9e0c7e0ab 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt @@ -290,10 +290,8 @@ fun isH2Database(jdbcUrl: String) = jdbcUrl.startsWith("jdbc:h2:") /** Check if any nested cause is of [SQLException] type. */ private fun Throwable.hasSQLExceptionCause(): Boolean = - if (cause == null) - false - else if (cause is SQLException) - true - else - cause?.hasSQLExceptionCause() ?: false - + when (cause) { + null -> false + is SQLException -> true + else -> cause?.hasSQLExceptionCause() ?: false + } \ No newline at end of file diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt index b7c3601cc0..cbaaba123d 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt @@ -176,8 +176,8 @@ class HibernateConfiguration( } // A tweaked version of `org.hibernate.type.descriptor.java.PrimitiveByteArrayTypeDescriptor` that truncates logged messages. - object CordaPrimitiveByteArrayTypeDescriptor : PrimitiveByteArrayTypeDescriptor() { - private val LOG_SIZE_LIMIT = 1024 + private object CordaPrimitiveByteArrayTypeDescriptor : PrimitiveByteArrayTypeDescriptor() { + private const val LOG_SIZE_LIMIT = 1024 override fun extractLoggableRepresentation(value: ByteArray?): String { return if (value == null) { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt index dbf93ec26e..6f1ca23897 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt @@ -72,6 +72,7 @@ internal class ConnectionStateMachine(serverMode: Boolean, transport = Engine.transport() transport.idleTimeout = IDLE_TIMEOUT transport.context = connection + @Suppress("UsePropertyAccessSyntax") transport.setEmitFlowEventOnSend(true) connection.collect(collector) val sasl = transport.sasl() diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPChannelHandler.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPChannelHandler.kt index ad5a22bae9..e39e263df6 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPChannelHandler.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPChannelHandler.kt @@ -101,31 +101,42 @@ internal class AMQPChannelHandler(private val serverMode: Boolean, val sslHandler = ctx.pipeline().get(SslHandler::class.java) localCert = sslHandler.engine().session.localCertificates[0].x509 remoteCert = sslHandler.engine().session.peerCertificates[0].x509 - try { - val remoteX500Name = CordaX500Name.build(remoteCert!!.subjectX500Principal) - require(allowedRemoteLegalNames == null || remoteX500Name in allowedRemoteLegalNames) - log.info("handshake completed subject: $remoteX500Name") + val remoteX500Name = try { + CordaX500Name.build(remoteCert!!.subjectX500Principal) } catch (ex: IllegalArgumentException) { - log.error("Invalid certificate subject", ex) + log.error("Certificate subject not a valid CordaX500Name", ex) ctx.close() return } + if (allowedRemoteLegalNames != null && remoteX500Name !in allowedRemoteLegalNames) { + log.error("Provided certificate subject $remoteX500Name not in expected set $allowedRemoteLegalNames") + ctx.close() + return + } + log.info("Handshake completed with subject: $remoteX500Name") createAMQPEngine(ctx) onOpen(Pair(ctx.channel() as SocketChannel, ConnectionChange(remoteAddress, remoteCert, true))) } else { - log.error("Handshake failure $evt") + log.error("Handshake failure ${evt.cause().message}") + if (log.isTraceEnabled) { + log.trace("Handshake failure", evt.cause()) + } ctx.close() } } } - @Suppress("OverridingDeprecatedMember") override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) { + log.warn("Closing channel due to nonrecoverable exception ${cause.message}") + if (log.isTraceEnabled) { + log.trace("Pipeline uncaught exception", cause) + } if (cause is ProxyConnectException) { log.warn("Proxy connection failed ${cause.message}") suppressClose = true // The pipeline gets marked as active on connection to the proxy rather than to the target, which causes excess close events } + ctx.close() } override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPClient.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPClient.kt index 85922c5a29..14fcfb9a6d 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPClient.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPClient.kt @@ -30,6 +30,7 @@ import net.corda.nodeapi.internal.protonwrapper.messages.impl.SendableMessageImp import rx.Observable import rx.subjects.PublishSubject import java.net.InetSocketAddress +import java.lang.Long.min import java.security.KeyStore import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock @@ -74,7 +75,9 @@ class AMQPClient(val targets: List, } val log = contextLogger() - const val RETRY_INTERVAL = 1000L + const val MIN_RETRY_INTERVAL = 1000L + const val MAX_RETRY_INTERVAL = 60000L + const val BACKOFF_MULTIPLIER = 2L const val NUM_CLIENT_THREADS = 2 } @@ -87,6 +90,13 @@ class AMQPClient(val targets: List, // Offset into the list of targets, so that we can implement round-robin reconnect logic. private var targetIndex = 0 private var currentTarget: NetworkHostAndPort = targets.first() + private var retryInterval = MIN_RETRY_INTERVAL + + private fun nextTarget() { + targetIndex = (targetIndex + 1).rem(targets.size) + log.info("Retry connect to ${targets[targetIndex]}") + retryInterval = min(MAX_RETRY_INTERVAL, retryInterval * BACKOFF_MULTIPLIER) + } private val connectListener = object : ChannelFutureListener { override fun operationComplete(future: ChannelFuture) { @@ -95,10 +105,9 @@ class AMQPClient(val targets: List, if (!stopping) { workerGroup?.schedule({ - log.info("Retry connect to $currentTarget") - targetIndex = (targetIndex + 1).rem(targets.size) + nextTarget() restart() - }, RETRY_INTERVAL, TimeUnit.MILLISECONDS) + }, retryInterval, TimeUnit.MILLISECONDS) } } else { log.info("Connected to $currentTarget") @@ -116,10 +125,9 @@ class AMQPClient(val targets: List, clientChannel = null if (!stopping) { workerGroup?.schedule({ - log.info("Retry connect") - targetIndex = (targetIndex + 1).rem(targets.size) + nextTarget() restart() - }, RETRY_INTERVAL, TimeUnit.MILLISECONDS) + }, retryInterval, TimeUnit.MILLISECONDS) } } } @@ -162,7 +170,10 @@ class AMQPClient(val targets: List, parent.userName, parent.password, parent.trace, - { parent._onConnection.onNext(it.second) }, + { + parent.retryInterval = MIN_RETRY_INTERVAL // reset to fast reconnect if we connect properly + parent._onConnection.onNext(it.second) + }, { parent._onConnection.onNext(it.second) }, { rcv -> parent._onReceive.onNext(rcv) })) } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt index 50dc3dc9cf..ef2aae5c47 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt @@ -100,7 +100,7 @@ class AMQPServer(val hostName: String, parent.password, parent.trace, { - parent.clientChannels.put(it.first.remoteAddress(), it.first) + parent.clientChannels[it.first.remoteAddress()] = it.first parent._onConnection.onNext(it.second) }, { @@ -204,5 +204,4 @@ class AMQPServer(val hostName: String, private val _onConnection = PublishSubject.create().toSerialized() val onConnection: Observable get() = _onConnection - } \ No newline at end of file diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/SSLHelper.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/SSLHelper.kt index f719e5ab2d..77e85aba19 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/SSLHelper.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/SSLHelper.kt @@ -12,22 +12,111 @@ package net.corda.nodeapi.internal.protonwrapper.netty import io.netty.handler.ssl.SslHandler import net.corda.core.utilities.NetworkHostAndPort +import net.corda.core.utilities.contextLogger +import net.corda.core.utilities.toHex import net.corda.nodeapi.ArtemisTcpTransport +import net.corda.nodeapi.internal.crypto.toBc +import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier +import org.bouncycastle.asn1.x509.Extension +import org.bouncycastle.asn1.x509.SubjectKeyIdentifier +import java.net.Socket import java.security.KeyStore import java.security.SecureRandom -import java.security.cert.CertPathBuilder -import java.security.cert.PKIXBuilderParameters -import java.security.cert.PKIXRevocationChecker -import java.security.cert.X509CertSelector +import java.security.cert.* import java.util.* import javax.net.ssl.* +internal class LoggingTrustManagerWrapper(val wrapped: X509ExtendedTrustManager) : X509ExtendedTrustManager() { + companion object { + val log = contextLogger() + } + + private fun certPathToString(certPath: Array?): String { + if (certPath == null) { + return "" + } + val certs = certPath.map { + val bcCert = it.toBc() + val subject = bcCert.subject.toString() + val issuer = bcCert.issuer.toString() + val keyIdentifier = try { + SubjectKeyIdentifier.getInstance(bcCert.getExtension(Extension.subjectKeyIdentifier).parsedValue).keyIdentifier.toHex() + } catch (ex: Exception) { + "null" + } + val authorityKeyIdentifier = try { + AuthorityKeyIdentifier.getInstance(bcCert.getExtension(Extension.authorityKeyIdentifier).parsedValue).keyIdentifier.toHex() + } catch (ex: Exception) { + "null" + } + " $subject[$keyIdentifier] issued by $issuer[$authorityKeyIdentifier]" + } + return certs.joinToString("\r\n") + } + + + private fun certPathToStringFull(chain: Array?): String { + if (chain == null) { + return "" + } + return chain.map { it.toString() }.joinToString(", ") + } + + private fun logErrors(chain: Array?, block: () -> Unit) { + try { + block() + } catch (ex: CertificateException) { + log.error("Bad certificate path ${ex.message}:\r\n${certPathToStringFull(chain)}") + throw ex + } + } + + @Throws(CertificateException::class) + override fun checkClientTrusted(chain: Array?, authType: String?, socket: Socket?) { + log.info("Check Client Certpath:\r\n${certPathToString(chain)}") + logErrors(chain) { wrapped.checkClientTrusted(chain, authType, socket) } + } + + @Throws(CertificateException::class) + override fun checkClientTrusted(chain: Array?, authType: String?, engine: SSLEngine?) { + log.info("Check Client Certpath:\r\n${certPathToString(chain)}") + logErrors(chain) { wrapped.checkClientTrusted(chain, authType, engine) } + } + + @Throws(CertificateException::class) + override fun checkClientTrusted(chain: Array?, authType: String?) { + log.info("Check Client Certpath:\r\n${certPathToString(chain)}") + logErrors(chain) { wrapped.checkClientTrusted(chain, authType) } + } + + @Throws(CertificateException::class) + override fun checkServerTrusted(chain: Array?, authType: String?, socket: Socket?) { + log.info("Check Server Certpath:\r\n${certPathToString(chain)}") + logErrors(chain) { wrapped.checkServerTrusted(chain, authType, socket) } + } + + @Throws(CertificateException::class) + override fun checkServerTrusted(chain: Array?, authType: String?, engine: SSLEngine?) { + log.info("Check Server Certpath:\r\n${certPathToString(chain)}") + logErrors(chain) { wrapped.checkServerTrusted(chain, authType, engine) } + } + + @Throws(CertificateException::class) + override fun checkServerTrusted(chain: Array?, authType: String?) { + log.info("Check Server Certpath:\r\n${certPathToString(chain)}") + logErrors(chain) { wrapped.checkServerTrusted(chain, authType) } + } + + override fun getAcceptedIssuers(): Array = wrapped.acceptedIssuers + +} + internal fun createClientSslHelper(target: NetworkHostAndPort, keyManagerFactory: KeyManagerFactory, trustManagerFactory: TrustManagerFactory): SslHandler { val sslContext = SSLContext.getInstance("TLS") val keyManagers = keyManagerFactory.keyManagers - val trustManagers = trustManagerFactory.trustManagers + val trustManagers = trustManagerFactory.trustManagers.filterIsInstance(X509ExtendedTrustManager::class.java).map { LoggingTrustManagerWrapper(it) }.toTypedArray() sslContext.init(keyManagers, trustManagers, SecureRandom()) val sslEngine = sslContext.createSSLEngine(target.host, target.port) sslEngine.useClientMode = true @@ -41,7 +130,7 @@ internal fun createServerSslHelper(keyManagerFactory: KeyManagerFactory, trustManagerFactory: TrustManagerFactory): SslHandler { val sslContext = SSLContext.getInstance("TLS") val keyManagers = keyManagerFactory.keyManagers - val trustManagers = trustManagerFactory.trustManagers + val trustManagers = trustManagerFactory.trustManagers.filterIsInstance(X509ExtendedTrustManager::class.java).map { LoggingTrustManagerWrapper(it) }.toTypedArray() sslContext.init(keyManagers, trustManagers, SecureRandom()) val sslEngine = sslContext.createSSLEngine() sslEngine.useClientMode = false diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt index e7e942c595..071f3e3ec0 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt @@ -1,4 +1,5 @@ @file:JvmName("ByteBufferStreams") + package net.corda.nodeapi.internal.serialization import net.corda.core.internal.LazyPool @@ -10,9 +11,9 @@ import java.nio.ByteBuffer import kotlin.math.min internal val serializeOutputStreamPool = LazyPool( - clear = ByteBufferOutputStream::reset, - shouldReturnToPool = { it.size() < 256 * 1024 }, // Discard if it grew too large - newInstance = { ByteBufferOutputStream(64 * 1024) }) + clear = ByteBufferOutputStream::reset, + shouldReturnToPool = { it.size() < 256 * 1024 }, // Discard if it grew too large + newInstance = { ByteBufferOutputStream(64 * 1024) }) internal fun byteArrayOutput(task: (ByteBufferOutputStream) -> T): ByteArray { return serializeOutputStreamPool.run { underlying -> diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt index 2ac9849a6e..3de15e4165 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt @@ -56,7 +56,7 @@ class SerializeAsTokenContextImpl(override val serviceHub: ServiceHub, init: Ser if (className !in classNameToSingleton) { // Only allowable if we are in SerializeAsTokenContext init (readOnly == false) if (readOnly) { - throw UnsupportedOperationException("Attempt to write token for lazy registered ${className}. All tokens should be registered during context construction.") + throw UnsupportedOperationException("Attempt to write token for lazy registered $className. All tokens should be registered during context construction.") } classNameToSingleton[className] = toBeTokenized } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt index ce74965c01..82913690d9 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt @@ -22,7 +22,7 @@ import java.lang.reflect.Type * [ByteArray] is automatically marshalled to/from the Proton-J wrapper, [Binary]. */ class AMQPPrimitiveSerializer(clazz: Class<*>) : AMQPSerializer { - override val typeDescriptor = Symbol.valueOf(SerializerFactory.primitiveTypeName(clazz)!!) + override val typeDescriptor = Symbol.valueOf(SerializerFactory.primitiveTypeName(clazz)!!)!! override val type: Type = clazz // NOOP since this is a primitive type. diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt index 17589b32f4..d65067b58a 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt @@ -78,6 +78,7 @@ abstract class AbstractAMQPSerializationScheme( val List.customSerializers get() = flatMap { it.serializationCustomSerializers }.toSet() } + // Parameter "context" is unused directy but passed in by reflection. Removing it will cause failures. private fun registerCustomSerializers(context: SerializationContext, factory: SerializerFactory) { with(factory) { register(publicKeySerializer) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt index 30d6052211..884c6b057e 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt @@ -1,4 +1,5 @@ @file:JvmName("AMQPSerializerFactories") + package net.corda.nodeapi.internal.serialization.amqp import net.corda.core.serialization.SerializationContext diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt index 6b5d38cfbf..97587a7585 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt @@ -9,6 +9,7 @@ */ @file:JvmName("AMQPStreams") + package net.corda.nodeapi.internal.serialization.amqp import net.corda.nodeapi.internal.serialization.ByteBufferInputStream diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt index d7bd52cca5..043174668b 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt @@ -42,7 +42,7 @@ open class ArraySerializer(override val type: Type, factory: SerializerFactory) "${type.componentType().typeName}$arrayType" } - override val typeDescriptor by lazy { + override val typeDescriptor: Symbol by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") } internal val elementType: Type by lazy { type.componentType() } @@ -105,7 +105,7 @@ abstract class PrimArraySerializer(type: Type, factory: SerializerFactory) : Arr companion object { // We don't need to handle the unboxed byte type as that is coercible to a byte array, but // the other 7 primitive types we do - val primTypes: Map PrimArraySerializer> = mapOf( + private val primTypes: Map PrimArraySerializer> = mapOf( IntArray::class.java to { f -> PrimIntArraySerializer(f) }, CharArray::class.java to { f -> PrimCharArraySerializer(f) }, BooleanArray::class.java to { f -> PrimBooleanArraySerializer(f) }, diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt index d5f027e211..9710a805ee 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt @@ -24,10 +24,10 @@ import kotlin.collections.LinkedHashSet /** * Serialization / deserialization of predefined set of supported [Collection] types covering mostly [List]s and [Set]s. */ -class CollectionSerializer(val declaredType: ParameterizedType, factory: SerializerFactory) : AMQPSerializer { +class CollectionSerializer(private val declaredType: ParameterizedType, factory: SerializerFactory) : AMQPSerializer { override val type: Type = declaredType as? DeserializedParameterizedType ?: DeserializedParameterizedType.make(SerializerFactory.nameForType(declaredType)) - override val typeDescriptor by lazy { + override val typeDescriptor: Symbol by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") } @@ -63,10 +63,8 @@ class CollectionSerializer(val declaredType: ParameterizedType, factory: Seriali (declaredType as? ParameterizedType) ?: DeserializedParameterizedType(collectionClass, arrayOf(SerializerFactory.AnyType)) - private fun findMostSuitableCollectionType(actualClass: Class<*>): Class> = supportedTypes.keys.findLast { it.isAssignableFrom(actualClass) }!! - } private val concreteBuilder: (List<*>) -> Collection<*> = findConcreteType(declaredType.rawType as Class<*>) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt index e2038fb626..d7ead1f4d4 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt @@ -69,7 +69,7 @@ class CorDappCustomSerializer( override val type = types[CORDAPP_TYPE] val proxyType = types[PROXY_TYPE] - override val typeDescriptor = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(type)}") + override val typeDescriptor: Symbol = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(type)}") val descriptor: Descriptor = Descriptor(typeDescriptor) private val proxySerializer: ObjectSerializer by lazy { ObjectSerializer(proxyType, factory) } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt index b6ace5113a..68cfaf941c 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt @@ -74,7 +74,7 @@ abstract class CustomSerializer : AMQPSerializer, SerializerFor { override fun isSerializerFor(clazz: Class<*>): Boolean = clazz == this.clazz override val type: Type get() = clazz - override val typeDescriptor by lazy { + override val typeDescriptor: Symbol by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${SerializerFingerPrinter().fingerprintForDescriptors(superClassSerializer.typeDescriptor.toString(), nameForType(clazz))}") } private val typeNotation: TypeNotation = RestrictedType( @@ -110,7 +110,7 @@ abstract class CustomSerializer : AMQPSerializer, SerializerFor { */ abstract class CustomSerializerImp(protected val clazz: Class, protected val withInheritance: Boolean) : CustomSerializer() { override val type: Type get() = clazz - override val typeDescriptor = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(clazz)}") + override val typeDescriptor: Symbol = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(clazz)}") override fun writeClassInfo(output: SerializationOutput) {} override val descriptor: Descriptor = Descriptor(typeDescriptor) override fun isSerializerFor(clazz: Class<*>): Boolean = if (withInheritance) this.clazz.isAssignableFrom(clazz) else this.clazz == clazz diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt index 3b000b6334..6a66193e37 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt @@ -18,7 +18,6 @@ import net.corda.core.utilities.ByteSequence import net.corda.nodeapi.internal.serialization.* import org.apache.qpid.proton.amqp.Binary import org.apache.qpid.proton.amqp.DescribedType -import org.apache.qpid.proton.amqp.UnsignedByte import org.apache.qpid.proton.amqp.UnsignedInteger import org.apache.qpid.proton.codec.Data import java.io.InputStream @@ -42,28 +41,6 @@ class DeserializationInput @JvmOverloads constructor(private val serializerFacto private val objectHistory: MutableList = mutableListOf() companion object { - private const val BYTES_NEEDED_TO_PEEK: Int = 23 - - fun peekSize(bytes: ByteArray): Int { - // There's an 8 byte header, and then a 0 byte plus descriptor followed by constructor - val eighth = bytes[8].toInt() - check(eighth == 0x0) { "Expected to find a descriptor in the AMQP stream" } - // We should always have an Envelope, so the descriptor should be a 64-bit long (0x80) - val ninth = UnsignedByte.valueOf(bytes[9]).toInt() - check(ninth == 0x80) { "Expected to find a ulong in the AMQP stream" } - // Skip 8 bytes - val eighteenth = UnsignedByte.valueOf(bytes[18]).toInt() - check(eighteenth == 0xd0 || eighteenth == 0xc0) { "Expected to find a list8 or list32 in the AMQP stream" } - val size = if (eighteenth == 0xc0) { - // Next byte is size - UnsignedByte.valueOf(bytes[19]).toInt() - 3 // Minus three as PEEK_SIZE assumes 4 byte unsigned integer. - } else { - // Next 4 bytes is size - UnsignedByte.valueOf(bytes[19]).toInt().shl(24) + UnsignedByte.valueOf(bytes[20]).toInt().shl(16) + UnsignedByte.valueOf(bytes[21]).toInt().shl(8) + UnsignedByte.valueOf(bytes[22]).toInt() - } - return size + BYTES_NEEDED_TO_PEEK - } - @VisibleForTesting @Throws(NotSerializableException::class) fun withDataBytes(byteSequence: ByteSequence, encodingWhitelist: EncodingWhitelist, task: (ByteBuffer) -> T): T { @@ -150,13 +127,12 @@ class DeserializationInput @JvmOverloads constructor(private val serializerFacto envelope) } - internal fun readObjectOrNull(obj: Any?, schema: SerializationSchemas, type: Type, context: SerializationContext, - offset: Int = 0 + internal fun readObjectOrNull(obj: Any?, schema: SerializationSchemas, type: Type, context: SerializationContext ): Any? { - return if (obj == null) null else readObject(obj, schema, type, context, offset) + return if (obj == null) null else readObject(obj, schema, type, context) } - internal fun readObject(obj: Any, schemas: SerializationSchemas, type: Type, context: SerializationContext, debugIndent: Int = 0): Any = + internal fun readObject(obj: Any, schemas: SerializationSchemas, type: Type, context: SerializationContext): Any = if (obj is DescribedType && ReferencedObject.DESCRIPTOR == obj.descriptor) { // It must be a reference to an instance that has already been read, cheaply and quickly returning it by reference. val objectIndex = (obj.described as UnsignedInteger).toInt() diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt index 1cb6d75c6e..d96840df97 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt @@ -38,7 +38,7 @@ class DeserializedParameterizedType(private val rawType: Class<*>, private val p private val _typeName: String = makeTypeName() private fun makeTypeName(): String { - val paramsJoined = params.map { it.typeName }.joinToString(", ") + val paramsJoined = params.joinToString(", ") { it.typeName } return "${rawType.name}<$paramsJoined>" } @@ -155,14 +155,14 @@ class DeserializedParameterizedType(private val rawType: Class<*>, private val p } override fun equals(other: Any?): Boolean { - if (other is ParameterizedType) { + return if (other is ParameterizedType) { if (this === other) { - return true + true } else { - return this.ownerType == other.ownerType && this.rawType == other.rawType && Arrays.equals(this.actualTypeArguments, other.actualTypeArguments) + this.ownerType == other.ownerType && this.rawType == other.rawType && Arrays.equals(this.actualTypeArguments, other.actualTypeArguments) } } else { - return false + false } } } \ No newline at end of file diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt index f08f9dce2c..f0479a7351 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt @@ -101,7 +101,7 @@ abstract class EvolutionSerializer( val constructorArgs = arrayOfNulls(constructor.parameters.size) constructor.parameters.withIndex().forEach { - readersAsSerialized.get(it.value.name!!)?.apply { + readersAsSerialized[it.value.name!!]?.apply { this.resultsIndex = it.index } ?: if (!it.value.type.isMarkedNullable) { throw NotSerializableException( diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt index 8973bfb54f..ee807bf72b 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt @@ -104,7 +104,7 @@ class SerializerFingerPrinter : FingerPrinter { // serialise the object in the first place (and thus the cache lookup fails). This is also // true of Any, where we need Example and Example to have the same fingerprint return if ((type in alreadySeen) - && (type !is SerializerFactory.AnyType) + && (type !== SerializerFactory.AnyType) && (type !is TypeVariable<*>) && (type !is WildcardType)) { hasher.putUnencodedChars(ALREADY_SEEN_HASH) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt index c903a13019..4a81e37215 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt @@ -33,7 +33,7 @@ open class ObjectSerializer(val clazz: Type, factory: SerializerFactory) : AMQPS private val logger = contextLogger() } - open internal val propertySerializers: PropertySerializers by lazy { + internal open val propertySerializers: PropertySerializers by lazy { propertiesForSerialization(kotlinConstructor, clazz, factory) } @@ -42,12 +42,12 @@ open class ObjectSerializer(val clazz: Type, factory: SerializerFactory) : AMQPS private val typeName = nameForType(clazz) override val typeDescriptor = Symbol.valueOf( - "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") + "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}")!! // We restrict to only those annotated or whitelisted private val interfaces = interfacesForSerialization(clazz, factory) - open internal val typeNotation: TypeNotation by lazy { + internal open val typeNotation: TypeNotation by lazy { CompositeType(typeName, null, generateProvides(), Descriptor(typeDescriptor), generateFields()) } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt index c7b72c646f..b61c89ce35 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt @@ -89,7 +89,7 @@ class PrivatePropertyReader(val field: Field, parentType: Type) : PropertyReader // So this used to report as an error, but given we serialise exceptions all the time it // provides for very scary log files so move this to trace level loggerFor().let { logger -> - logger.trace("Using kotlin introspection on internal type ${field}") + logger.trace("Using kotlin introspection on internal type $field") logger.trace("Unexpected internal Kotlin error", e) } true diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt index cad8ae2d7f..4e61819d5d 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt @@ -134,18 +134,18 @@ open class SerializationOutput @JvmOverloads constructor( // assigned to them first as they will be first read from the stream on receiving end. // Skip for primitive types as they are too small and overhead of referencing them will be much higher than their content if (suitableForObjectReference(obj.javaClass)) { - objectHistory.put(obj, objectHistory.size) + objectHistory[obj] = objectHistory.size } } else { data.writeReferencedObject(ReferencedObject(retrievedRefCount)) } } - open internal fun writeTypeNotations(vararg typeNotation: TypeNotation): Boolean { + internal open fun writeTypeNotations(vararg typeNotation: TypeNotation): Boolean { return schemaHistory.addAll(typeNotation) } - open internal fun requireSerializer(type: Type) { + internal open fun requireSerializer(type: Type) { if (type != SerializerFactory.AnyType && type != Object::class.java) { val serializer = serializerFactory.get(null, type) if (serializer !in serializerHistory) { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt index 1da5cb0e2c..3b19ca35e7 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt @@ -154,7 +154,7 @@ open class SerializerFactory( return if (actualClass.typeParameters.isNotEmpty()) { // The actual class can never have type variables resolved, due to the JVM's use of type erasure, so let's try and resolve them // Search for declared type in the inheritance hierarchy and then see if that fills in all the variables - val implementationChain: List? = findPathToDeclared(actualClass, declaredType, mutableListOf()) + val implementationChain: List? = findPathToDeclared(actualClass, declaredType, mutableListOf()) if (implementationChain != null) { val start = implementationChain.last() val rest = implementationChain.dropLast(1).drop(1) @@ -315,6 +315,7 @@ open class SerializerFactory( return if (declaredSuperClass == null || !customSerializer.isSerializerFor(declaredSuperClass) || !customSerializer.revealSubclassesInSchema) { + @Suppress("UNCHECKED_CAST") customSerializer as? AMQPSerializer } else { // Make a subclass serializer for the subclass and return that... diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt index 91f068ef43..bd85f9a7c5 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt @@ -22,7 +22,7 @@ import java.lang.reflect.Type */ class SingletonSerializer(override val type: Class<*>, val singleton: Any, factory: SerializerFactory) : AMQPSerializer { override val typeDescriptor = Symbol.valueOf( - "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") + "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}")!! private val interfaces = interfacesForSerialization(type, factory) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt index 4b2a33886e..b471e66809 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt @@ -82,7 +82,7 @@ abstract class Transform : DescribedType { */ class UnknownTransform : Transform() { companion object : DescribedTypeConstructor { - val typeName = "UnknownTransform" + const val typeName = "UnknownTransform" override fun newInstance(obj: Any?) = UnknownTransform() @@ -100,7 +100,7 @@ class UnknownTransform : Transform() { */ class UnknownTestTransform(val a: Int, val b: Int, val c: Int) : Transform() { companion object : DescribedTypeConstructor { - val typeName = "UnknownTest" + const val typeName = "UnknownTest" override fun newInstance(obj: Any?): UnknownTestTransform { val described = obj as List<*> @@ -127,7 +127,7 @@ class EnumDefaultSchemaTransform(val old: String, val new: String) : Transform() /** * Value encoded into the schema that identifies a transform as this type */ - val typeName = "EnumDefault" + const val typeName = "EnumDefault" override fun newInstance(obj: Any?): EnumDefaultSchemaTransform { val described = obj as List<*> @@ -164,7 +164,7 @@ class RenameSchemaTransform(val from: String, val to: String) : Transform() { /** * Value encoded into the schema that identifies a transform as this type */ - val typeName = "Rename" + const val typeName = "Rename" override fun newInstance(obj: Any?): RenameSchemaTransform { val described = obj as List<*> @@ -223,9 +223,7 @@ data class TransformsSchema(val types: Map')) { this.substring(0, this.indexOf('<')) } else this -fun AMQPField.getTypeAsClass(classloader: ClassLoader) = typeStrToType[Pair(type, mandatory)] ?: when (type) { +fun AMQPField.getTypeAsClass(classloader: ClassLoader) = (typeStrToType[Pair(type, mandatory)] ?: when (type) { "string" -> String::class.java "binary" -> ByteArray::class.java "*" -> if (requires.isEmpty()) Any::class.java else { classloader.loadClass(requires[0].stripGenerics()) } else -> classloader.loadClass(type.stripGenerics()) -} +})!! fun AMQPField.validateType(classloader: ClassLoader) = when (type) { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt index 8b5897d422..8d7e298104 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt @@ -16,7 +16,7 @@ import com.esotericsoftware.kryo.serializers.ClosureSerializer import java.io.Serializable object CordaClosureSerializer : ClosureSerializer() { - val ERROR_MESSAGE = "Unable to serialize Java Lambda expression, unless explicitly declared e.g., Runnable r = (Runnable & Serializable) () -> System.out.println(\"Hello world!\");" + const val ERROR_MESSAGE = "Unable to serialize Java Lambda expression, unless explicitly declared e.g., Runnable r = (Runnable & Serializable) () -> System.out.println(\"Hello world!\");" override fun write(kryo: Kryo, output: Output, target: Any) { if (!isSerializable(target)) { @@ -31,7 +31,7 @@ object CordaClosureSerializer : ClosureSerializer() { } object CordaClosureBlacklistSerializer : ClosureSerializer() { - val ERROR_MESSAGE = "Java 8 Lambda expressions are not supported for serialization." + const val ERROR_MESSAGE = "Java 8 Lambda expressions are not supported for serialization." override fun write(kryo: Kryo, output: Output, target: Any) { throw IllegalArgumentException(ERROR_MESSAGE) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt index 0b9d42f97d..5799141d7a 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt @@ -226,6 +226,7 @@ object DefaultKryoCustomizer { if (kryo.serializationContext() != null) { val attachmentHash = SecureHash.SHA256(input.readBytes(32)) val contract = input.readString() + @Suppress("UNCHECKED_CAST") val additionalContracts = kryo.readClassAndObject(input) as Set val uploader = input.readString() val context = kryo.serializationContext()!! @@ -243,6 +244,7 @@ object DefaultKryoCustomizer { } else { val attachment = GeneratedAttachment(input.readBytesWithLength()) val contract = input.readString() + @Suppress("UNCHECKED_CAST") val additionalContracts = kryo.readClassAndObject(input) as Set val uploader = input.readString() return ContractAttachment(attachment, contract, additionalContracts, uploader) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt index 94d3fe01cd..6fcf77002e 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt @@ -9,6 +9,7 @@ */ @file:JvmName("KryoStreams") + package net.corda.nodeapi.internal.serialization.kryo import com.esotericsoftware.kryo.io.Input diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java index 8aff41edbf..baeee920d8 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java @@ -53,7 +53,7 @@ public final class ForbiddenLambdaSerializationTests { assertThat(throwable).isNotNull(); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); if (ctx != SerializationContext.UseCase.RPCServer && ctx != SerializationContext.UseCase.Storage) { - assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.INSTANCE.getERROR_MESSAGE()); + assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.ERROR_MESSAGE); } else { assertThat(throwable).hasMessageContaining("RPC not allowed to deserialise internal classes"); } @@ -75,7 +75,7 @@ public final class ForbiddenLambdaSerializationTests { assertThat(throwable).isInstanceOf(IllegalArgumentException.class); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); if (ctx != SerializationContext.UseCase.RPCServer && ctx != SerializationContext.UseCase.Storage) { - assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.INSTANCE.getERROR_MESSAGE()); + assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.ERROR_MESSAGE); } else { assertThat(throwable).hasMessageContaining("RPC not allowed to deserialise internal classes"); } diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java index 8871976dc5..e85eb00815 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java @@ -61,7 +61,7 @@ public final class LambdaCheckpointSerializationTest { assertThat(throwable).isNotNull(); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); - assertThat(throwable).hasMessage(CordaClosureSerializer.INSTANCE.getERROR_MESSAGE()); + assertThat(throwable).hasMessage(CordaClosureSerializer.ERROR_MESSAGE); } private SerializedBytes serialize(final T target) { diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java index c7932721ee..bb01f54077 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java @@ -12,7 +12,6 @@ package net.corda.nodeapi.internal.serialization.amqp; import net.corda.nodeapi.internal.serialization.AllWhitelist; import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationContext; -import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationContextKt; import org.assertj.core.api.Assertions; import org.junit.Ignore; import org.junit.Test; diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java index 80621a0a99..9a0162422a 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java @@ -1,7 +1,6 @@ package net.corda.nodeapi.internal.serialization.amqp; import com.google.common.collect.ImmutableList; -import kotlin.Suppress; import net.corda.core.contracts.ContractState; import net.corda.core.identity.AbstractParty; import net.corda.core.serialization.SerializedBytes; diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java index 153d4fb5c8..b48b83fbd3 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java @@ -10,22 +10,17 @@ package net.corda.nodeapi.internal.serialization.amqp; -import com.google.common.collect.ImmutableList; -import net.corda.core.contracts.ContractState; -import net.corda.core.identity.AbstractParty; import net.corda.core.serialization.ConstructorForDeserialization; import net.corda.nodeapi.internal.serialization.AllWhitelist; import net.corda.core.serialization.SerializedBytes; import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationContext; import org.apache.qpid.proton.codec.DecoderImpl; import org.apache.qpid.proton.codec.EncoderImpl; -import org.jetbrains.annotations.NotNull; import org.junit.Test; import javax.annotation.Nonnull; import java.io.NotSerializableException; import java.nio.ByteBuffer; -import java.util.List; import java.util.Objects; import static org.junit.Assert.assertTrue; diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java index 126ff34f71..30402c3ea0 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java @@ -11,7 +11,7 @@ import java.util.Map; public class TestSerializationContext { - static private Map serializationProperties = new HashMap(); + private static Map serializationProperties = new HashMap<>(); public static SerializationContext testSerializationContext = new SerializationContextImpl( ByteSequence.of(new byte[] { 'c', 'o', 'r', 'd', 'a', (byte)0, (byte)0, (byte)1}), diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt index e187930e56..bb15c22a31 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt @@ -46,7 +46,7 @@ class AttachmentsClassLoaderStaticContractTests { class AttachmentDummyContract : Contract { companion object { - private val ATTACHMENT_PROGRAM_ID = "net.corda.nodeapi.internal.AttachmentsClassLoaderStaticContractTests\$AttachmentDummyContract" + private const val ATTACHMENT_PROGRAM_ID = "net.corda.nodeapi.internal.AttachmentsClassLoaderStaticContractTests\$AttachmentDummyContract" } data class State(val magicNumber: Int = 0) : ContractState { diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt index fa9f3b1ea2..2a23342a26 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt @@ -20,7 +20,12 @@ import net.corda.core.internal.declaredField import net.corda.core.internal.toWireTransaction import net.corda.core.node.ServiceHub import net.corda.core.node.services.AttachmentStorage -import net.corda.core.serialization.* +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.MissingAttachmentsException +import net.corda.core.serialization.SerializationContext +import net.corda.core.serialization.SerializationFactory +import net.corda.core.serialization.deserialize +import net.corda.core.serialization.serialize import net.corda.core.utilities.ByteSequence import net.corda.core.utilities.OpaqueBytes import net.corda.node.internal.cordapp.CordappLoader @@ -38,10 +43,12 @@ import net.corda.testing.internal.kryoSpecific import net.corda.testing.internal.rigorousMock import net.corda.testing.services.MockAttachmentStorage import org.apache.commons.io.IOUtils -import org.junit.Assert.* +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test -import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.net.URL import java.net.URLClassLoader @@ -135,6 +142,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `test overlapping file exception`() { val storage = attachments val att0 = attachmentId @@ -147,7 +155,8 @@ class AttachmentsClassLoaderTests { } @Test - fun `basic`() { + @Suppress("DEPRECATION") + fun basic() { val storage = attachments val att0 = attachmentId val att1 = storage.importAttachment(fakeAttachment("file1.txt", "some data").inputStream()) @@ -159,6 +168,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `Check platform independent path handling in attachment jars`() { val storage = MockAttachmentStorage() @@ -179,6 +189,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `loading class AnotherDummyContract`() { val storage = attachments val att0 = attachmentId @@ -200,6 +211,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `testing Kryo with ClassLoader (with top level class name)`() { val contract = createContract2Cash() @@ -222,6 +234,7 @@ class AttachmentsClassLoaderTests { class Data(val contract: Contract) @Test + @Suppress("DEPRECATION") fun `testing Kryo with ClassLoader (without top level class name)`() { val data = Data(createContract2Cash()) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt index d81a14e1fc..98f71f2b5e 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt @@ -28,7 +28,6 @@ import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Rule import org.junit.Test import java.security.KeyPair -import java.security.PrivateKey import java.security.PublicKey import java.security.SignatureException diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt index 53833cb132..05e985ab42 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt @@ -28,32 +28,32 @@ import kotlin.reflect.full.primaryConstructor class ConfigParsingTest { @Test - fun `String`() { + fun String() { testPropertyType("hello world!", "bye") } @Test - fun `Int`() { + fun Int() { testPropertyType(1, 2) } @Test - fun `Long`() { + fun Long() { testPropertyType(Long.MAX_VALUE, Long.MIN_VALUE) } @Test - fun `Double`() { + fun Double() { testPropertyType(1.2, 3.4) } @Test - fun `Boolean`() { + fun Boolean() { testPropertyType(true, false) } @Test - fun `Enum`() { + fun Enum() { testPropertyType(TestEnum.Value2, TestEnum.Value1, valuesToString = true) } @@ -66,17 +66,17 @@ class ConfigParsingTest { } @Test - fun `LocalDate`() { + fun LocalDate() { testPropertyType(LocalDate.now(), LocalDate.now().plusDays(1), valuesToString = true) } @Test - fun `Instant`() { + fun Instant() { testPropertyType(Instant.now(), Instant.now().plusMillis(100), valuesToString = true) } @Test - fun `NetworkHostAndPort`() { + fun NetworkHostAndPort() { testPropertyType( NetworkHostAndPort("localhost", 2223), NetworkHostAndPort("localhost", 2225), @@ -84,18 +84,18 @@ class ConfigParsingTest { } @Test - fun `Path`() { + fun Path() { val path = "tmp" / "test" testPropertyType(path, path / "file", valuesToString = true) } @Test - fun `URL`() { + fun URL() { testPropertyType(URL("http://localhost:1234"), URL("http://localhost:1235"), valuesToString = true) } @Test - fun `UUID`() { + fun UUID() { testPropertyType(UUID.randomUUID(), UUID.randomUUID(), valuesToString = true) } @@ -146,7 +146,7 @@ class ConfigParsingTest { } @Test - fun `Set`() { + fun Set() { val data = StringSetData(setOf("a", "b")) assertThat(config("values" to listOf("a", "a", "b")).parseAs()).isEqualTo(data) assertThat(data.toConfig()).isEqualTo(config("values" to listOf("a", "b"))) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt index d5b75d227b..a46abbd7b9 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt @@ -24,7 +24,6 @@ import rx.schedulers.TestScheduler import java.nio.file.Path import java.time.Duration import java.util.concurrent.TimeUnit -import kotlin.streams.toList class NodeInfoFilesCopierTest { companion object { @@ -123,7 +122,7 @@ class NodeInfoFilesCopierTest { } @Test - fun `clear`() { + fun clear() { // Configure 2 nodes. nodeInfoFilesCopier.addConfig(node1RootPath) nodeInfoFilesCopier.addConfig(node2RootPath) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt index bcdb9cbda0..c2e7fec876 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt @@ -65,7 +65,7 @@ class MapsSerializationTest { val wrongPayloadType = WrongPayloadType(payload) assertThatThrownBy { wrongPayloadType.serialize() } .isInstanceOf(IllegalArgumentException::class.java).hasMessageContaining( - "Map type class java.util.HashMap is unstable under iteration. Suggested fix: use java.util.LinkedHashMap instead.") + "Map type class java.util.HashMap is unstable under iteration. Suggested fix: use java.util.LinkedHashMap instead.") } @CordaSerializable diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt index def077904f..533846c01a 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt @@ -50,7 +50,6 @@ class PrivateKeySerializationTest(private val privateKey: PrivateKey, private va fun `failed with wrong UseCase`() { assertThatThrownBy { privateKey.serialize(context = SerializationDefaults.P2P_CONTEXT) } .isInstanceOf(IllegalStateException::class.java) - .hasMessageContaining("UseCase '${P2P}' is not within") - + .hasMessageContaining("UseCase '$P2P' is not within") } } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt index 7889a4bc38..3b4d15aead 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt @@ -407,6 +407,7 @@ class EnumEvolvabilityTests { val f = sf.javaClass.getDeclaredField("transformsCache") f.isAccessible = true + @Suppress("UNCHECKED_CAST") val transformsCache = f.get(sf) as ConcurrentHashMap>> assertEquals(0, transformsCache.size) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt index 7bfd33ec5b..8509d508fc 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt @@ -25,7 +25,7 @@ class ErrorMessagesTests { val VERBOSE get() = false } - private fun errMsg(property:String, testname: String) = + private fun errMsg(property: String, testname: String) = "Property '$property' or its getter is non public, this renders class 'class $testname\$C' unserializable -> class $testname\$C" // Java allows this to be set at the class level yet Kotlin doesn't for some reason diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt index 99823fe350..73534de3d7 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt @@ -17,7 +17,7 @@ import net.corda.nodeapi.internal.serialization.AllWhitelist import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationOutput import net.corda.nodeapi.internal.serialization.amqp.testutils.serializeAndReturnSchema -class FingerPrinterTesting : FingerPrinter { +class FingerPrinterTesting : FingerPrinter { private var index = 0 private val cache = mutableMapOf() @@ -39,18 +39,19 @@ class FingerPrinterTestingTests { companion object { const val VERBOSE = true } + @Test fun testingTest() { val fpt = FingerPrinterTesting() - assertEquals ("0", fpt.fingerprint(Integer::class.java)) - assertEquals ("1", fpt.fingerprint(String::class.java)) - assertEquals ("0", fpt.fingerprint(Integer::class.java)) - assertEquals ("1", fpt.fingerprint(String::class.java)) + assertEquals("0", fpt.fingerprint(Integer::class.java)) + assertEquals("1", fpt.fingerprint(String::class.java)) + assertEquals("0", fpt.fingerprint(Integer::class.java)) + assertEquals("1", fpt.fingerprint(String::class.java)) } @Test fun worksAsReplacement() { - data class C (val a: Int, val b: Long) + data class C(val a: Int, val b: Long) val factory = SerializerFactory( AllWhitelist, @@ -60,8 +61,7 @@ class FingerPrinterTestingTests { val blob = TestSerializationOutput(VERBOSE, factory).serializeAndReturnSchema(C(1, 2L)) - assertEquals (1, blob.schema.types.size) - assertEquals ("", blob.schema.types[0].descriptor.toString()) + assertEquals(1, blob.schema.types.size) + assertEquals("", blob.schema.types[0].descriptor.toString()) } - } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt index 56c6ab7624..178c532de9 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt @@ -31,7 +31,7 @@ class OverridePKSerializerTest { override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext - ) : PublicKey { + ): PublicKey { throw SerializerTestException("Custom read call") } diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt index cefc3e51ab..eba38ccb6d 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt @@ -10,9 +10,10 @@ import org.junit.Test class RoundTripTests { @Test fun mutableBecomesImmutable() { - data class C(val l : MutableList) + data class C(val l: MutableList) + val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(mutableListOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(mutableListOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) Assertions.assertThatThrownBy { @@ -23,15 +24,16 @@ class RoundTripTests { @Test fun mutableStillMutable() { class C { - val l : MutableList + val l: MutableList @Suppress("Unused") - constructor (l : MutableList) { + constructor (l: MutableList) { this.l = l.toMutableList() } } + val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(mutableListOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(mutableListOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) newC.l.add("d") @@ -39,14 +41,14 @@ class RoundTripTests { @Test fun mutableStillMutable2() { - data class C (val l : MutableList){ + data class C(val l: MutableList) { @ConstructorForDeserialization @Suppress("Unused") - constructor (l : Collection) : this (l.toMutableList()) + constructor (l: Collection) : this(l.toMutableList()) } val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(mutableListOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(mutableListOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) newC.l.add("d") @@ -54,10 +56,11 @@ class RoundTripTests { @Test fun mutableBecomesImmutable4() { - data class C(val l : List) + data class C(val l: List) + val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(listOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(listOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) - val newC2 = newC.copy (l = (newC.l + "d")) + val newC2 = newC.copy(l = (newC.l + "d")) } } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt index d283d07c00..ace26affb0 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt @@ -17,7 +17,13 @@ import com.nhaarman.mockito_kotlin.whenever import net.corda.client.rpc.RPCException import net.corda.core.CordaException import net.corda.core.CordaRuntimeException -import net.corda.core.contracts.* +import net.corda.core.contracts.Amount +import net.corda.core.contracts.Contract +import net.corda.core.contracts.ContractAttachment +import net.corda.core.contracts.ContractState +import net.corda.core.contracts.PrivacySalt +import net.corda.core.contracts.StateRef +import net.corda.core.contracts.TransactionState import net.corda.core.crypto.Crypto import net.corda.core.crypto.SecureHash import net.corda.core.crypto.secureRandomBytes @@ -26,25 +32,47 @@ import net.corda.core.identity.AbstractParty import net.corda.core.identity.CordaX500Name import net.corda.core.internal.AbstractAttachment import net.corda.core.internal.x500Name -import net.corda.core.serialization.* +import net.corda.core.serialization.ConstructorForDeserialization +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.EncodingWhitelist +import net.corda.core.serialization.MissingAttachmentsException +import net.corda.core.serialization.SerializationContext +import net.corda.core.serialization.SerializationFactory import net.corda.core.transactions.LedgerTransaction import net.corda.core.utilities.OpaqueBytes import net.corda.nodeapi.internal.DEV_INTERMEDIATE_CA import net.corda.nodeapi.internal.crypto.ContentSignerBuilder -import net.corda.nodeapi.internal.serialization.* +import net.corda.nodeapi.internal.serialization.AllWhitelist +import net.corda.nodeapi.internal.serialization.CordaSerializationEncoding +import net.corda.nodeapi.internal.serialization.EmptyWhitelist +import net.corda.nodeapi.internal.serialization.GeneratedAttachment import net.corda.nodeapi.internal.serialization.amqp.SerializerFactory.Companion.isPrimitive -import net.corda.nodeapi.internal.serialization.amqp.testutils.* -import net.corda.nodeapi.internal.serialization.carpenter.ClassCarpenterImpl +import net.corda.nodeapi.internal.serialization.amqp.testutils.deserialize +import net.corda.nodeapi.internal.serialization.amqp.testutils.serialize +import net.corda.nodeapi.internal.serialization.amqp.testutils.testDefaultFactory +import net.corda.nodeapi.internal.serialization.amqp.testutils.testDefaultFactoryNoEvolution +import net.corda.nodeapi.internal.serialization.amqp.testutils.testSerializationContext +import net.corda.nodeapi.internal.serialization.encodingNotPermittedFormat import net.corda.testing.contracts.DummyContract import net.corda.testing.core.BOB_NAME import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.core.TestIdentity import net.corda.testing.internal.rigorousMock import org.apache.activemq.artemis.api.core.SimpleString -import org.apache.qpid.proton.amqp.* +import org.apache.qpid.proton.amqp.Decimal128 +import org.apache.qpid.proton.amqp.Decimal32 +import org.apache.qpid.proton.amqp.Decimal64 +import org.apache.qpid.proton.amqp.Symbol +import org.apache.qpid.proton.amqp.UnsignedByte +import org.apache.qpid.proton.amqp.UnsignedInteger +import org.apache.qpid.proton.amqp.UnsignedLong +import org.apache.qpid.proton.amqp.UnsignedShort import org.apache.qpid.proton.codec.DecoderImpl import org.apache.qpid.proton.codec.EncoderImpl -import org.assertj.core.api.Assertions.* +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatExceptionOfType +import org.assertj.core.api.Assertions.assertThatThrownBy +import org.assertj.core.api.Assertions.catchThrowable import org.bouncycastle.cert.X509v2CRLBuilder import org.bouncycastle.cert.jcajce.JcaX509CRLConverter import org.bouncycastle.jce.provider.BouncyCastleProvider @@ -60,7 +88,20 @@ import java.io.NotSerializableException import java.math.BigDecimal import java.math.BigInteger import java.security.cert.X509CRL -import java.time.* +import java.time.DayOfWeek +import java.time.Duration +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.Month +import java.time.MonthDay +import java.time.OffsetDateTime +import java.time.OffsetTime +import java.time.Period +import java.time.Year +import java.time.YearMonth +import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import java.util.* import kotlin.reflect.full.superclasses @@ -243,7 +284,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi } EncoderImpl(decoder) DeserializationInput.withDataBytes(bytes, encodingWhitelist) { - decoder.setByteBuffer(it) + decoder.byteBuffer = it // Check that a vanilla AMQP decoder can deserialize without schema. val result = decoder.readObject() as Envelope assertNotNull(result) @@ -899,7 +940,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi @Test fun `test generic in constructor serialize`() { - val obj = GenericSubclass(OtherGeneric()) + val obj = GenericSubclass(OtherGeneric()) serdes(obj) } @@ -1196,7 +1237,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi factory.register(net.corda.nodeapi.internal.serialization.amqp.custom.BigDecimalSerializer) factory.register(net.corda.nodeapi.internal.serialization.amqp.custom.CurrencySerializer) - val c = C(Amount(100, BigDecimal("1.5"), Currency.getInstance("USD"))) + val c = C(Amount(100, BigDecimal("1.5"), Currency.getInstance("USD"))) // were the issue not fixed we'd blow up here SerializationOutput(factory, compression).serialize(c) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt index a75d94da25..a9c75359b7 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt @@ -17,8 +17,8 @@ val TESTING_CONTEXT = SerializationContextImpl(amqpMagic, // Test factory that lets us count the number of serializer registration attempts class TestSerializerFactory( - wl : ClassWhitelist, - cl : ClassLoader + wl: ClassWhitelist, + cl: ClassLoader ) : SerializerFactory(wl, cl) { var registerCount = 0 @@ -83,16 +83,17 @@ class TestSerializationFactory : SerializationFactory() { class SerializationSchemaTests { @Test fun onlyRegisterCustomSerializersOnce() { - @CordaSerializable data class C(val a: Int) + @CordaSerializable + data class C(val a: Int) val c = C(1) val testSerializationFactory = TestSerializationFactory() val expectedCustomSerializerCount = 40 - assertEquals (0, testFactory.registerCount) - c.serialize (testSerializationFactory, TESTING_CONTEXT) - assertEquals (expectedCustomSerializerCount, testFactory.registerCount) - c.serialize (testSerializationFactory, TESTING_CONTEXT) - assertEquals (expectedCustomSerializerCount, testFactory.registerCount) + assertEquals(0, testFactory.registerCount) + c.serialize(testSerializationFactory, TESTING_CONTEXT) + assertEquals(expectedCustomSerializerCount, testFactory.registerCount) + c.serialize(testSerializationFactory, TESTING_CONTEXT) + assertEquals(expectedCustomSerializerCount, testFactory.registerCount) } } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt index 7ce41ef211..28234d4eac 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt @@ -78,7 +78,6 @@ class StaticInitialisationOfSerializedObjectTest { assertEquals(1, serialisersByType.size) } - @Test fun deserializeTest() { data class D(val c: C2) @@ -109,8 +108,7 @@ class StaticInitialisationOfSerializedObjectTest { // Version of a serializer factory that will allow the class carpenter living on the // factory to have a different whitelist applied to it than the factory class TestSerializerFactory(wl1: ClassWhitelist, wl2: ClassWhitelist) : - SerializerFactory(wl1, ClassCarpenterImpl(ClassLoader.getSystemClassLoader(), wl2)) { - } + SerializerFactory(wl1, ClassCarpenterImpl(ClassLoader.getSystemClassLoader(), wl2)) // This time have the serialization factory and the carpenter use different whitelists @Test diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt index 23d55a8c72..1079766bed 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt @@ -27,7 +27,7 @@ class TestClassLoader(private var exclude: List) : ClassLoader() { } interface TestInterface { - fun runThing() : Int + fun runThing(): Int } // Create a custom serialization factory where we need to be able to both specify a carpenter @@ -63,10 +63,10 @@ class CarpenterExceptionTests { val a1 = CLA().loadClass(A::class.java.name) val a2 = CLB().loadClass(A::class.java.name) - assertTrue (TypeToken.of(a1).isSubtypeOf(a2)) - assertTrue (a1 is Type) - assertTrue (a2 is Type) - assertTrue (a3 is Type) + assertTrue(TypeToken.of(a1).isSubtypeOf(a2)) + assertTrue(a1 is Type) + assertTrue(a2 is Type) + assertTrue(a3 is Type) assertEquals(a1, a2) assertEquals(a1, a3) assertEquals(a2, a3) @@ -74,11 +74,11 @@ class CarpenterExceptionTests { @Test fun carpenterExceptionRethrownAsNotSerializableException() { - data class C2 (val i: Int) : TestInterface { + data class C2(val i: Int) : TestInterface { override fun runThing() = 1 } - data class C1 (val i: Int, val c: C2) + data class C1(val i: Int, val c: C2) // We need two factories to ensure when we deserialize the blob we don't just use the serializer // we built to serialise things diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt index 361c0a6213..61d7b76730 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt @@ -50,7 +50,7 @@ fun Schema.mangleNames(names: List): Schema { * rather than have it create its own */ class SerializerFactoryExternalCarpenter(classCarpenter: ClassCarpenter) - : SerializerFactory (classCarpenter.whitelist, classCarpenter) + : SerializerFactory(classCarpenter.whitelist, classCarpenter) open class AmqpCarpenterBase(whitelist: ClassWhitelist) { var cc = ClassCarpenterImpl(whitelist = whitelist) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt index f2a14647ff..6b4ca7baa9 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt @@ -63,7 +63,8 @@ class ClassCarpenterWhitelistTest { // it's marked as CordaSerializable @Test fun notWhitelistedButAnnotated() { - @CordaSerializable data class A(val a: Int) + @CordaSerializable + data class A(val a: Int) class WL : ClassWhitelist { override fun hasListed(type: Class<*>) = false diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt index 6b0c8ca46d..e116b78aca 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt @@ -108,6 +108,5 @@ class MultiMemberCompositeSchemaToClassCarpenterTests : AmqpCarpenterBase(AllWhi assertEquals(pinochio.getMethod("getA").invoke(p), amqpObj.a) assertEquals(pinochio.getMethod("getB").invoke(p), amqpObj.b) } - } diff --git a/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt b/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt index ee1c434b84..b70f5654f2 100644 --- a/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt @@ -52,7 +52,7 @@ class AuthDBTests : NodeBasedTest() { @JvmField val databaseSchemas = IntegrationTestSchemas(ALICE_NAME.toDatabaseSchemaName()) - private val cacheExpireAfterSecs: Long = 1 + private const val cacheExpireAfterSecs: Long = 1 @JvmStatic @Parameterized.Parameters(name = "password encryption format = {0}") @@ -248,7 +248,7 @@ private class UsersDB : AutoCloseable { val jdbcUrl: String companion object { - val DB_CREATE_SCHEMA = """ + const val DB_CREATE_SCHEMA = """ CREATE TABLE users (username VARCHAR(256), password TEXT); CREATE TABLE user_roles (username VARCHAR(256), role_name VARCHAR(256)); CREATE TABLE roles_permissions (role_name VARCHAR(256), permission TEXT); @@ -259,7 +259,7 @@ private class UsersDB : AutoCloseable { session { it.execute("INSERT INTO users VALUES ('${user.username}', '${user.password}')") for (role in user.roles) { - it.execute("INSERT INTO user_roles VALUES ('${user.username}', '${role}')") + it.execute("INSERT INTO user_roles VALUES ('${user.username}', '$role')") } } } @@ -287,7 +287,7 @@ private class UsersDB : AutoCloseable { } private val dataSource: DataSource - inline private fun session(statement: (Statement) -> Unit) { + private inline fun session(statement: (Statement) -> Unit) { dataSource.connection.use { it.autoCommit = false it.createStatement().use(statement) @@ -299,7 +299,7 @@ private class UsersDB : AutoCloseable { users: List = emptyList(), roleAndPermissions: List = emptyList()) { - jdbcUrl = "jdbc:h2:mem:${name};DB_CLOSE_DELAY=-1" + jdbcUrl = "jdbc:h2:mem:$name;DB_CLOSE_DELAY=-1" dataSource = DataSourceFactory.createDataSource(Properties().apply { put("dataSourceClassName", "org.h2.jdbcx.JdbcDataSource") put("dataSource.url", jdbcUrl) @@ -338,7 +338,6 @@ private val hashedPasswords = mapOf( * A functional object for producing password encoded according to the given scheme. */ private fun encodePassword(s: String, format: PasswordEncryption) = when (format) { - PasswordEncryption.NONE -> s - PasswordEncryption.SHIRO_1_CRYPT -> hashedPasswords[format]!![s] ?: - DefaultPasswordService().encryptPassword(s.toCharArray()) - } \ No newline at end of file + PasswordEncryption.NONE -> s + PasswordEncryption.SHIRO_1_CRYPT -> hashedPasswords[format]!![s] ?: DefaultPasswordService().encryptPassword(s.toCharArray()) +} \ No newline at end of file diff --git a/node/src/integration-test/kotlin/net/corda/node/BootTests.kt b/node/src/integration-test/kotlin/net/corda/node/BootTests.kt index 8962669597..1ada752f6d 100644 --- a/node/src/integration-test/kotlin/net/corda/node/BootTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/BootTests.kt @@ -51,8 +51,7 @@ class BootTests : IntegrationTest() { fun `java deserialization is disabled`() { driver { val user = User("u", "p", setOf(startFlow())) - val future = CordaRPCClient(startNode(rpcUsers = listOf(user)).getOrThrow().rpcAddress). - start(user.username, user.password).proxy.startFlow(::ObjectInputStreamFlow).returnValue + val future = CordaRPCClient(startNode(rpcUsers = listOf(user)).getOrThrow().rpcAddress).start(user.username, user.password).proxy.startFlow(::ObjectInputStreamFlow).returnValue assertThatThrownBy { future.getOrThrow() }.isInstanceOf(InvalidClassException::class.java).hasMessage("filter status: REJECTED") } } diff --git a/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt b/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt index 436c2e2c07..4a01cb8cc3 100644 --- a/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt @@ -42,7 +42,7 @@ class NodeUnloadHandlerTests : IntegrationTest() { startNode(providedName = DUMMY_BANK_A_NAME).getOrThrow() // just want to fall off the end of this for the mo... } - Assert.assertTrue("Timed out waiting for AbstractNode to invoke the test service shutdown callback",latch.await(30, TimeUnit.SECONDS)) + Assert.assertTrue("Timed out waiting for AbstractNode to invoke the test service shutdown callback", latch.await(30, TimeUnit.SECONDS)) } @CordaService @@ -60,7 +60,5 @@ class NodeUnloadHandlerTests : IntegrationTest() { log.info("shutting down") latch.countDown() } - } - } \ No newline at end of file diff --git a/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt b/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt index d3b70aa9a5..5a6b964700 100644 --- a/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt @@ -47,14 +47,12 @@ class AMQPBridgeTest { private val log = loggerFor() - private val ALICE = TestIdentity(ALICE_NAME) private val BOB = TestIdentity(BOB_NAME) private val artemisPort = freePort() private val artemisPort2 = freePort() private val amqpPort = freePort() private val artemisAddress = NetworkHostAndPort("localhost", artemisPort) - private val artemisAddress2 = NetworkHostAndPort("localhost", artemisPort2) private val amqpAddress = NetworkHostAndPort("localhost", amqpPort) private abstract class AbstractNodeConfiguration : NodeConfiguration diff --git a/node/src/integration-test/kotlin/net/corda/node/amqp/ProtonWrapperTests.kt b/node/src/integration-test/kotlin/net/corda/node/amqp/ProtonWrapperTests.kt index a70132b3a8..ef9e09b741 100644 --- a/node/src/integration-test/kotlin/net/corda/node/amqp/ProtonWrapperTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/amqp/ProtonWrapperTests.kt @@ -20,20 +20,30 @@ import net.corda.core.toFuture import net.corda.core.utilities.NetworkHostAndPort import net.corda.node.services.config.* import net.corda.node.services.messaging.ArtemisMessagingServer +import net.corda.nodeapi.ArtemisTcpTransport.Companion.CIPHER_SUITES import net.corda.nodeapi.internal.ArtemisMessagingClient import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.P2P_PREFIX import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.PEER_USER +import net.corda.nodeapi.internal.config.SSLConfiguration +import net.corda.nodeapi.internal.createDevKeyStores +import net.corda.nodeapi.internal.crypto.* import net.corda.nodeapi.internal.protonwrapper.messages.MessageStatus import net.corda.nodeapi.internal.protonwrapper.netty.AMQPClient import net.corda.nodeapi.internal.protonwrapper.netty.AMQPServer import net.corda.testing.core.* +import net.corda.testing.internal.createDevIntermediateCaCertPath import net.corda.testing.internal.rigorousMock import org.apache.activemq.artemis.api.core.RoutingType import org.junit.Assert.assertArrayEquals import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import java.security.SecureRandom +import java.security.cert.X509Certificate +import javax.net.ssl.* +import kotlin.concurrent.thread import kotlin.test.assertEquals +import kotlin.test.assertTrue class ProtonWrapperTests { @Rule @@ -109,6 +119,91 @@ class ProtonWrapperTests { } } + private fun SSLConfiguration.createTrustStore(rootCert: X509Certificate) { + val trustStore = loadOrCreateKeyStore(trustStoreFile, trustStorePassword) + trustStore.addOrReplaceCertificate(X509Utilities.CORDA_ROOT_CA, rootCert) + trustStore.save(trustStoreFile, trustStorePassword) + } + + + @Test + fun `Test AMQP Client with invalid root certificate`() { + val sslConfig = object : SSLConfiguration { + override val certificatesDirectory = temporaryFolder.root.toPath() + override val keyStorePassword = "serverstorepass" + override val trustStorePassword = "trustpass" + override val crlCheckSoftFail: Boolean = true + } + + val (rootCa, intermediateCa) = createDevIntermediateCaCertPath() + + // Generate server cert and private key and populate another keystore suitable for SSL + sslConfig.createDevKeyStores(ALICE_NAME, rootCa.certificate, intermediateCa) + sslConfig.createTrustStore(rootCa.certificate) + + val keyStore = loadKeyStore(sslConfig.sslKeystore, sslConfig.keyStorePassword) + val trustStore = loadKeyStore(sslConfig.trustStoreFile, sslConfig.trustStorePassword) + + val context = SSLContext.getInstance("TLS") + val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()) + keyManagerFactory.init(keyStore, sslConfig.keyStorePassword.toCharArray()) + val keyManagers = keyManagerFactory.keyManagers + val trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) + trustMgrFactory.init(trustStore) + val trustManagers = trustMgrFactory.trustManagers + context.init(keyManagers, trustManagers, SecureRandom()) + + val serverSocketFactory = context.serverSocketFactory + + val serverSocket = serverSocketFactory.createServerSocket(serverPort) as SSLServerSocket + val serverParams = SSLParameters(CIPHER_SUITES.toTypedArray(), + arrayOf("TLSv1.2")) + serverParams.wantClientAuth = true + serverParams.needClientAuth = true + serverParams.endpointIdentificationAlgorithm = null // Reconfirm default no server name indication, use our own validator. + serverSocket.sslParameters = serverParams + serverSocket.useClientMode = false + + val lock = Object() + var done = false + var handshakeError = false + + val serverThread = thread { + try { + val sslServerSocket = serverSocket.accept() as SSLSocket + sslServerSocket.addHandshakeCompletedListener { + done = true + } + sslServerSocket.startHandshake() + synchronized(lock) { + while (!done) { + lock.wait(1000) + } + } + sslServerSocket.close() + } catch (ex: SSLHandshakeException) { + handshakeError = true + } + } + + val amqpClient = createClient() + amqpClient.use { + val clientConnected = amqpClient.onConnection.toFuture() + amqpClient.start() + val clientConnect = clientConnected.get() + assertEquals(false, clientConnect.connected) + synchronized(lock) { + done = true + lock.notifyAll() + } + } + serverThread.join(1000) + assertTrue(handshakeError) + serverSocket.close() + assertTrue(done) + } + + @Test fun `Client Failover for multiple IP`() { val amqpServer = createServer(serverPort) diff --git a/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt index f06aaef251..e2f954cec3 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt @@ -25,7 +25,6 @@ import net.corda.core.node.services.vault.QueryCriteria import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.NonEmptySet import net.corda.core.utilities.getOrThrow -import net.corda.core.utilities.seconds import net.corda.testMessage.ScheduledState import net.corda.testMessage.SpentState import net.corda.testing.contracts.DummyContract diff --git a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt index 3936f77d5a..21a486f1a3 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt @@ -64,5 +64,4 @@ class FlowVersioningTest : NodeBasedTest() { @Suspendable override fun call() = otherSideSession.send(otherSideSession.getCounterpartyFlowInfo().flowVersion) } - } \ No newline at end of file diff --git a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt index 30ef8aea5b..9713ad28d9 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt @@ -13,7 +13,13 @@ package net.corda.node.services.statemachine import co.paralleluniverse.fibers.Suspendable import net.corda.client.rpc.CordaRPCClient import net.corda.core.crypto.SecureHash -import net.corda.core.flows.* +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.FlowSession +import net.corda.core.flows.InitiatedBy +import net.corda.core.flows.InitiatingFlow +import net.corda.core.flows.ReceiveTransactionFlow +import net.corda.core.flows.SendTransactionFlow +import net.corda.core.flows.StartableByRPC import net.corda.core.internal.InputStreamAndHash import net.corda.core.internal.concurrent.transpose import net.corda.core.messaging.startFlow @@ -23,7 +29,11 @@ import net.corda.node.services.config.MB import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyState -import net.corda.testing.core.* +import net.corda.testing.core.ALICE_NAME +import net.corda.testing.core.BOB_NAME +import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.core.TestIdentity +import net.corda.testing.core.dummyCommand import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.driver import net.corda.testing.internal.IntegrationTest diff --git a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt index 9228047dcf..217b261f5c 100644 --- a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt +++ b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt @@ -12,6 +12,7 @@ package net.corda.node.internal import com.codahale.metrics.MetricRegistry import com.google.common.collect.MutableClassToInstanceMap +import com.google.common.util.concurrent.MoreExecutors import net.corda.confidential.SwapIdentitiesFlow import net.corda.confidential.SwapIdentitiesHandler import net.corda.core.CordaException @@ -19,7 +20,16 @@ import net.corda.core.concurrent.CordaFuture import net.corda.core.context.InvocationContext import net.corda.core.crypto.newSecureRandom import net.corda.core.crypto.sign -import net.corda.core.flows.* +import net.corda.core.flows.ContractUpgradeFlow +import net.corda.core.flows.FinalityFlow +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.FlowLogicRefFactory +import net.corda.core.flows.FlowSession +import net.corda.core.flows.InitiatedBy +import net.corda.core.flows.InitiatingFlow +import net.corda.core.flows.NotaryChangeFlow +import net.corda.core.flows.NotaryFlow +import net.corda.core.flows.StartableByService import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.identity.PartyAndCertificate @@ -30,15 +40,33 @@ import net.corda.core.internal.concurrent.map import net.corda.core.internal.concurrent.openFuture import net.corda.core.internal.notary.NotaryService import net.corda.core.internal.uncheckedCast -import net.corda.core.messaging.* -import net.corda.core.node.* -import net.corda.core.node.services.* +import net.corda.core.messaging.CordaRPCOps +import net.corda.core.messaging.FlowHandle +import net.corda.core.messaging.FlowHandleImpl +import net.corda.core.messaging.FlowProgressHandle +import net.corda.core.messaging.FlowProgressHandleImpl +import net.corda.core.messaging.RPCOps +import net.corda.core.node.AppServiceHub +import net.corda.core.node.NetworkParameters +import net.corda.core.node.NodeInfo +import net.corda.core.node.ServiceHub +import net.corda.core.node.ServicesForResolution +import net.corda.core.node.StatesToRecord +import net.corda.core.node.services.AttachmentStorage +import net.corda.core.node.services.CordaService +import net.corda.core.node.services.IdentityService +import net.corda.core.node.services.KeyManagementService +import net.corda.core.node.services.TransactionVerifierService import net.corda.core.serialization.SerializationWhitelist import net.corda.core.serialization.SerializeAsToken import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.serialize import net.corda.core.transactions.SignedTransaction -import net.corda.core.utilities.* +import net.corda.core.utilities.NetworkHostAndPort +import net.corda.core.utilities.days +import net.corda.core.utilities.debug +import net.corda.core.utilities.getOrThrow +import net.corda.core.utilities.minutes import net.corda.node.CordaClock import net.corda.node.VersionInfo import net.corda.node.internal.classloading.requireAnnotation @@ -50,21 +78,61 @@ import net.corda.node.internal.security.RPCSecurityManager import net.corda.node.services.ContractUpgradeHandler import net.corda.node.services.FinalityHandler import net.corda.node.services.NotaryChangeHandler -import net.corda.node.services.api.* -import net.corda.node.services.config.* +import net.corda.node.services.api.CheckpointStorage +import net.corda.node.services.api.DummyAuditService +import net.corda.node.services.api.FlowStarter +import net.corda.node.services.api.IdentityServiceInternal +import net.corda.node.services.api.MonitoringService +import net.corda.node.services.api.NetworkMapCacheBaseInternal +import net.corda.node.services.api.NetworkMapCacheInternal +import net.corda.node.services.api.NodePropertiesStore +import net.corda.node.services.api.SchedulerService +import net.corda.node.services.api.SchemaService +import net.corda.node.services.api.ServiceHubInternal +import net.corda.node.services.api.StartedNodeServices +import net.corda.node.services.api.VaultServiceInternal +import net.corda.node.services.api.WritableTransactionStorage +import net.corda.node.services.config.BFTSMaRtConfiguration +import net.corda.node.services.config.NodeConfiguration +import net.corda.node.services.config.NotaryConfig +import net.corda.node.services.config.configureWithDevSSLCertificate import net.corda.node.services.config.shell.toShellConfig +import net.corda.node.services.config.shouldInitCrashShell import net.corda.node.services.events.NodeSchedulerService import net.corda.node.services.events.ScheduledActivityObserver import net.corda.node.services.identity.PersistentIdentityService import net.corda.node.services.keys.PersistentKeyManagementService import net.corda.node.services.messaging.DeduplicationHandler import net.corda.node.services.messaging.MessagingService -import net.corda.node.services.network.* -import net.corda.node.services.persistence.* +import net.corda.node.services.network.NetworkMapCacheImpl +import net.corda.node.services.network.NetworkMapClient +import net.corda.node.services.network.NetworkMapUpdater +import net.corda.node.services.network.NodeInfoWatcher +import net.corda.node.services.network.PersistentNetworkMapCache +import net.corda.node.services.persistence.AbstractPartyDescriptor +import net.corda.node.services.persistence.AbstractPartyToX500NameAsStringConverter +import net.corda.node.services.persistence.DBCheckpointStorage +import net.corda.node.services.persistence.DBTransactionMappingStorage +import net.corda.node.services.persistence.DBTransactionStorage +import net.corda.node.services.persistence.NodeAttachmentService +import net.corda.node.services.persistence.NodePropertiesPersistentStore +import net.corda.node.services.persistence.RunOnceService import net.corda.node.services.schema.HibernateObserver import net.corda.node.services.schema.NodeSchemaService -import net.corda.node.services.statemachine.* -import net.corda.node.services.transactions.* +import net.corda.node.services.statemachine.FlowLogicRefFactoryImpl +import net.corda.node.services.statemachine.SingleThreadedStateMachineManager +import net.corda.node.services.statemachine.StateMachineManager +import net.corda.node.services.statemachine.appName +import net.corda.node.services.statemachine.flowVersionAndInitiatingClass +import net.corda.node.services.transactions.BFTNonValidatingNotaryService +import net.corda.node.services.transactions.BFTSMaRt +import net.corda.node.services.transactions.MySQLNonValidatingNotaryService +import net.corda.node.services.transactions.MySQLValidatingNotaryService +import net.corda.node.services.transactions.RaftNonValidatingNotaryService +import net.corda.node.services.transactions.RaftUniquenessProvider +import net.corda.node.services.transactions.RaftValidatingNotaryService +import net.corda.node.services.transactions.SimpleNotaryService +import net.corda.node.services.transactions.ValidatingNotaryService import net.corda.node.services.upgrade.ContractUpgradeServiceImpl import net.corda.node.services.vault.NodeVaultService import net.corda.node.utilities.AffinityExecutor @@ -75,7 +143,11 @@ import net.corda.nodeapi.internal.DevIdentityGenerator import net.corda.nodeapi.internal.NodeInfoAndSigned import net.corda.nodeapi.internal.SignedNodeInfo import net.corda.nodeapi.internal.crypto.X509Utilities -import net.corda.nodeapi.internal.persistence.* +import net.corda.nodeapi.internal.persistence.CordaPersistence +import net.corda.nodeapi.internal.persistence.DatabaseConfig +import net.corda.nodeapi.internal.persistence.HibernateConfiguration +import net.corda.nodeapi.internal.persistence.SchemaMigration +import net.corda.nodeapi.internal.persistence.isH2Database import net.corda.nodeapi.internal.storeLegalIdentity import net.corda.tools.shell.InteractiveShell import org.apache.activemq.artemis.utils.ReusableLatch @@ -98,6 +170,7 @@ import java.time.Duration import java.time.format.DateTimeParseException import java.util.* import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import kotlin.collections.set @@ -271,7 +344,17 @@ abstract class AbstractNode(val configuration: NodeConfiguration, flowLogicRefFactory = flowLogicRefFactory, drainingModePollPeriod = configuration.drainingModePollPeriod, nodeProperties = nodeProperties) - makeVaultObservers(schedulerService, database.hibernateConfig, smm, schemaService, flowLogicRefFactory) + + (serverThread as? ExecutorService)?.let { + runOnStop += { + // We wait here, even though any in-flight messages should have been drained away because the + // server thread can potentially have other non-messaging tasks scheduled onto it. The timeout value is + // arbitrary and might be inappropriate. + MoreExecutors.shutdownAndAwaitTermination(it, 50, TimeUnit.SECONDS) + } + } + + makeVaultObservers(schedulerService, database.hibernateConfig, schemaService, flowLogicRefFactory) val rpcOps = makeRPCOps(flowStarter, database, smm) startMessagingService(rpcOps) installCoreFlows() @@ -653,16 +736,15 @@ abstract class AbstractNode(val configuration: NodeConfiguration, networkParameters, servicesForResolution) network = makeMessagingService(database, nodeInfo, nodeProperties, networkParameters) - val tokenizableServices = mutableListOf(attachments, network, services.vaultService, + return mutableListOf(attachments, network, services.vaultService, services.keyManagementService, services.identityService, platformClock, services.auditService, services.monitoringService, services.networkMapCache, services.schemaService, services.transactionVerifierService, services.validatedTransactions, services.contractUpgradeService, services, cordappProvider, this) - return tokenizableServices } protected open fun makeTransactionStorage(database: CordaPersistence, transactionCacheSizeBytes: Long): WritableTransactionStorage = DBTransactionStorage(transactionCacheSizeBytes) - private fun makeVaultObservers(schedulerService: SchedulerService, hibernateConfig: HibernateConfiguration, smm: StateMachineManager, schemaService: SchemaService, flowLogicRefFactory: FlowLogicRefFactory) { + private fun makeVaultObservers(schedulerService: SchedulerService, hibernateConfig: HibernateConfiguration, schemaService: SchemaService, flowLogicRefFactory: FlowLogicRefFactory) { ScheduledActivityObserver.install(services.vaultService, schedulerService, flowLogicRefFactory) HibernateObserver.install(services.vaultService.rawUpdates, hibernateConfig, schemaService) } @@ -709,7 +791,7 @@ abstract class AbstractNode(val configuration: NodeConfiguration, } val props = configuration.dataSourceProperties - if (props.isEmpty()) throw DatabaseConfigurationException("There must be a database configured.") + if (props.isEmpty) throw DatabaseConfigurationException("There must be a database configured.") val database = configureDatabase(props, configuration.database, identityService, schemaService) // Now log the vendor string as this will also cause a connection to be tested eagerly. logVendorString(database, log) @@ -729,7 +811,7 @@ abstract class AbstractNode(val configuration: NodeConfiguration, } } - open protected fun checkNetworkMapIsInitialized() { + protected open fun checkNetworkMapIsInitialized() { if (!services.networkMapCache.loadDBSuccess) { // TODO: There should be a consistent approach to configuration error exceptions. throw NetworkMapCacheEmptyException() @@ -913,8 +995,8 @@ abstract class AbstractNode(val configuration: NodeConfiguration, override fun jdbcSession(): Connection = database.createSession() // allows services to register handlers to be informed when the node stop method is called - override fun registerUnloadHandler(handler: () -> Unit) { - runOnStop += handler + override fun registerUnloadHandler(runOnStop: () -> Unit) { + this@AbstractNode.runOnStop += runOnStop } } } diff --git a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt index 80ece1b22b..21f6b7b017 100644 --- a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt +++ b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt @@ -102,12 +102,14 @@ internal class CordaRPCOpsImpl( } } + @Suppress("OverridingDeprecatedMember") override fun internalVerifiedTransactionsSnapshot(): List { - val (snapshot, updates) = internalVerifiedTransactionsFeed() + val (snapshot, updates) = @Suppress("DEPRECATION") internalVerifiedTransactionsFeed() updates.notUsed() return snapshot } + @Suppress("OverridingDeprecatedMember") override fun internalVerifiedTransactionsFeed(): DataFeed, SignedTransaction> { return database.transaction { services.validatedTransactions.track() 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 1e643b5598..a159b97714 100644 --- a/node/src/main/kotlin/net/corda/node/internal/Node.kt +++ b/node/src/main/kotlin/net/corda/node/internal/Node.kt @@ -192,7 +192,7 @@ open class Node(configuration: NodeConfiguration, val rpcServerAddresses = if (configuration.rpcOptions.standAloneBroker) { BrokerAddresses(configuration.rpcOptions.address!!, configuration.rpcOptions.adminAddress) } else { - startLocalRpcBroker(networkParameters) + startLocalRpcBroker() } val advertisedAddress = info.addresses.single() val externalBridge = configuration.enterpriseConfiguration.externalBridge @@ -232,7 +232,7 @@ open class Node(configuration: NodeConfiguration, nodeProperties.flowsDrainingMode.values) } - private fun startLocalRpcBroker(networkParameters: NetworkParameters): BrokerAddresses? { + private fun startLocalRpcBroker(): BrokerAddresses? { with(configuration) { return rpcOptions.address?.let { require(rpcOptions.address != null) { "RPC address needs to be specified for local RPC broker." } diff --git a/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt b/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt index 0d7af03b91..dab26e0ed4 100644 --- a/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt +++ b/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt @@ -152,11 +152,11 @@ open class NodeStartup(val args: Array) { return true } - open protected fun preNetworkRegistration(conf: NodeConfiguration) = Unit + protected open fun preNetworkRegistration(conf: NodeConfiguration) = Unit - open protected fun createNode(conf: NodeConfiguration, versionInfo: VersionInfo): Node = Node(conf, versionInfo) + protected open fun createNode(conf: NodeConfiguration, versionInfo: VersionInfo): Node = Node(conf, versionInfo) - open protected fun startNode(conf: NodeConfiguration, versionInfo: VersionInfo, startTime: Long, cmdlineOptions: CmdLineOptions) { + protected open fun startNode(conf: NodeConfiguration, versionInfo: VersionInfo, startTime: Long, cmdlineOptions: CmdLineOptions) { val node = createNode(conf, versionInfo) if (cmdlineOptions.justGenerateNodeInfo) { // Perform the minimum required start-up logic to be able to write a nodeInfo to disk @@ -190,7 +190,7 @@ open class NodeStartup(val args: Array) { startedNode.internals.run() } - open protected fun logStartupInfo(versionInfo: VersionInfo, cmdlineOptions: CmdLineOptions, conf: NodeConfiguration) { + protected open fun logStartupInfo(versionInfo: VersionInfo, cmdlineOptions: CmdLineOptions, conf: NodeConfiguration) { logger.info("Vendor: ${versionInfo.vendor}") logger.info("Release: ${versionInfo.releaseVersion}") logger.info("Platform Version: ${versionInfo.platformVersion}") @@ -212,7 +212,7 @@ open class NodeStartup(val args: Array) { logger.info("Starting as node on ${conf.p2pAddress}") } - open protected fun registerWithNetwork(conf: NodeConfiguration, nodeRegistrationConfig: NodeRegistrationOption) { + protected open fun registerWithNetwork(conf: NodeConfiguration, nodeRegistrationConfig: NodeRegistrationOption) { val compatibilityZoneURL = conf.compatibilityZoneURL!! println() println("******************************************************************") @@ -223,9 +223,9 @@ open class NodeStartup(val args: Array) { NodeRegistrationHelper(conf, HTTPNetworkRegistrationService(compatibilityZoneURL), nodeRegistrationConfig).buildKeystore() } - open protected fun loadConfigFile(cmdlineOptions: CmdLineOptions): NodeConfiguration = cmdlineOptions.loadConfig() + protected open fun loadConfigFile(cmdlineOptions: CmdLineOptions): NodeConfiguration = cmdlineOptions.loadConfig() - open protected fun banJavaSerialisation(conf: NodeConfiguration) { + protected open fun banJavaSerialisation(conf: NodeConfiguration) { val isOracleDbDriver = conf.dataSourceProperties.getProperty("dataSource.url", "").startsWith("jdbc:oracle:") val filter = if (conf.notary?.bftSMaRt != null && isOracleDbDriver) { @@ -241,7 +241,7 @@ open class NodeStartup(val args: Array) { SerialFilter.install(filter) } - open protected fun getVersionInfo(): VersionInfo { + protected open fun getVersionInfo(): VersionInfo { // Manifest properties are only available if running from the corda jar fun manifestValue(name: String): String? = if (Manifests.exists(name)) Manifests.read(name) else null @@ -289,7 +289,7 @@ open class NodeStartup(val args: Array) { pidFileRw.write(ourProcessID.toByteArray()) } - open protected fun initLogging(cmdlineOptions: CmdLineOptions) { + protected open fun initLogging(cmdlineOptions: CmdLineOptions) { val loggingLevel = cmdlineOptions.loggingLevel.name.toLowerCase(Locale.ENGLISH) System.setProperty("defaultLogLevel", loggingLevel) // These properties are referenced from the XML config file. if (cmdlineOptions.logToConsole) { diff --git a/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt b/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt index 9108c13a52..dedf8af509 100644 --- a/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt +++ b/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt @@ -64,8 +64,10 @@ class RpcAuthorisationProxy(private val implementation: CordaRPCOps, private val implementation.vaultTrackBy(criteria, paging, sorting, contractStateType) } + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsSnapshot() = guard("internalVerifiedTransactionsSnapshot", implementation::internalVerifiedTransactionsSnapshot) + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsFeed() = guard("internalVerifiedTransactionsFeed", implementation::internalVerifiedTransactionsFeed) override fun stateMachineRecordedTransactionMappingSnapshot() = guard("stateMachineRecordedTransactionMappingSnapshot", implementation::stateMachineRecordedTransactionMappingSnapshot) diff --git a/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt b/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt index 60f285ba2b..1c6453a273 100644 --- a/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt +++ b/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt @@ -67,6 +67,7 @@ class RpcExceptionHandlingProxy(private val delegate: SecureCordaRPCOps) : Corda override fun networkParametersFeed() = wrapFeed(delegate::networkParametersFeed) + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsFeed() = wrapFeed(delegate::internalVerifiedTransactionsFeed) override fun stateMachinesSnapshot() = wrap(delegate::stateMachinesSnapshot) @@ -81,6 +82,7 @@ class RpcExceptionHandlingProxy(private val delegate: SecureCordaRPCOps) : Corda override fun vaultQueryByWithSorting(contractStateType: Class, criteria: QueryCriteria, sorting: Sort) = wrap { delegate.vaultQueryByWithSorting(contractStateType, criteria, sorting) } + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsSnapshot() = wrap(delegate::internalVerifiedTransactionsSnapshot) override fun stateMachineRecordedTransactionMappingSnapshot() = wrap(delegate::stateMachineRecordedTransactionMappingSnapshot) diff --git a/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt b/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt index 1a8d0e7f89..9d41e5c5ab 100644 --- a/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt +++ b/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt @@ -58,7 +58,7 @@ private class MultiplexingReactiveArtemisConsumer(private val queueNames: Set = cordapps.filter { !it.contractClassNames.isEmpty() }.map { diff --git a/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt b/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt index 1559157ba0..53af2f635a 100644 --- a/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt +++ b/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt @@ -45,15 +45,15 @@ object NodeInfoSchemaV1 : MappedSchema( val hash: String, @Column(name = "addresses") - @OneToMany(cascade = arrayOf(CascadeType.ALL), orphanRemoval = true) + @OneToMany(cascade = [(CascadeType.ALL)], orphanRemoval = true) @JoinColumn(name = "node_info_id", foreignKey = ForeignKey(name = "FK__info_hosts__infos")) val addresses: List, @Column(name = "legal_identities_certs") - @ManyToMany(cascade = arrayOf(CascadeType.ALL)) + @ManyToMany(cascade = [(CascadeType.ALL)]) @JoinTable(name = "node_link_nodeinfo_party", - joinColumns = arrayOf(JoinColumn(name = "node_info_id", foreignKey = ForeignKey(name = "FK__link_nodeinfo_party__infos"))), - inverseJoinColumns = arrayOf(JoinColumn(name = "party_name", foreignKey = ForeignKey(name = "FK__link_ni_p__info_p_cert")))) + joinColumns = [(JoinColumn(name = "node_info_id", foreignKey = ForeignKey(name = "FK__link_nodeinfo_party__infos")))], + inverseJoinColumns = [(JoinColumn(name = "party_name", foreignKey = ForeignKey(name = "FK__link_ni_p__info_p_cert")))]) val legalIdentitiesAndCerts: List, @Column(name = "platform_version") @@ -117,7 +117,7 @@ object NodeInfoSchemaV1 : MappedSchema( val isMain: Boolean, - @ManyToMany(mappedBy = "legalIdentitiesAndCerts", cascade = arrayOf(CascadeType.ALL)) // ManyToMany because of distributed services. + @ManyToMany(mappedBy = "legalIdentitiesAndCerts", cascade = [(CascadeType.ALL)]) // ManyToMany because of distributed services. private val persistentNodeInfos: Set = emptySet() ) : Serializable { constructor(partyAndCert: PartyAndCertificate, isMain: Boolean = false) diff --git a/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt b/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt index f90043c896..074b5fab8d 100644 --- a/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt +++ b/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt @@ -25,14 +25,13 @@ interface AuthorizingSubject { * (e.g. an RPC invocation) represented by an [action] string followed by an * optional list of arguments. */ - fun isPermitted(action : String, vararg arguments : String) : Boolean + fun isPermitted(action: String, vararg arguments: String): Boolean } /** * An implementation of [AuthorizingSubject] permitting all actions */ -class AdminSubject(override val principal : String) : AuthorizingSubject { +class AdminSubject(override val principal: String) : AuthorizingSubject { override fun isPermitted(action: String, vararg arguments: String) = true - } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt index c23929f698..b771e58c3f 100644 --- a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt +++ b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt @@ -11,7 +11,6 @@ package net.corda.node.internal.security import net.corda.core.context.AuthServiceId -import org.apache.shiro.authc.AuthenticationException import javax.security.auth.login.FailedLoginException /** diff --git a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt index 6102d4494f..8423daf9bf 100644 --- a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt +++ b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt @@ -15,6 +15,7 @@ import com.github.benmanes.caffeine.cache.Cache import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.primitives.Ints import net.corda.core.context.AuthServiceId +import net.corda.core.internal.uncheckedCast import net.corda.core.utilities.loggerFor import net.corda.node.internal.DataSourceFactory import net.corda.node.services.config.PasswordEncryption @@ -154,10 +155,10 @@ private class RPCPermission : DomainPermission { */ private object RPCPermissionResolver : PermissionResolver { - private val SEPARATOR = '.' - private val ACTION_START_FLOW = "startflow" - private val ACTION_INVOKE_RPC = "invokerpc" - private val ACTION_ALL = "all" + private const val SEPARATOR = '.' + private const val ACTION_START_FLOW = "startflow" + private const val ACTION_INVOKE_RPC = "invokerpc" + private const val ACTION_ALL = "all" private val FLOW_RPC_CALLS = setOf( "startFlowDynamic", "startTrackedFlowDynamic", @@ -269,9 +270,8 @@ private typealias ShiroCache = org.apache.shiro.cache.Cache /* * Adapts a [com.github.benmanes.caffeine.cache.Cache] to a [org.apache.shiro.cache.Cache] implementation. */ -private fun Cache.toShiroCache(name: String) = object : ShiroCache { +private fun Cache.toShiroCache() = object : ShiroCache { - val name = name private val impl = this@toShiroCache override operator fun get(key: K) = impl.getIfPresent(key) @@ -310,7 +310,7 @@ private class CaffeineCacheManager(val maxSize: Long, override fun getCache(name: String): ShiroCache { val result = instances[name] ?: buildCache(name) instances.putIfAbsent(name, result) - return result as ShiroCache + return uncheckedCast(result) } private fun buildCache(name: String): ShiroCache { @@ -319,7 +319,7 @@ private class CaffeineCacheManager(val maxSize: Long, .expireAfterWrite(timeToLiveSeconds, TimeUnit.SECONDS) .maximumSize(maxSize) .build() - .toShiroCache(name) + .toShiroCache() } companion object { diff --git a/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt b/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt index e4df018bac..e536aaeb73 100644 --- a/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt +++ b/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt @@ -65,8 +65,7 @@ class ContractUpgradeHandler(otherSide: FlowSession) : AbstractStateReplacementF val ourSTX = serviceHub.validatedTransactions.getTransaction(proposal.stateRef.txhash) requireNotNull(ourSTX) { "We don't have a copy of the referenced state" } val oldStateAndRef = ourSTX!!.tx.outRef(proposal.stateRef.index) - val authorisedUpgrade = serviceHub.contractUpgradeService.getAuthorisedContractUpgrade(oldStateAndRef.ref) ?: - throw IllegalStateException("Contract state upgrade is unauthorised. State hash : ${oldStateAndRef.ref}") + val authorisedUpgrade = serviceHub.contractUpgradeService.getAuthorisedContractUpgrade(oldStateAndRef.ref) ?: throw IllegalStateException("Contract state upgrade is unauthorised. State hash : ${oldStateAndRef.ref}") val proposedTx = stx.coreTransaction as ContractUpgradeWireTransaction val expectedTx = ContractUpgradeUtils.assembleUpgradeTx(oldStateAndRef, proposal.modification, proposedTx.privacySalt, serviceHub) requireThat { diff --git a/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt b/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt index 025f0cac58..2e579ed055 100644 --- a/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt +++ b/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt @@ -13,7 +13,6 @@ package net.corda.node.services.api import com.codahale.metrics.MetricRegistry import net.corda.core.serialization.SingletonSerializeAsToken - /** * Provides access to various metrics and ways to notify monitoring services of things, for sysadmin purposes. * This is not an interface because it is too lightweight to bother mocking out. diff --git a/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt b/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt index 3c47746835..f9803a2820 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt @@ -64,13 +64,11 @@ object ConfigHelper { .withFallback(defaultConfig) .resolve() - log.info("Config:\n${finalConfig.root().render(ConfigRenderOptions.defaults())}") val entrySet = finalConfig.entrySet().filter { entry -> entry.key.contains("\"") } - for (mutableEntry in entrySet) { - val key = mutableEntry.key - log.error("Config files should not contain \" in property names. Please fix: ${key}") + for ((key) in entrySet) { + log.error("Config files should not contain \" in property names. Please fix: $key") } return finalConfig diff --git a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt index 3d7f1f2968..3fb8334b0b 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt @@ -83,7 +83,7 @@ interface NodeConfiguration : NodeSSLConfiguration { } val defaultAttachmentContentCacheSize: Long = 10.MB - val defaultAttachmentCacheBound = 1024L + const val defaultAttachmentCacheBound = 1024L } } diff --git a/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt b/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt index 453a9c7dbd..1ff4ad66df 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt @@ -12,7 +12,6 @@ import net.corda.tools.shell.ShellConfiguration.Companion.SSHD_HOSTKEY_DIR import net.corda.tools.shell.ShellConfiguration.Companion.SSH_PORT import net.corda.tools.shell.ShellSslOptions - //re-packs data to Shell specific classes fun NodeConfiguration.toShellConfig(): ShellConfiguration { diff --git a/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt b/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt index 21a796d841..d5cb3a94d8 100644 --- a/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt +++ b/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt @@ -9,10 +9,10 @@ import net.corda.nodeapi.internal.persistence.CordaPersistence interface ScheduledFlowRepository { fun delete(key: StateRef): Boolean fun merge(value: ScheduledStateRef): Boolean - fun getLatest(lookahead: Int) : List> + fun getLatest(lookahead: Int): List> } -class PersistentScheduledFlowRepository(val database: CordaPersistence): ScheduledFlowRepository { +class PersistentScheduledFlowRepository(val database: CordaPersistence) : ScheduledFlowRepository { private fun toPersistentEntityKey(stateRef: StateRef): PersistentStateRef { return PersistentStateRef(stateRef.txhash.toString(), stateRef.index) } @@ -32,7 +32,7 @@ class PersistentScheduledFlowRepository(val database: CordaPersistence): Schedul override fun delete(key: StateRef): Boolean { return database.transaction { - val elem = session.find(NodeSchedulerService.PersistentScheduledState::class.java, toPersistentEntityKey(key!!)) + val elem = session.find(NodeSchedulerService.PersistentScheduledState::class.java, toPersistentEntityKey(key)) if (elem != null) { session.remove(elem) true @@ -55,7 +55,7 @@ class PersistentScheduledFlowRepository(val database: CordaPersistence): Schedul } } - override fun getLatest(lookahead: Int) : List> { + override fun getLatest(lookahead: Int): List> { return database.transaction { val criteriaQuery = session.criteriaBuilder.createQuery(NodeSchedulerService.PersistentScheduledState::class.java) val shed = criteriaQuery.from(NodeSchedulerService.PersistentScheduledState::class.java) diff --git a/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt b/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt index b4f2540f70..8ec7cebf4d 100644 --- a/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt +++ b/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt @@ -35,7 +35,6 @@ import java.time.Duration * @param subjectPublicKey public key of new identity. * @param issuer issuer to generate a key and certificate for. Must be an identity this node has the private key for. * @param issuerSigner a content signer for the issuer. - * @param revocationEnabled whether to check revocation status of certificates in the certificate path. * @return X.509 certificate and path to the trust root. */ fun freshCertificate(identityService: IdentityService, diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt index f26fa64557..1c9db2dbaf 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt @@ -168,7 +168,7 @@ class ArtemisMessagingServer(private val config: NodeConfiguration, * 4. Verifiers. These are given read access to the verification request queue and write access to the response queue. */ private fun ConfigurationImpl.configureAddressSecurity(): Configuration { - val nodeInternalRole = Role(NODE_ROLE, true, true, true, true, true, true, true, true) + val nodeInternalRole = Role(NODE_ROLE, true, true, true, true, true, true, true, true, true, true) securityRoles["$INTERNAL_PREFIX#"] = setOf(nodeInternalRole) // Do not add any other roles here as it's only for the node securityRoles["$P2P_PREFIX#"] = setOf(nodeInternalRole, restrictedRole(PEER_ROLE, send = true)) securityRoles[VerifierApi.VERIFICATION_REQUESTS_QUEUE_NAME] = setOf(nodeInternalRole, restrictedRole(VERIFIER_ROLE, consume = true)) @@ -180,7 +180,7 @@ class ArtemisMessagingServer(private val config: NodeConfiguration, deleteDurableQueue: Boolean = false, createNonDurableQueue: Boolean = false, deleteNonDurableQueue: Boolean = false, manage: Boolean = false, browse: Boolean = false): Role { return Role(name, send, consume, createDurableQueue, deleteDurableQueue, createNonDurableQueue, - deleteNonDurableQueue, manage, browse) + deleteNonDurableQueue, manage, browse, createDurableQueue || createNonDurableQueue, deleteDurableQueue || deleteNonDurableQueue) } @Throws(IOException::class, KeyStoreException::class) diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt b/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt index 77c08f37b5..7fbc77a9bc 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt @@ -116,8 +116,7 @@ interface MessagingService { val myAddress: SingleMessageRecipient } -fun MessagingService.send(topicSession: String, payload: Any, to: MessageRecipients, deduplicationId: DeduplicationId = DeduplicationId.createRandom(newSecureRandom()), retryId: Long? = null, additionalHeaders: Map = emptyMap()) - = send(createMessage(topicSession, payload.serialize().bytes, deduplicationId, additionalHeaders), to, retryId) +fun MessagingService.send(topicSession: String, payload: Any, to: MessageRecipients, deduplicationId: DeduplicationId = DeduplicationId.createRandom(newSecureRandom()), retryId: Long? = null, additionalHeaders: Map = emptyMap()) = send(createMessage(topicSession, payload.serialize().bytes, deduplicationId, additionalHeaders), to, retryId) interface MessageHandlerRegistration diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt b/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt index 56127bbb85..0a32099a09 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt @@ -26,7 +26,11 @@ import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.deserialize import net.corda.core.serialization.internal.nodeSerializationEnv import net.corda.core.serialization.serialize -import net.corda.core.utilities.* +import net.corda.core.utilities.ByteSequence +import net.corda.core.utilities.NetworkHostAndPort +import net.corda.core.utilities.OpaqueBytes +import net.corda.core.utilities.contextLogger +import net.corda.core.utilities.trace import net.corda.node.VersionInfo import net.corda.node.internal.LifecycleSupport import net.corda.node.internal.artemis.ReactiveArtemisConsumer @@ -39,11 +43,14 @@ import net.corda.node.utilities.PersistentMap import net.corda.nodeapi.ArtemisTcpTransport import net.corda.nodeapi.ConnectionDirection import net.corda.nodeapi.internal.ArtemisMessagingComponent -import net.corda.nodeapi.internal.ArtemisMessagingComponent.* +import net.corda.nodeapi.internal.ArtemisMessagingComponent.ArtemisAddress import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.BRIDGE_CONTROL import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.BRIDGE_NOTIFY import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.P2PMessagingHeaders import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.PEERS_PREFIX +import net.corda.nodeapi.internal.ArtemisMessagingComponent.NodeAddress +import net.corda.nodeapi.internal.ArtemisMessagingComponent.RemoteInboxAddress +import net.corda.nodeapi.internal.ArtemisMessagingComponent.ServiceAddress import net.corda.nodeapi.internal.bridging.BridgeControl import net.corda.nodeapi.internal.bridging.BridgeEntry import net.corda.nodeapi.internal.persistence.CordaPersistence @@ -53,7 +60,12 @@ import org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID import org.apache.activemq.artemis.api.core.Message.HDR_VALIDATED_USER import org.apache.activemq.artemis.api.core.RoutingType import org.apache.activemq.artemis.api.core.SimpleString -import org.apache.activemq.artemis.api.core.client.* +import org.apache.activemq.artemis.api.core.client.ActiveMQClient +import org.apache.activemq.artemis.api.core.client.ClientConsumer +import org.apache.activemq.artemis.api.core.client.ClientMessage +import org.apache.activemq.artemis.api.core.client.ClientProducer +import org.apache.activemq.artemis.api.core.client.ClientSession +import org.apache.activemq.artemis.api.core.client.ServerLocator import org.apache.commons.lang.ArrayUtils.EMPTY_BYTE_ARRAY import rx.Observable import rx.Subscription diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt b/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt index b94c962d9f..ba3e6a4789 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt @@ -147,7 +147,7 @@ class RPCServer( private fun createObservableSubscriptionMap(): ObservableSubscriptionMap { val onObservableRemove = RemovalListener { key, value, cause -> - log.debug { "Unsubscribing from Observable with id ${key} because of ${cause}" } + log.debug { "Unsubscribing from Observable with id $key because of $cause" } value!!.subscription.unsubscribe() } return Caffeine.newBuilder().removalListener(onObservableRemove).executor(SameThreadExecutor.getExecutor()).build() @@ -384,7 +384,7 @@ class RPCServer( private fun bufferIfQueueNotBound(clientAddress: SimpleString, message: RPCApi.ServerToClient.RpcReply, context: ObservableContext): Boolean { val clientBuffer = responseMessageBuffer.compute(clientAddress, { _, value -> when (value) { - null -> BufferOrNone.Buffer(ArrayList()).apply { + null -> BufferOrNone.Buffer(ArrayList()).apply { container.add(MessageAndContext(message, context)) } is BufferOrNone.Buffer -> value.apply { diff --git a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt index d6f6512cef..9a3be36c26 100644 --- a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt +++ b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt @@ -25,7 +25,12 @@ import net.corda.core.utilities.minutes import net.corda.node.services.api.NetworkMapCacheInternal import net.corda.node.utilities.NamedThreadFactory import net.corda.nodeapi.exceptions.OutdatedNetworkParameterHashException -import net.corda.nodeapi.internal.network.* +import net.corda.nodeapi.internal.network.NETWORK_PARAMS_FILE_NAME +import net.corda.nodeapi.internal.network.NETWORK_PARAMS_UPDATE_FILE_NAME +import net.corda.nodeapi.internal.network.NetworkMap +import net.corda.nodeapi.internal.network.ParametersUpdate +import net.corda.nodeapi.internal.network.SignedNetworkParameters +import net.corda.nodeapi.internal.network.verifiedNetworkMapCert import rx.Subscription import rx.subjects.PublishSubject import java.nio.file.Path diff --git a/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt b/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt index 74acaf6ba0..2f5ecbaa05 100644 --- a/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt +++ b/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt @@ -317,7 +317,7 @@ open class PersistentNetworkMapCache( NodeInfoSchemaV1.PersistentNodeInfo::class.java) query.setParameter("host", hostAndPort.host) query.setParameter("port", hostAndPort.port) - query.setMaxResults(1) + query.maxResults = 1 val result = query.resultList return result.map { it.toNodeInfo() }.singleOrNull() } diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt index 7a6436ee00..a32d21505d 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt @@ -12,6 +12,7 @@ package net.corda.node.services.persistence import net.corda.core.identity.AbstractParty import net.corda.core.identity.CordaX500Name +import net.corda.core.internal.uncheckedCast import net.corda.core.node.services.IdentityService import net.corda.core.utilities.contextLogger import org.hibernate.type.descriptor.WrapperOptions @@ -63,10 +64,10 @@ class AbstractPartyDescriptor(private val identityService: IdentityService) : Ab override fun unwrap(value: AbstractParty?, type: Class, options: WrapperOptions): X? { return if (value != null) { if (AbstractParty::class.java.isAssignableFrom(type)) { - return value as X + return uncheckedCast(value) } if (String::class.java.isAssignableFrom(type)) { - return toString(value) as X + return uncheckedCast(toString(value)) } throw unknownUnwrap(type) } else { diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt index 2833ff0164..54511e037c 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt @@ -31,6 +31,7 @@ class AbstractPartyToX500NameAsStringConverter(private val identityService: Iden if (party != null) { val partyName = identityService.wellKnownPartyFromAnonymous(party)?.toString() if (partyName != null) return partyName + log.warn("Identity service unable to resolve AbstractParty: $party") } return null // non resolvable anonymous parties } diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt b/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt index 4bcf516049..66a1538b23 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt @@ -18,6 +18,7 @@ import net.corda.node.services.statemachine.Checkpoint import net.corda.nodeapi.internal.persistence.NODE_DATABASE_PREFIX import net.corda.nodeapi.internal.persistence.currentDBSession import org.apache.commons.lang.ArrayUtils.EMPTY_BYTE_ARRAY +import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* import java.util.stream.Stream @@ -31,7 +32,7 @@ import javax.persistence.Lob * Simple checkpoint key value storage in DB. */ class DBCheckpointStorage : CheckpointStorage { - val log = LoggerFactory.getLogger(this::class.java) + val log: Logger = LoggerFactory.getLogger(this::class.java) @Entity @javax.persistence.Table(name = "${NODE_DATABASE_PREFIX}checkpoints") diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt b/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt index c60e78ebf2..b4ebdce00f 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt @@ -54,10 +54,10 @@ class DBTransactionMappingStorage : StateMachineRecordedTransactionMappingStorag return AppendOnlyPersistentMap( toPersistentEntityKey = { it.toString() }, fromPersistentEntity = { Pair(SecureHash.parse(it.txId), StateMachineRunId(UUID.fromString(it.stateMachineRunId))) }, - toPersistentEntity = { key: SecureHash, value: StateMachineRunId -> + toPersistentEntity = { key: SecureHash, (uuid) -> DBTransactionMapping().apply { txId = key.toString() - stateMachineRunId = value.uuid.toString() + stateMachineRunId = uuid.toString() } }, persistentEntityClass = DBTransactionMapping::class.java @@ -81,11 +81,8 @@ class DBTransactionMappingStorage : StateMachineRecordedTransactionMappingStorag override fun track(): DataFeed, StateMachineTransactionMapping> { return concurrentBox.exclusive { - DataFeed( - stateMachineTransactionMap.allPersisted().map { StateMachineTransactionMapping(it.second, it.first) }.toList(), - updates.bufferUntilSubscribed().wrapWithDatabaseTransaction() - ) + DataFeed(stateMachineTransactionMap.allPersisted().map { StateMachineTransactionMapping(it.second, it.first) }.toList(), + updates.bufferUntilSubscribed().wrapWithDatabaseTransaction()) } } - } diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt b/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt index 2fe2f7a15f..f8eb3c52d2 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt @@ -106,8 +106,7 @@ class NodeAttachmentService( @ElementCollection @Column(name = "contract_class_name") - @CollectionTable(name = "node_attchments_contracts", joinColumns = arrayOf( - JoinColumn(name = "att_id", referencedColumnName = "att_id")), + @CollectionTable(name = "node_attchments_contracts", joinColumns = [(JoinColumn(name = "att_id", referencedColumnName = "att_id"))], foreignKey = ForeignKey(name = "FK__ctr_class__attachments")) var contractClassNames: List? = null ) : Serializable @@ -220,13 +219,9 @@ class NodeAttachmentService( // If repeatedly looking for non-existing attachments becomes a performance issue, this is either indicating a // a problem somewhere else or this needs to be revisited. - private val attachmentContentCache = NonInvalidatingWeightBasedCache>>( + private val attachmentContentCache = NonInvalidatingWeightBasedCache( maxWeight = attachmentContentCacheSize, - weigher = object : Weigher>> { - override fun weigh(key: SecureHash, value: Optional>): Int { - return key.size + if (value.isPresent) value.get().second.size else 0 - } - }, + weigher = Weigher>> { key, value -> key.size + if (value.isPresent) value.get().second.size else 0 }, loadFunction = { Optional.ofNullable(loadAttachmentContent(it)) } ) @@ -268,6 +263,7 @@ class NodeAttachmentService( return null } + @Suppress("OverridingDeprecatedMember") override fun importAttachment(jar: InputStream): AttachmentId { return import(jar, UNKNOWN_UPLOADER, null) } @@ -306,8 +302,9 @@ class NodeAttachmentService( } } + @Suppress("OverridingDeprecatedMember") override fun importOrGetAttachment(jar: InputStream): AttachmentId = try { - importAttachment(jar) + import(jar, UNKNOWN_UPLOADER, null) } catch (faee: java.nio.file.FileAlreadyExistsException) { AttachmentId.parse(faee.message!!) } diff --git a/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt b/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt index 31a3a28509..f4b774f6a0 100644 --- a/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt +++ b/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt @@ -52,8 +52,8 @@ internal class NodeLoginModule : LoginModule { internal const val CERT_CHAIN_CHECKS_ARG = "CertChainChecks" internal const val USE_SSL_ARG = "useSsl" - internal val SECURITY_MANAGER_ARG = "RpcSecurityManager" - internal val LOGIN_LISTENER_ARG = "LoginListener" + internal const val SECURITY_MANAGER_ARG = "RpcSecurityManager" + internal const val LOGIN_LISTENER_ARG = "LoginListener" private val log = loggerFor() } diff --git a/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt b/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt index 18e8dcb5ca..925952217b 100644 --- a/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt +++ b/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt @@ -51,7 +51,7 @@ internal class RpcBrokerConfiguration(baseDirectory: Path, maxMessageSize: Int, initialiseSettings(maxMessageSize) - val nodeInternalRole = Role(NodeLoginModule.NODE_ROLE, true, true, true, true, true, true, true, true) + val nodeInternalRole = Role(NodeLoginModule.NODE_ROLE, true, true, true, true, true, true, true, true, true, true) val rolesAdderOnLogin = RolesAdderOnLogin { username -> "${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.$username.#" to setOf(nodeInternalRole, restrictedRole( @@ -136,6 +136,6 @@ internal class RpcBrokerConfiguration(baseDirectory: Path, maxMessageSize: Int, private fun restrictedRole(name: String, send: Boolean = false, consume: Boolean = false, createDurableQueue: Boolean = false, deleteDurableQueue: Boolean = false, createNonDurableQueue: Boolean = false, deleteNonDurableQueue: Boolean = false, manage: Boolean = false, browse: Boolean = false): Role { - return Role(name, send, consume, createDurableQueue, deleteDurableQueue, createNonDurableQueue, deleteNonDurableQueue, manage, browse) + return Role(name, send, consume, createDurableQueue, deleteDurableQueue, createNonDurableQueue, deleteNonDurableQueue, manage, browse, createDurableQueue || createNonDurableQueue, deleteDurableQueue || deleteNonDurableQueue) } } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt b/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt index 975c35fa17..01f4ac0040 100644 --- a/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt +++ b/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt @@ -25,7 +25,6 @@ import net.corda.nodeapi.internal.persistence.contextTransaction import org.hibernate.FlushMode import rx.Observable - /** * Small data class bundling together a ContractState and a StateRef (as opposed to a TransactionState and StateRef * in StateAndRef) @@ -63,10 +62,7 @@ class HibernateObserver private constructor(private val config: HibernateConfigu @VisibleForTesting internal fun persistStatesWithSchema(statesAndRefs: List, schema: MappedSchema) { val sessionFactory = config.sessionFactoryForSchemas(setOf(schema)) - val session = sessionFactory.withOptions(). - connection(contextTransaction.connection). - flushMode(FlushMode.MANUAL). - openSession() + val session = sessionFactory.withOptions().connection(contextTransaction.connection).flushMode(FlushMode.MANUAL).openSession() session.use { thisSession -> statesAndRefs.forEach { val mappedObject = schemaService.generateMappedObject(it.state, schema) diff --git a/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt b/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt index 37aa9bd2ff..cadc427d50 100644 --- a/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt +++ b/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt @@ -99,9 +99,9 @@ class NodeSchemaService(extraSchemas: Set = emptySet(), includeNot // Because schema is always one supported by the state, just delegate. override fun generateMappedObject(state: ContractState, schema: MappedSchema): PersistentState { - if ((schema is VaultSchemaV1) && (state is LinearState)) + if ((schema === VaultSchemaV1) && (state is LinearState)) return VaultSchemaV1.VaultLinearStates(state.linearId, state.participants) - if ((schema is VaultSchemaV1) && (state is FungibleAsset<*>)) + if ((schema === VaultSchemaV1) && (state is FungibleAsset<*>)) return VaultSchemaV1.VaultFungibleStates(state.owner, state.amount.quantity, state.amount.token.issuer.party, state.amount.token.issuer.reference, state.participants) return (state as QueryableState).generateMappedObject(schema) } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt index 23de83ccb6..7d8b60232a 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt @@ -112,17 +112,23 @@ sealed class Action { /** * Create a new database transaction. */ - object CreateTransaction : Action() { override fun toString() = "CreateTransaction" } + object CreateTransaction : Action() { + override fun toString() = "CreateTransaction" + } /** * Roll back the current database transaction. */ - object RollbackTransaction : Action() { override fun toString() = "RollbackTransaction" } + object RollbackTransaction : Action() { + override fun toString() = "RollbackTransaction" + } /** * Commit the current database transaction. */ - object CommitTransaction : Action() { override fun toString() = "CommitTransaction" } + object CommitTransaction : Action() { + override fun toString() = "CommitTransaction" + } /** * Execute the specified [operation]. @@ -141,7 +147,9 @@ sealed class Action { sealed class FlowRemovalReason { data class OrderlyFinish(val flowReturnValue: Any?) : FlowRemovalReason() data class ErrorFinish(val flowErrors: List) : FlowRemovalReason() - object SoftShutdown : FlowRemovalReason() { override fun toString() = "SoftShutdown" } + object SoftShutdown : FlowRemovalReason() { + override fun toString() = "SoftShutdown" + } // TODO Should we remove errored flows? How will the flow hospital work? Perhaps keep them in memory for a while, flush // them after a timeout, reload them on flow hospital request. In any case if we ever want to remove them // (e.g. temporarily) then add a case for that here. diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt index 14d52a126b..03c488e291 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt @@ -134,8 +134,7 @@ class ActionExecutorImpl( @Suspendable private fun executePropagateErrors(action: Action.PropagateErrors) { - action.errorMessages.forEach { error -> - val exception = error.flowException + action.errorMessages.forEach { (exception) -> log.debug("Propagating error", exception) } for (sessionState in action.sessions) { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt index 55dc47cb88..c7b3800a7f 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt @@ -25,10 +25,10 @@ class CountUpDownLatch(initialValue: Int) { } override fun tryAcquireShared(arg: Int): Int { - if (arg >= 0) { - return if (state == arg) 1 else -1 + return if (arg >= 0) { + if (state == arg) 1 else -1 } else { - return if (state <= -arg) 1 else -1 + if (state <= -arg) 1 else -1 } } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt index 202d5107c1..42978d51de 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt @@ -29,7 +29,9 @@ sealed class Event { * should be idempotent in the [DoRemainingWork] event, meaning a second subsequent event shouldn't modify the state * or produce [Action]s. */ - object DoRemainingWork : Event() { override fun toString() = "DoRemainingWork" } + object DoRemainingWork : Event() { + override fun toString() = "DoRemainingWork" + } /** * Deliver a session message. @@ -60,12 +62,16 @@ sealed class Event { * Trigger a soft shutdown, removing the flow as soon as possible. This causes the flow to be removed as soon as * this event is processed. Note that on restart the flow will resume as normal. */ - object SoftShutdown : Event() { override fun toString() = "SoftShutdown" } + object SoftShutdown : Event() { + override fun toString() = "SoftShutdown" + } /** * Start error propagation on a errored flow. This may be triggered by e.g. a [FlowHospital]. */ - object StartErrorPropagation : Event() { override fun toString() = "StartErrorPropagation" } + object StartErrorPropagation : Event() { + override fun toString() = "StartErrorPropagation" + } /** * @@ -92,7 +98,9 @@ sealed class Event { * Scheduled by the flow. * */ - object LeaveSubFlow : Event() { override fun toString() = "LeaveSubFlow" } + object LeaveSubFlow : Event() { + override fun toString() = "LeaveSubFlow" + } /** * Signal a flow suspension. This causes the flow's stack and the state machine's state together with the suspending diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt index e7ab42274e..ddf3c6329d 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt @@ -154,16 +154,16 @@ class FlowLogicRefFactoryImpl(private val classloader: ClassLoader) : SingletonS } private fun parameterAssignableFrom(type: Type, value: Any): Boolean { - if (type is Class<*>) { + return if (type is Class<*>) { if (type.isPrimitive) { - return Primitives.unwrap(value.javaClass) == type + Primitives.unwrap(value.javaClass) == type } else { - return type.isAssignableFrom(value.javaClass) + type.isAssignableFrom(value.javaClass) } } else if (type is ParameterizedType) { - return parameterAssignableFrom(type.rawType, value) + parameterAssignableFrom(type.rawType, value) } else { - return false + false } } } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt index dbe56f95b3..0d517c6689 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt @@ -49,7 +49,7 @@ class FlowMessagingImpl(val serviceHub: ServiceHubInternal): FlowMessaging { companion object { val log = contextLogger() - val sessionTopic = "platform.session" + const val sessionTopic = "platform.session" } override fun start(onMessage: (ReceivedMessage, deduplicationHandler: DeduplicationHandler) -> Unit) { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt index 3b6850f5f3..7e245e43a0 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt @@ -10,7 +10,6 @@ package net.corda.node.services.statemachine -import net.corda.core.crypto.random63BitValue import net.corda.core.flows.FlowException import net.corda.core.flows.FlowInfo import net.corda.core.serialization.CordaSerializable @@ -31,7 +30,6 @@ import java.security.SecureRandom @CordaSerializable sealed class SessionMessage - @CordaSerializable data class SessionId(val toLong: Long) { companion object { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt index 03f770809c..60e0ddbcd4 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt @@ -346,7 +346,7 @@ class SingleThreadedStateMachineManager( val flowId = sessionToFlow[recipientId] if (flowId == null) { deduplicationHandler.afterDatabaseTransaction() - if (sessionMessage.payload is EndSessionMessage) { + if (sessionMessage.payload === EndSessionMessage) { logger.debug { "Got ${EndSessionMessage::class.java.simpleName} for " + "unknown session $recipientId, discarding..." @@ -569,7 +569,7 @@ class SingleThreadedStateMachineManager( private fun addAndStartFlow(id: StateMachineRunId, flow: Flow) { val checkpoint = flow.fiber.snapshot().checkpoint for (sessionId in getFlowSessionIds(checkpoint)) { - sessionToFlow.put(sessionId, id) + sessionToFlow[sessionId] = id } mutex.locked { if (stopping) { @@ -578,7 +578,7 @@ class SingleThreadedStateMachineManager( } else { incrementLiveFibers() unfinishedFibers.countUp() - flows.put(id, flow) + flows[id] = flow flow.fiber.scheduleEvent(Event.DoRemainingWork) when (checkpoint.flowState) { is FlowState.Unstarted -> { 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 446e99d536..289c22590c 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 @@ -43,6 +43,7 @@ interface StateMachineManager { * Starts the state machine manager, loading and starting the state machines in storage. */ fun start(tokenizableServices: List) + /** * Stops the state machine manager gracefully, waiting until all but [allowedUnsuspendedFiberCount] flows reach the * next checkpoint. @@ -69,6 +70,7 @@ interface StateMachineManager { */ sealed class Change { abstract val logic: FlowLogic<*> + data class Add(override val logic: FlowLogic<*>) : Change() data class Removed(override val logic: FlowLogic<*>, val result: Try<*>) : Change() } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt index 7f0911d765..27cecdbb85 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt @@ -57,5 +57,4 @@ class DumpHistoryOnErrorInterceptor(val delegate: TransitionExecutor) : Transiti return Pair(continuation, nextState) } - } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt index f5e298fed8..4f7f140673 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt @@ -6,7 +6,7 @@ import net.corda.node.services.statemachine.* import net.corda.node.services.statemachine.transitions.FlowContinuation import net.corda.node.services.statemachine.transitions.TransitionResult -class MetricInterceptor(val metrics: MetricRegistry, val delegate: TransitionExecutor): TransitionExecutor { +class MetricInterceptor(val metrics: MetricRegistry, val delegate: TransitionExecutor) : TransitionExecutor { @Suspendable override fun executeTransition(fiber: FlowFiber, previousState: StateMachineState, event: Event, transition: TransitionResult, actionExecutor: ActionExecutor): Pair { val metricActionInterceptor = MetricActionInterceptor(metrics, actionExecutor) @@ -14,7 +14,7 @@ class MetricInterceptor(val metrics: MetricRegistry, val delegate: TransitionExe } } -class MetricActionInterceptor(val metrics: MetricRegistry, val delegate: ActionExecutor): ActionExecutor { +class MetricActionInterceptor(val metrics: MetricRegistry, val delegate: ActionExecutor) : ActionExecutor { @Suspendable override fun executeAction(fiber: FlowFiber, action: Action) { val context = metrics.timer("Flows.Actions.${action.javaClass.simpleName}").time() diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt index 93ecae468a..abb95f67af 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt @@ -48,7 +48,7 @@ class DeliverSessionMessageTransition( } else { val payload = event.sessionMessage.payload // Dispatch based on what kind of message it is. - val _exhaustive = when (payload) { + when (payload) { is ConfirmSessionMessage -> confirmMessageTransition(existingSession, payload) is DataSessionMessage -> dataMessageTransition(existingSession, payload) is ErrorSessionMessage -> errorMessageTransition(existingSession, payload) diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt index d6455032f8..d848175d5a 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt @@ -260,7 +260,7 @@ class StartedFlowTransition( } else { val sessionMessage = DataSessionMessage(message) val deduplicationId = DeduplicationId.createForNormal(checkpoint, index++) - val _exhaustive = when (existingSessionState) { + when (existingSessionState) { is SessionState.Uninitiated -> { val initialMessage = createInitialSessionMessage(existingSessionState.initiatingSubFlow, sourceSessionId, message) actions.add(Action.SendInitial(existingSessionState.party, initialMessage, deduplicationId)) @@ -327,7 +327,7 @@ class StartedFlowTransition( val sessionState = checkpoint.sessions[sessionId]!! when (sessionState) { is SessionState.Initiated -> { - if (sessionState.initiatedState is InitiatedSessionState.Ended) { + if (sessionState.initiatedState === InitiatedSessionState.Ended) { UnexpectedFlowEndException( "Tried to access ended session $sessionId", cause = null, @@ -347,7 +347,7 @@ class StartedFlowTransition( val sessionState = checkpoint.sessions[sessionId]!! when (sessionState) { is SessionState.Initiated -> { - if (sessionState.initiatedState is InitiatedSessionState.Ended && + if (sessionState.initiatedState === InitiatedSessionState.Ended && sessionState.receivedMessages.isEmpty()) { UnexpectedFlowEndException( "Tried to access ended session $sessionId with empty buffer", diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt index 1cd0782bcb..fbbb28808c 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt @@ -22,6 +22,7 @@ interface Transition { val context: TransitionContext /** The state the transition is starting in. */ val startingState: StateMachineState + /** The (almost) pure transition function. The only side-effect we allow is random number generation. */ fun transition(): TransitionResult diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt index 86918a9a99..2f56e2a0ad 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt @@ -78,7 +78,5 @@ class TransitionBuilder(val context: TransitionContext, initialState: StateMachi } } - - class CannotFindSessionException(sessionId: SessionId) : IllegalStateException("Couldn't find session with id $sessionId") class UnexpectedEventInState : IllegalStateException("Unexpected event") diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt index d7be626a3e..cf965075fb 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt @@ -47,10 +47,14 @@ sealed class FlowContinuation { /** * Keep processing pending events. */ - object ProcessEvents : FlowContinuation() { override fun toString() = "ProcessEvents" } + object ProcessEvents : FlowContinuation() { + override fun toString() = "ProcessEvents" + } /** * Immediately abort the flow. Note that this does not imply an error condition. */ - object Abort : FlowContinuation() { override fun toString() = "Abort" } + object Abort : FlowContinuation() { + override fun toString() = "Abort" + } } diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt index 6b9b514101..9bd9d2974b 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt @@ -30,7 +30,7 @@ import java.util.concurrent.TimeUnit.MILLISECONDS class BFTSMaRtConfig(private val replicaAddresses: List, debug: Boolean, val exposeRaces: Boolean) : PathManager(Files.createTempDirectory("bft-smart-config")) { companion object { private val log = contextLogger() - internal val portIsClaimedFormat = "Port %s is claimed by another replica: %s" + internal const val portIsClaimedFormat = "Port %s is claimed by another replica: %s" } val clusterSize get() = replicaAddresses.size @@ -45,9 +45,9 @@ class BFTSMaRtConfig(private val replicaAddresses: List, deb } } configWriter("hosts.config") { - replicaAddresses.forEachIndexed { index, address -> + replicaAddresses.forEachIndexed { index, (host, port) -> // The documentation strongly recommends IP addresses: - println("$index ${InetAddress.getByName(address.host).hostAddress} ${address.port}") + println("$index ${InetAddress.getByName(host).hostAddress} $port") } } val systemConfig = String.format(javaClass.getResource("system.config.printf").readText(), n, maxFaultyReplicas(n), if (debug) 1 else 0, (0 until n).joinToString(",")) diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt b/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt index 86f80ba2a5..8d8834d121 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt @@ -57,8 +57,7 @@ class OutOfProcessTransactionVerifierService( metrics.register(metric("VerificationsInFlight"), Gauge { verificationHandles.size }) responseConsumer.setMessageHandler { message -> val response = VerifierApi.VerificationResponse.fromClientMessage(message) - val handle = verificationHandles.remove(response.verificationId) ?: - throw VerificationResultForUnknownTransaction(response.verificationId) + val handle = verificationHandles.remove(response.verificationId) ?: throw VerificationResultForUnknownTransaction(response.verificationId) handle.durationTimerContext.stop() val exception = response.exception if (exception == null) { diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt b/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt index 2e4c394f64..71ac6a6678 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt @@ -43,7 +43,7 @@ import javax.persistence.* @ThreadSafe class PersistentUniquenessProvider(val clock: Clock) : UniquenessProvider, SingletonSerializeAsToken() { @MappedSuperclass - open class BaseComittedState( + class BaseComittedState( @EmbeddedId val id: PersistentStateRef, diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt b/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt index c2f8720aff..74662f5633 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt @@ -82,11 +82,11 @@ class RaftUniquenessProvider( Pair(it.index, SecureHash.parse(it.value) as SecureHash)) }, - toPersistentEntity = { k: StateRef, v: Pair -> + toPersistentEntity = { k: StateRef, (first, second) -> CommittedState( PersistentStateRef(k), - v.second.toString(), - v.first) + second.toString(), + first) }, persistentEntityClass = CommittedState::class.java diff --git a/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt b/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt index 0c279bf76d..f59669e4e1 100644 --- a/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt @@ -57,7 +57,7 @@ class ContractUpgradeServiceImpl : ContractUpgradeService, SingletonSerializeAsT override fun getAuthorisedContractUpgrade(ref: StateRef) = authorisedUpgrade[ref.toString()] override fun storeAuthorisedContractUpgrade(ref: StateRef, upgradedContractClass: Class>) { - authorisedUpgrade.put(ref.toString(), upgradedContractClass.name) + authorisedUpgrade[ref.toString()] = upgradedContractClass.name } override fun removeAuthorisedContractUpgrade(ref: StateRef) { diff --git a/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt b/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt index 82128d6ded..fba33f1c0c 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt @@ -474,7 +474,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status)) } } else { - commonPredicates.put(predicateID, criteriaBuilder.equal(vaultStates.get(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status)) + commonPredicates[predicateID] = criteriaBuilder.equal(vaultStates.get(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status) } } @@ -489,7 +489,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class(VaultSchemaV1.VaultStates::contractStateClassName.name).`in`(contractStateTypes.plus(existingTypes)))) } } else { - commonPredicates.put(predicateID, criteriaBuilder.and(vaultStates.get(VaultSchemaV1.VaultStates::contractStateClassName.name).`in`(contractStateTypes))) + commonPredicates[predicateID] = criteriaBuilder.and(vaultStates.get(VaultSchemaV1.VaultStates::contractStateClassName.name).`in`(contractStateTypes)) } } @@ -511,7 +511,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class("stateRef"), entityRoot.get("stateRef")) joinPredicates.add(joinPredicate) entityRoot @@ -537,22 +537,20 @@ class HibernateQueryCriteriaParser(val contractStateType: Class, String, String?> { - val entityClassAndColumnName: Triple, String, String?> = - when (sortAttribute) { - is Sort.CommonStateAttribute -> { - Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeParent, sortAttribute.attributeChild) - } - is Sort.VaultStateAttribute -> { - Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeName, null) - } - is Sort.LinearStateAttribute -> { - Triple(VaultSchemaV1.VaultLinearStates::class.java, sortAttribute.attributeName, null) - } - is Sort.FungibleStateAttribute -> { - Triple(VaultSchemaV1.VaultFungibleStates::class.java, sortAttribute.attributeName, null) - } - else -> throw VaultQueryException("Invalid sort attribute: $sortAttribute") - } - return entityClassAndColumnName + return when (sortAttribute) { + is Sort.CommonStateAttribute -> { + Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeParent, sortAttribute.attributeChild) + } + is Sort.VaultStateAttribute -> { + Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeName, null) + } + is Sort.LinearStateAttribute -> { + Triple(VaultSchemaV1.VaultLinearStates::class.java, sortAttribute.attributeName, null) + } + is Sort.FungibleStateAttribute -> { + Triple(VaultSchemaV1.VaultFungibleStates::class.java, sortAttribute.attributeName, null) + } + else -> throw VaultQueryException("Invalid sort attribute: $sortAttribute") + } } } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt index 5a4e1f5996..0e3a9989ec 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt @@ -476,7 +476,7 @@ class NodeVaultService( } } if (stateRefs.isNotEmpty()) - statesAndRefs.addAll(servicesForResolution.loadStates(stateRefs) as Collection>) + statesAndRefs.addAll(uncheckedCast(servicesForResolution.loadStates(stateRefs))) return Vault.Page(states = statesAndRefs, statesMetadata = statesMeta, stateTypes = criteriaParser.stateTypes, totalStatesAvailable = totalStates, otherResults = otherResults) } diff --git a/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt b/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt index b06807a8f5..8e83aeebe0 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt @@ -84,9 +84,7 @@ object VaultSchemaV1 : MappedSchema(schemaFamily = VaultSchema.javaClass, versio /** X500Name of participant parties **/ @ElementCollection @CollectionTable(name = "vault_linear_states_parts", - joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")), + joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))], foreignKey = ForeignKey(name = "FK__lin_stat_parts__lin_stat")) @Column(name = "participants") var participants: MutableSet? = null, @@ -117,9 +115,7 @@ object VaultSchemaV1 : MappedSchema(schemaFamily = VaultSchema.javaClass, versio /** X500Name of participant parties **/ @ElementCollection @CollectionTable(name = "vault_fungible_states_parts", - joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")), + joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))], foreignKey = ForeignKey(name = "FK__fung_st_parts__fung_st")) @Column(name = "participants") var participants: MutableSet? = null, diff --git a/node/src/main/kotlin/net/corda/node/utilities/AddOrRemove.kt b/node/src/main/kotlin/net/corda/node/utilities/AddOrRemove.kt deleted file mode 100644 index cc2f9c8435..0000000000 --- a/node/src/main/kotlin/net/corda/node/utilities/AddOrRemove.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * R3 Proprietary and Confidential - * - * Copyright (c) 2018 R3 Limited. All rights reserved. - * - * The intellectual and technical concepts contained herein are proprietary to R3 and its suppliers and are protected by trade secret law. - * - * Distribution of this file or any portion thereof via any medium without the express permission of R3 is strictly prohibited. - */ - -package net.corda.node.utilities - -import net.corda.core.serialization.CordaSerializable - -/** - * Enum for when adding/removing something, for example adding or removing an entry in a directory. - */ -@CordaSerializable -enum class AddOrRemove { - ADD, - REMOVE -} diff --git a/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt b/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt index 5670621523..c0f011c976 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt @@ -14,7 +14,7 @@ import java.net.InetAddress import java.net.NetworkInterface object AddressUtils { - private val REACHABLE_TIMEOUT_MS = 1000 + private const val REACHABLE_TIMEOUT_MS = 1000 /** Returns the first public IP address found on any of the network interfaces, or `null` if none found. */ fun tryDetectPublicIP(): InetAddress? { diff --git a/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt b/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt index 2c66d3e99d..2c6eda742c 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt @@ -46,10 +46,10 @@ interface AffinityExecutor : Executor { * way! Make sure the executor can't possibly be waiting for the calling thread. */ fun fetchFrom(fetcher: () -> T): T { - if (isOnThread) - return fetcher() + return if (isOnThread) + fetcher() else - return CompletableFuture.supplyAsync(Supplier { fetcher() }, this).get() + CompletableFuture.supplyAsync(Supplier { fetcher() }, this).get() } /** diff --git a/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt b/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt index 0a092214dc..295d5c1461 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt @@ -33,7 +33,7 @@ abstract class AppendOnlyPersistentMapBase( private val log = contextLogger() } - abstract protected val cache: LoadingCache> + protected abstract val cache: LoadingCache> /** * Returns the value associated with the key, first loading that value from the storage if necessary. @@ -173,13 +173,9 @@ class WeightBasedAppendOnlyPersistentMap( fromPersistentEntity, toPersistentEntity, persistentEntityClass) { - override val cache = NonInvalidatingWeightBasedCache>( + override val cache = NonInvalidatingWeightBasedCache( maxWeight = maxWeight, - weigher = object : Weigher> { - override fun weigh(key: K, value: Optional): Int { - return weighingFunc(key, value) - } - }, + weigher = Weigher> { key, value -> weighingFunc(key, value) }, loadFunction = { key -> Optional.ofNullable(loadValue(key)) } ) } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt b/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt index 732089773a..fe0984c341 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt @@ -54,9 +54,9 @@ object JVMAgentRegistry { path } else { (this::class.java.classLoader as? URLClassLoader) - ?.urLs - ?.map(URL::toPath) - ?.firstOrNull { it.fileName.toString() == jarFileName } + ?.urLs + ?.map(URL::toPath) + ?.firstOrNull { it.fileName.toString() == jarFileName } } } } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt b/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt index 2db65cf5dd..ec97753696 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt @@ -15,13 +15,12 @@ import java.util.concurrent.Executors import java.util.concurrent.ThreadFactory import java.util.concurrent.atomic.AtomicInteger - /** * Utility class that allows to give threads arbitrary name prefixes when they are created * via an executor. It will use an underlying thread factory to create the actual thread * and then override the thread name with the prefix and an ever increasing number */ -class NamedThreadFactory(private val name:String, private val underlyingFactory: ThreadFactory) : ThreadFactory{ +class NamedThreadFactory(private val name: String, private val underlyingFactory: ThreadFactory) : ThreadFactory { val threadNumber = AtomicInteger(1) override fun newThread(runnable: Runnable?): Thread { val thread = underlyingFactory.newThread(runnable) diff --git a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt index 98aab89067..dbc458160e 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt @@ -15,7 +15,6 @@ import com.github.benmanes.caffeine.cache.Caffeine import com.github.benmanes.caffeine.cache.LoadingCache import com.github.benmanes.caffeine.cache.Weigher - class NonInvalidatingCache private constructor( val cache: LoadingCache ) : LoadingCache by cache { @@ -46,7 +45,6 @@ class NonInvalidatingWeightBasedCache private constructor( constructor (maxWeight: Long, weigher: Weigher, loadFunction: (K) -> V) : this(buildCache(maxWeight, weigher, loadFunction)) - private companion object { private fun buildCache(maxWeight: Long, weigher: Weigher, loadFunction: (K) -> V): LoadingCache { val builder = Caffeine.newBuilder().maximumWeight(maxWeight).weigher(weigher) diff --git a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt index b0036dac5b..7cb538bbc2 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt @@ -20,7 +20,7 @@ class NonInvalidatingUnboundCache private constructor( val cache: LoadingCache ) : LoadingCache by cache { - constructor(loadFunction: (K) -> V, removalListener: RemovalListener = RemovalListener { key, value, cause -> }, + constructor(loadFunction: (K) -> V, removalListener: RemovalListener = RemovalListener { _, _, _ -> }, keysToPreload: () -> Iterable = { emptyList() }) : this(buildCache(loadFunction, removalListener, keysToPreload)) diff --git a/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt b/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt index 9e306757b1..2d5af65291 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt @@ -69,10 +69,10 @@ data class DiffPath( object ObjectDiffer { fun diff(a: Any?, b: Any?): DiffTree? { if (a == null || b == null) { - if (a == b) { - return null + return if (a == b) { + null } else { - return DiffTree.Last(a, b) + DiffTree.Last(a, b) } } if (a != b) { @@ -82,34 +82,36 @@ object ObjectDiffer { // TODO deduplicate this code if (a is Map<*, *> && b is Map<*, *>) { val allKeys = a.keys + b.keys - val branches = allKeys.mapNotNull { key -> diff(a.get(key), b.get(key))?.let { key.toString() to it } } - if (branches.isEmpty()) { - return null + val branches = allKeys.mapNotNull { key -> diff(a[key], b[key])?.let { key.toString() to it } } + return if (branches.isEmpty()) { + null } else { - return DiffTree.Step(branches) + DiffTree.Step(branches) } } + // Apparently this is not always caught by the above as one might think. + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") if (a is java.util.Map<*, *> && b is java.util.Map<*, *>) { val allKeys = a.keySet() + b.keySet() val branches = allKeys.mapNotNull { key -> diff(a.get(key), b.get(key))?.let { key.toString() to it } } - if (branches.isEmpty()) { - return null + return if (branches.isEmpty()) { + null } else { - return DiffTree.Step(branches) + DiffTree.Step(branches) } } val aFields = getFieldFoci(a) val bFields = getFieldFoci(b) try { - if (aFields != bFields) { - return DiffTree.Last(a, b) + return if (aFields != bFields) { + DiffTree.Last(a, b) } else { // TODO need to account for cases where the fields don't match up (different subclasses) - val branches = aFields.map { field -> diff(field.get(a), field.get(b))?.let { field.name to it } }.filterNotNull() + val branches = aFields.mapNotNull { field -> diff(field.get(a), field.get(b))?.let { field.name to it } } if (branches.isEmpty()) { - return DiffTree.Last(a, b) + DiffTree.Last(a, b) } else { - return DiffTree.Step(branches) + DiffTree.Step(branches) } } } catch (throwable: Exception) { @@ -151,4 +153,4 @@ object ObjectDiffer { } return foci } -} +} \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt b/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt index 5f5c82c927..6637936b49 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt @@ -64,6 +64,7 @@ class HTTPNetworkRegistrationService(compatibilityZoneURL: URL) : NetworkRegistr } } -val HttpURLConnection.cacheControl: CacheControl get() { - return CacheControl.parse(Headers.of(headerFields.filterKeys { it != null }.mapValues { it.value[0] })) -} +val HttpURLConnection.cacheControl: CacheControl + get() { + return CacheControl.parse(Headers.of(headerFields.filterKeys { it != null }.mapValues { it.value[0] })) + } diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index 54de3b66ef..37af37b526 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -24,7 +24,11 @@ import net.corda.core.flows.FlowLogic import net.corda.core.flows.StartableByRPC import net.corda.core.flows.StateMachineRunId import net.corda.core.identity.Party -import net.corda.core.messaging.* +import net.corda.core.messaging.CordaRPCOps +import net.corda.core.messaging.StateMachineUpdate +import net.corda.core.messaging.startFlow +import net.corda.core.messaging.vaultQueryBy +import net.corda.core.messaging.vaultTrackBy import net.corda.core.node.services.Vault import net.corda.core.node.services.queryBy import net.corda.core.transactions.SignedTransaction @@ -49,7 +53,6 @@ import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.expect import net.corda.testing.core.expectEvents import net.corda.testing.core.sequence -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNetwork.MockNode import net.corda.testing.node.internal.InternalMockNodeParameters @@ -79,7 +82,7 @@ private fun buildSubject(principal: String, permissionStrings: Set) = class CordaRPCOpsImplTest { private companion object { - val testJar = "net/corda/node/testing/test.jar" + const val testJar = "net/corda/node/testing/test.jar" } private lateinit var mockNet: InternalMockNetwork diff --git a/node/src/test/kotlin/net/corda/node/services/config/NodeConfigurationImplTest.kt b/node/src/test/kotlin/net/corda/node/services/config/NodeConfigurationImplTest.kt index 115f91f74c..320591dcbf 100644 --- a/node/src/test/kotlin/net/corda/node/services/config/NodeConfigurationImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/config/NodeConfigurationImplTest.kt @@ -10,9 +10,9 @@ package net.corda.node.services.config -import com.zaxxer.hikari.HikariConfig import com.typesafe.config.Config import com.typesafe.config.ConfigFactory +import com.zaxxer.hikari.HikariConfig import net.corda.core.internal.div import net.corda.core.internal.toPath import net.corda.core.utilities.NetworkHostAndPort diff --git a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt index 84682618c7..f787aad067 100644 --- a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt @@ -118,7 +118,7 @@ class MockScheduledFlowRepository : ScheduledFlowRepository { if (map.containsKey(value.ref)) { result = true } - map.put(value.ref, value) + map[value.ref] = value return result } diff --git a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt index 4174c8424c..dee2a22cd4 100644 --- a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt @@ -54,7 +54,7 @@ class NetworkMapCacheTest { } @Test - fun `getNodeByLegalIdentity`() { + fun getNodeByLegalIdentity() { val aliceNode = mockNet.createPartyNode(ALICE_NAME) val alice = aliceNode.info.singleIdentity() val bobNode = mockNet.createPartyNode(BOB_NAME) @@ -68,7 +68,7 @@ class NetworkMapCacheTest { } @Test - fun `getPeerByLegalName`() { + fun getPeerByLegalName() { val aliceNode = mockNet.createPartyNode(ALICE_NAME) val bobNode = mockNet.createPartyNode(BOB_NAME) val bobCache: NetworkMapCache = bobNode.services.networkMapCache diff --git a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt index c35cb1a44f..70178a917c 100644 --- a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt @@ -12,13 +12,13 @@ package net.corda.node.services.network import net.corda.core.crypto.Crypto import net.corda.core.crypto.sha256 -import net.corda.core.internal.* +import net.corda.core.internal.sign import net.corda.core.serialization.serialize import net.corda.core.utilities.seconds +import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.SerializationEnvironmentRule -import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.driver.PortAllocation import net.corda.testing.internal.DEV_ROOT_CA import net.corda.testing.internal.TestNodeInfoBuilder @@ -35,7 +35,6 @@ import java.io.IOException import java.net.URL import java.time.Instant import java.time.temporal.ChronoUnit -import java.util.* import kotlin.test.assertEquals class NetworkMapClientTest { diff --git a/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt b/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt index de4d5e827c..f402c4e35a 100644 --- a/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt @@ -30,6 +30,7 @@ import org.junit.Before import org.junit.Rule import org.junit.Test import java.net.URL +import java.nio.file.FileSystem import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -38,7 +39,7 @@ class NetworkParametersReaderTest { @JvmField val testSerialization = SerializationEnvironmentRule(true) - val fs = Jimfs.newFileSystem(Configuration.unix()) + val fs: FileSystem = Jimfs.newFileSystem(Configuration.unix()) private val cacheTimeout = 100000.seconds private lateinit var server: NetworkMapServer diff --git a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt index ea8f90ee23..32aec1ba32 100644 --- a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt @@ -166,7 +166,7 @@ class FlowFrameworkTests { bobNode.registerFlowFactory(WaitForOtherSideEndBeforeSendAndReceive::class) { NoOpFlow() } val sessionEndReceived = Semaphore(0) receivedSessionMessagesObservable().filter { - it.message is ExistingSessionMessage && it.message.payload is EndSessionMessage + it.message is ExistingSessionMessage && it.message.payload === EndSessionMessage }.subscribe { sessionEndReceived.release() } val resultFuture = aliceNode.services.startFlow( WaitForOtherSideEndBeforeSendAndReceive(bob, sessionEndReceived)).resultFuture diff --git a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt index 311e66116e..80d30268b8 100644 --- a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt @@ -16,7 +16,6 @@ import net.corda.core.flows.SchedulableFlow import org.junit.Test import java.time.Duration import kotlin.reflect.jvm.jvmName -import kotlin.test.assertEquals class FlowLogicRefFactoryImplTest { diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt index 4b0714e9c1..2890420db3 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt @@ -27,7 +27,8 @@ import org.junit.rules.ExpectedException class VaultQueryExceptionsTests : VaultQueryParties by rule { companion object { - @ClassRule @JvmField + @ClassRule + @JvmField val rule = object : VaultQueryTestRule() { override val cordappPackages = listOf( "net.corda.testing.contracts", diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt index 053eaef2f4..582c2d86bf 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt @@ -2209,7 +2209,7 @@ abstract class VaultQueryTestsBase : VaultQueryParties { } @Test - fun `unconsumedCashStatesForSpending_single_issuer_reference`() { + fun unconsumedCashStatesForSpending_single_issuer_reference() { database.transaction { vaultFiller.fillWithSomeTestCash(1000.DOLLARS, notaryServices, 1, DUMMY_CASH_ISSUER) this.session.flush() diff --git a/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt b/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt index 13f979bfea..dc0f26fbe2 100644 --- a/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt +++ b/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt @@ -18,8 +18,8 @@ import java.util.concurrent.atomic.AtomicReference import kotlin.test.* class AffinityExecutorTests { - var _executor: AffinityExecutor.ServiceAffinityExecutor? = null - val executor: AffinityExecutor.ServiceAffinityExecutor get() = _executor!! + private var _executor: AffinityExecutor.ServiceAffinityExecutor? = null + private val executor: AffinityExecutor.ServiceAffinityExecutor get() = _executor!! @After fun shutdown() { diff --git a/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt b/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt index 7745f1a63b..c5add42c8a 100644 --- a/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt +++ b/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt @@ -35,7 +35,7 @@ class PersistentMapTests { database.transaction { val map = createTestMap() - map.put(testHash, "test") + map[testHash] = "test" assertEquals(map[testHash], "test") } @@ -67,9 +67,9 @@ class PersistentMapTests { database.transaction { val map = createTestMap() - map.put(testHash, "test") + map[testHash] = "test" - map.put(testHash, "updated") + map[testHash] = "updated" assertEquals("updated", map[testHash]) } @@ -129,7 +129,7 @@ class PersistentMapTests { database.transaction { val map = createTestMap() - map.put(testHash, "test") + map[testHash] = "test" assertEquals(map[testHash], "test") } diff --git a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt index 323fed32eb..080619edd3 100644 --- a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt +++ b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt @@ -193,7 +193,7 @@ private fun printHelp(parser: OptionParser) { parser.printHelpOn(System.out) } -val ATTACHMENT_PROGRAM_ID = "net.corda.attachmentdemo.AttachmentContract" +const val ATTACHMENT_PROGRAM_ID = "net.corda.attachmentdemo.AttachmentContract" class AttachmentContract : Contract { override fun verify(tx: LedgerTransaction) { diff --git a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt index 9b18acb731..882dd184cc 100644 --- a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt +++ b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt @@ -48,8 +48,7 @@ object BankOfCordaClientApi { // Resolve parties via RPC val issueToParty = rpc.wellKnownPartyFromX500Name(params.issueToPartyName) ?: throw IllegalStateException("Unable to locate ${params.issueToPartyName} in Network Map Service") - val notaryLegalIdentity = rpc.notaryIdentities().firstOrNull { it.name == params.notaryName } ?: - throw IllegalStateException("Couldn't locate notary ${params.notaryName} in NetworkMapCache") + val notaryLegalIdentity = rpc.notaryIdentities().firstOrNull { it.name == params.notaryName } ?: throw IllegalStateException("Couldn't locate notary ${params.notaryName} in NetworkMapCache") val anonymous = true val issuerBankPartyRef = OpaqueBytes.of(params.issuerBankPartyRef.toByte()) diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt index 65e92c6883..76f1e582d4 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt @@ -244,7 +244,7 @@ object NodeInterestRates { fun getRate(tenor: Tenor): BigDecimal? { return rates.getOrElse(tenor) { val rate = interpolate(tenor) - if (rate != null) rates.put(tenor, rate) + if (rate != null) rates[tenor] = rate return rate } } diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt index 766b377d58..c53818c632 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt @@ -11,15 +11,40 @@ package net.corda.irs.contract import com.fasterxml.jackson.annotation.JsonIgnoreProperties -import net.corda.core.contracts.* +import net.corda.core.contracts.Amount +import net.corda.core.contracts.Command +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.CommandWithParties +import net.corda.core.contracts.Contract +import net.corda.core.contracts.SchedulableState +import net.corda.core.contracts.ScheduledActivity +import net.corda.core.contracts.StateAndContract +import net.corda.core.contracts.StateAndRef +import net.corda.core.contracts.StateRef +import net.corda.core.contracts.TransactionState +import net.corda.core.contracts.TypeOnlyCommandData +import net.corda.core.contracts.UniqueIdentifier +import net.corda.core.contracts.requireThat +import net.corda.core.contracts.select import net.corda.core.flows.FlowLogicRefFactory import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party import net.corda.core.serialization.CordaSerializable import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder -import net.corda.finance.contracts.* -import net.corda.irs.flows.FixingFlow +import net.corda.finance.contracts.AccrualAdjustment +import net.corda.finance.contracts.BusinessCalendar +import net.corda.finance.contracts.DateRollConvention +import net.corda.finance.contracts.DateRollDirection +import net.corda.finance.contracts.DayCountBasisDay +import net.corda.finance.contracts.DayCountBasisYear +import net.corda.finance.contracts.Expression +import net.corda.finance.contracts.Fix +import net.corda.finance.contracts.FixOf +import net.corda.finance.contracts.FixableDealState +import net.corda.finance.contracts.Frequency +import net.corda.finance.contracts.PaymentRule +import net.corda.finance.contracts.Tenor import net.corda.irs.utilities.suggestInterestRateAnnouncementTimeWindow import org.apache.commons.jexl3.JexlBuilder import org.apache.commons.jexl3.MapContext @@ -75,7 +100,7 @@ abstract class RatePaymentEvent(date: LocalDate, val notional: Amount, val rate: Rate) : PaymentEvent(date) { companion object { - val CSVHeader = "AccrualStartDate,AccrualEndDate,DayCountFactor,Days,Date,Ccy,Notional,Rate,Flow" + const val CSVHeader = "AccrualStartDate,AccrualEndDate,DayCountFactor,Days,Date,Ccy,Notional,Rate,Flow" } override fun calculate(): Amount = flow @@ -499,7 +524,7 @@ class InterestRateSwap : Contract { } private fun verifyAgreeCommand(inputs: List, outputs: List) { - val irs = outputs.filterIsInstance().single() + val irs = outputs.single() requireThat { "There are no in states for an agreement" using inputs.isEmpty() "There are events in the fix schedule" using (irs.calculation.fixedLegPaymentSchedule.isNotEmpty()) @@ -521,8 +546,8 @@ class InterestRateSwap : Contract { } private fun verifyFixCommand(inputs: List, outputs: List, command: CommandWithParties) { - val irs = outputs.filterIsInstance().single() - val prevIrs = inputs.filterIsInstance().single() + val irs = outputs.single() + val prevIrs = inputs.single() val paymentDifferences = getFloatingLegPaymentsDifferences(prevIrs.calculation.floatingLegPaymentSchedule, irs.calculation.floatingLegPaymentSchedule) // Having both of these tests are "redundant" as far as verify() goes, however, by performing both @@ -560,7 +585,7 @@ class InterestRateSwap : Contract { } private fun verifyMatureCommand(inputs: List, outputs: List) { - val irs = inputs.filterIsInstance().single() + val irs = inputs.single() requireThat { "No more fixings to be applied" using (irs.calculation.nextFixingDate() == null) "The irs is fully consumed and there is no id matched output state" using outputs.isEmpty() diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt index 9c160ee660..6d98bb1594 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt @@ -12,6 +12,6 @@ package net.corda.irs.contract fun InterestRateSwap.State.exportIRSToCSV(): String = "Fixed Leg\n" + FixedRatePaymentEvent.CSVHeader + "\n" + - this.calculation.fixedLegPaymentSchedule.toSortedMap().values.map { it.asCSV() }.joinToString("\n") + "\n" + + this.calculation.fixedLegPaymentSchedule.toSortedMap().values.joinToString("\n") { it.asCSV() } + "\n" + "Floating Leg\n" + FloatingRatePaymentEvent.CSVHeader + "\n" + - this.calculation.floatingLegPaymentSchedule.toSortedMap().values.map { it.asCSV() }.joinToString("\n") + "\n" + this.calculation.floatingLegPaymentSchedule.toSortedMap().values.joinToString("\n") { it.asCSV() } + "\n" diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt index aa69d9e40a..771bdf524c 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt @@ -18,7 +18,6 @@ import net.corda.finance.contracts.Tenor import java.math.BigDecimal import java.util.* - // Things in here will move to the general utils class when we've hammered out various discussions regarding amounts, dates, oracle etc. /** diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt index 9a717c00e6..76f4a0ce60 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt @@ -85,7 +85,6 @@ object AutoOfferFlow { subFlow(ReportToRegulatorFlow(regulator, finalTx)) return finalTx } - } @InitiatingFlow diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt index 5bb093319f..f7ce26dc94 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt @@ -79,8 +79,8 @@ object FixingFlow { @Suspendable override fun filtering(elem: Any): Boolean { return when (elem) { - // Only expose Fix commands in which the oracle is on the list of requested signers - // to the oracle node, to avoid leaking privacy + // Only expose Fix commands in which the oracle is on the list of requested signers + // to the oracle node, to avoid leaking privacy is Command<*> -> handshake.payload.oracle.owningKey in elem.signers && elem.value is Fix else -> false } @@ -109,12 +109,12 @@ object FixingFlow { override val notaryParty: Party get() = dealToFix.state.notary - @Suspendable override fun checkProposal(stx: SignedTransaction) = requireThat { + @Suspendable + override fun checkProposal(stx: SignedTransaction) = requireThat { // Add some constraints here. } } - /** Used to set up the session between [Floater] and [Fixer] */ @CordaSerializable data class FixingSession(val ref: StateRef, val oracle: Party) diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt index 4c27556e87..e77a092913 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt @@ -1,6 +1,5 @@ package net.corda.irs.api -import com.google.common.collect.testing.Helpers import com.google.common.collect.testing.Helpers.assertContains import net.corda.core.contracts.Command import net.corda.core.contracts.TransactionState @@ -16,7 +15,11 @@ import net.corda.finance.contracts.FixOf import net.corda.finance.contracts.asset.CASH import net.corda.finance.contracts.asset.Cash import net.corda.irs.flows.RatesFixFlow -import net.corda.testing.core.* +import net.corda.testing.core.ALICE_NAME +import net.corda.testing.core.BOB_NAME +import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.core.TestIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.LogHelper import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNodeParameters diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt index 83279e605a..e1127eb841 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt @@ -272,7 +272,7 @@ class IRSTests { */ private fun generateIRSTxn(irsSelect: Int): SignedTransaction { val dummyIRS = createDummyIRS(irsSelect) - val genTX: SignedTransaction = run { + return run { val gtx = InterestRateSwap().generateAgreement( fixedLeg = dummyIRS.fixedLeg, floatingLeg = dummyIRS.floatingLeg, @@ -286,7 +286,6 @@ class IRSTests { val ptx2 = miniCorpServices.addSignature(ptx1) notaryServices.addSignature(ptx2) } - return genTX } /** diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt index 100972e716..2998e8b829 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt @@ -52,7 +52,7 @@ object UpdateBusinessDayFlow { } @Suspendable - override fun call(): Unit { + override fun call() { progressTracker.currentStep = NOTIFYING for (recipient in getRecipients()) { doNextRecipient(recipient) diff --git a/samples/irs-demo/src/system-test/kotlin/IRSDemoDockerTest.kt b/samples/irs-demo/src/system-test/kotlin/net/corda/irs/IRSDemoDockerTest.kt similarity index 87% rename from samples/irs-demo/src/system-test/kotlin/IRSDemoDockerTest.kt rename to samples/irs-demo/src/system-test/kotlin/net/corda/irs/IRSDemoDockerTest.kt index 93a42c4cb0..e766422ae3 100644 --- a/samples/irs-demo/src/system-test/kotlin/IRSDemoDockerTest.kt +++ b/samples/irs-demo/src/system-test/kotlin/net/corda/irs/IRSDemoDockerTest.kt @@ -11,18 +11,15 @@ package net.corda.irs import com.palantir.docker.compose.DockerComposeRule +import com.palantir.docker.compose.ImmutableDockerComposeRule import com.palantir.docker.compose.configuration.DockerComposeFiles import com.palantir.docker.compose.connection.waiting.HealthChecks import org.junit.ClassRule import org.junit.Test import org.openqa.selenium.By -import org.openqa.selenium.OutputType import org.openqa.selenium.WebElement import org.openqa.selenium.phantomjs.PhantomJSDriver import org.openqa.selenium.support.ui.WebDriverWait -import java.nio.file.Files -import java.nio.file.Paths -import java.nio.file.StandardCopyOption import kotlin.test.assertNotNull import kotlin.test.assertTrue @@ -43,26 +40,22 @@ class IRSDemoDockerTest { @ClassRule @JvmField - var docker = DockerComposeRule.builder() + var docker: ImmutableDockerComposeRule = DockerComposeRule.builder() .files(DockerComposeFiles.from( System.getProperty("CORDAPP_DOCKER_COMPOSE"), System.getProperty("WEB_DOCKER_COMPOSE"))) - .waitingForService("web-a", HealthChecks.toRespondOverHttp(8080, { port -> port.inFormat("http://\$HOST:\$EXTERNAL_PORT") })) + .waitingForService("web-a", HealthChecks.toRespondOverHttp(8080, { port -> port.inFormat("http://\$HOST:\$EXTERNAL_PORT") })) .build() } @Test fun `runs IRS demo selenium phantomjs`() { - val driver = PhantomJSDriver() - val webAPort = docker.containers() - .container("web-a") - .port(8080) + val webAPort = docker.containers().container("web-a").port(8080) - - driver.get("http://${webAPort.ip}:${webAPort.externalPort}"); + driver.get("http://${webAPort.ip}:${webAPort.externalPort}") //no deals on fresh interface val dealRows = driver.findElementsByCssSelector("table#deal-list tbody tr") diff --git a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt index c09e6d12c9..4d39f103c0 100644 --- a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt +++ b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt @@ -33,19 +33,19 @@ import org.springframework.context.annotation.Bean @SpringBootApplication class IrsDemoWebApplication { @Value("\${corda.host}") - lateinit var cordaHost:String + lateinit var cordaHost: String @Value("\${corda.user}") - lateinit var cordaUser:String + lateinit var cordaUser: String @Value("\${corda.password}") - lateinit var cordaPassword:String + lateinit var cordaPassword: String @Bean fun rpcClient(): CordaRPCOps { log.info("Connecting to Corda on $cordaHost using username $cordaUser and password $cordaPassword") // TODO remove this when CordaRPC gets proper connection retry, please - var maxRetries = 100; + var maxRetries = 100 do { try { return CordaRPCClient(NetworkHostAndPort.parse(cordaHost)).start(cordaUser, cordaPassword).proxy @@ -70,7 +70,8 @@ class IrsDemoWebApplication { companion object { private val log = LoggerFactory.getLogger(this::class.java) - @JvmStatic fun main(args: Array) { + @JvmStatic + fun main(args: Array) { SpringApplication.run(IrsDemoWebApplication::class.java, *args) } } diff --git a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt index 6a8ed8694b..4496794bc7 100644 --- a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt +++ b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt @@ -58,15 +58,13 @@ class InterestRateSwapAPI { } } - @Autowired lateinit var rpc: CordaRPCOps private fun getAllDeals(): Array { val vault = rpc.vaultQueryBy().states val states = vault.filterStatesOfType() - val swaps = states.map { it.state.data }.toTypedArray() - return swaps + return states.map { it.state.data }.toTypedArray() } @GetMapping("/deals") diff --git a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt index 9bd2938d73..ad51b61a32 100644 --- a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt +++ b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt @@ -18,12 +18,12 @@ import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) -@SpringBootTest(properties = arrayOf("corda.host=localhost:12345", "corda.user=user", "corda.password=password", "liquibase.enabled=false")) +@SpringBootTest(properties = ["corda.host=localhost:12345", "corda.user=user", "corda.password=password", "liquibase.enabled=false"]) class IrsDemoWebApplicationTests { - @MockBean - lateinit var rpc: CordaRPCOps + @MockBean + lateinit var rpc: CordaRPCOps - @Test - fun contextLoads() { - } + @Test + fun contextLoads() { + } } diff --git a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt index 21a815ff01..8b68ba4454 100644 --- a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt +++ b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt @@ -39,6 +39,6 @@ class IRSDemoClientApi(hostAndPort: NetworkHostAndPort) { } private companion object { - private val apiRoot = "api/irs" + private const val apiRoot = "api/irs" } } diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt index 452c44647a..83be14b1d2 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt @@ -21,7 +21,6 @@ import net.corda.node.internal.StartedNode import net.corda.node.services.statemachine.StateMachineManager import net.corda.testing.core.TestIdentity import net.corda.testing.node.InMemoryMessagingNetwork -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import net.corda.testing.node.TestClock import net.corda.testing.node.internal.InternalMockNetwork @@ -198,7 +197,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, } } - val networkInitialisationFinished = allOf(*mockNet.nodes.map { it.nodeReadyFuture.toCompletableFuture() }.toTypedArray()) + val networkInitialisationFinished: CompletableFuture = allOf(*mockNet.nodes.map { it.nodeReadyFuture.toCompletableFuture() }.toTypedArray()) fun start(): Future { mockNet.startNodes() diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt index 2902afdf1f..6dccbd72aa 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt @@ -26,7 +26,7 @@ import java.nio.file.Paths fun main(args: Array) = BFTNotaryCordform().nodeRunner().deployAndRunNodes() -private val clusterSize = 4 // Minimum size that tolerates a faulty replica. +private const val clusterSize = 4 // Minimum size that tolerates a faulty replica. private val notaryNames = createNotaryNames(clusterSize) // This is not the intended final design for how to use CordformDefinition, please treat this as experimental and DO diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt index 8e4b2fc8b0..1f15a1ec31 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt @@ -57,7 +57,7 @@ class RaftNotaryCordform : CordformDefinition() { } fun notaryNode(index: Int, nodePort: Int, clusterPort: Int? = null, configure: CordformNode.() -> Unit) = node { name(notaryNames[index]) - val clusterAddresses = if (clusterPort != null ) listOf(NetworkHostAndPort("localhost", clusterPort)) else emptyList() + val clusterAddresses = if (clusterPort != null) listOf(NetworkHostAndPort("localhost", clusterPort)) else emptyList() notary(NotaryConfig(validating = true, raft = RaftConfig(NetworkHostAndPort("localhost", nodePort), clusterAddresses))) configure() devMode(true) 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 f3048c5bb2..4c59b03618 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 @@ -25,7 +25,7 @@ import net.corda.core.transactions.TransactionBuilder @StartableByRPC class DummyIssueAndMove(private val notary: Party, private val counterpartyNode: Party, private val discriminator: Int) : FlowLogic() { companion object { - private val DO_NOTHING_PROGRAM_ID = "net.corda.notarydemo.flows.DummyIssueAndMove\$DoNothingContract" + private const val DO_NOTHING_PROGRAM_ID = "net.corda.notarydemo.flows.DummyIssueAndMove\$DoNothingContract" } class DoNothingContract : Contract { diff --git a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt index f7909608e8..b188e3702f 100644 --- a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt +++ b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt @@ -21,7 +21,7 @@ import java.time.LocalDate import java.time.ZoneOffset import java.time.temporal.ChronoUnit -val PORTFOLIO_SWAP_PROGRAM_ID = "net.corda.vega.contracts.PortfolioSwap" +const val PORTFOLIO_SWAP_PROGRAM_ID = "net.corda.vega.contracts.PortfolioSwap" /** * Represents an aggregate set of trades agreed between two parties and a possible valuation of that portfolio at a diff --git a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt index b099571a67..88d69418c3 100644 --- a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt +++ b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt @@ -39,7 +39,6 @@ data class PortfolioSwap(private val blank: Void? = null) : Contract { "the valuer hasn't changed" using (inputs[0].valuer == outputs[0].valuer) "the linear id hasn't changed" using (inputs[0].linearId == outputs[0].linearId) } - } } } diff --git a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java index e1b1ce88c6..389650e331 100644 --- a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java +++ b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java @@ -135,7 +135,7 @@ public abstract class ExampleMarketDataBuilder { } if (url.getProtocol() != null && "jar".equals(url.getProtocol().toLowerCase(Locale.ENGLISH))) { // Inside a JAR - int classSeparatorIdx = url.getFile().indexOf("!"); + int classSeparatorIdx = url.getFile().indexOf('!'); if (classSeparatorIdx == -1) { throw new IllegalArgumentException(Messages.format("Unexpected JAR file URL: {}", url)); } @@ -344,9 +344,9 @@ public abstract class ExampleMarketDataBuilder { CharSource inputSource = cdsYieldCurvesResource.getCharSource(); Map yieldCuves = MarkitYieldCurveDataParser.parse(inputSource); - for (IsdaYieldCurveInputsId id : yieldCuves.keySet()) { - IsdaYieldCurveInputs curveInputs = yieldCuves.get(id); - builder.addValue(id, curveInputs); + for (Map.Entry isdaYieldCurveInputsIdIsdaYieldCurveInputsEntry : yieldCuves.entrySet()) { + IsdaYieldCurveInputs curveInputs = isdaYieldCurveInputsIdIsdaYieldCurveInputsEntry.getValue(); + builder.addValue(isdaYieldCurveInputsIdIsdaYieldCurveInputsEntry.getKey(), curveInputs); } } diff --git a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java index 5a77b17dbb..7a69bb0c1e 100644 --- a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java +++ b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java @@ -124,16 +124,12 @@ public class MarkitIndexCreditCurveDataParser { spread = parseRate(compositeSpreadText); } - List points = curveData.get(id); - if (points == null) { - points = Lists.newArrayList(); - curveData.put(id, points); - } + List points = curveData.computeIfAbsent(id, k -> Lists.newArrayList()); points.add(new Point(term, maturity, spread)); } - for (IsdaIndexCreditCurveInputsId curveId : curveData.keySet()) { - MarkitRedCode redCode = MarkitRedCode.from(curveId.getReferenceInformation().getIndexId()); + for (Map.Entry> isdaIndexCreditCurveInputsIdListEntry : curveData.entrySet()) { + MarkitRedCode redCode = MarkitRedCode.from((isdaIndexCreditCurveInputsIdListEntry.getKey()).getReferenceInformation().getIndexId()); StaticData staticData = staticDataMap.get(redCode); ArgChecker.notNull(staticData, "Did not find a static data record for " + redCode); CdsConvention convention = staticData.getConvention(); @@ -141,9 +137,9 @@ public class MarkitIndexCreditCurveDataParser { double indexFactor = staticData.getIndexFactor(); // TODO add fromDate handling - String creditCurveName = curveId.toString(); + String creditCurveName = (isdaIndexCreditCurveInputsIdListEntry.getKey()).toString(); - List points = curveData.get(curveId); + List points = isdaIndexCreditCurveInputsIdListEntry.getValue(); Period[] periods = points.stream().map(s -> s.getTenor().getPeriod()).toArray(Period[]::new); LocalDate[] endDates = points.stream().map(s -> s.getDate()).toArray(LocalDate[]::new); @@ -157,9 +153,9 @@ public class MarkitIndexCreditCurveDataParser { convention, indexFactor); - builder.addValue(curveId, curveInputs); + builder.addValue(isdaIndexCreditCurveInputsIdListEntry.getKey(), curveInputs); - IsdaIndexRecoveryRateId recoveryRateId = IsdaIndexRecoveryRateId.of(curveId.getReferenceInformation()); + IsdaIndexRecoveryRateId recoveryRateId = IsdaIndexRecoveryRateId.of((isdaIndexCreditCurveInputsIdListEntry.getKey()).getReferenceInformation()); CdsRecoveryRate cdsRecoveryRate = CdsRecoveryRate.of(recoveryRate); builder.addValue(recoveryRateId, cdsRecoveryRate); diff --git a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java index e99ea6c941..0dcedacea3 100644 --- a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java +++ b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java @@ -65,26 +65,22 @@ public class MarkitYieldCurveDataParser { Double.parseDouble(rateText)); IsdaYieldCurveConvention convention = IsdaYieldCurveConvention.of(conventionText); - List points = curveData.get(convention); - if (points == null) { - points = Lists.newArrayList(); - curveData.put(convention, points); - } + List points = curveData.computeIfAbsent(convention, k -> Lists.newArrayList()); points.add(point); } // convert the curve data into the result map Map result = Maps.newHashMap(); - for (IsdaYieldCurveConvention convention : curveData.keySet()) { - List points = curveData.get(convention); - result.put(IsdaYieldCurveInputsId.of(convention.getCurrency()), + for (Map.Entry> isdaYieldCurveConventionListEntry : curveData.entrySet()) { + List points = isdaYieldCurveConventionListEntry.getValue(); + result.put(IsdaYieldCurveInputsId.of((isdaYieldCurveConventionListEntry.getKey()).getCurrency()), IsdaYieldCurveInputs.of( - CurveName.of(convention.getName()), + CurveName.of((isdaYieldCurveConventionListEntry.getKey()).getName()), points.stream().map(s -> s.getTenor().getPeriod()).toArray(Period[]::new), points.stream().map(s -> s.getDate()).toArray(LocalDate[]::new), points.stream().map(s -> s.getInstrumentType()).toArray(IsdaYieldCurveUnderlyingType[]::new), points.stream().mapToDouble(s -> s.getRate()).toArray(), - convention)); + isdaYieldCurveConventionListEntry.getKey())); } return result; } diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt index d95a21789c..19123252e4 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt @@ -46,7 +46,7 @@ object BimmAnalysisUtils { first: CurrencyParameterSensitivities, second: MultiCurrencyAmount): Triple { val amount = second.amounts.map { it.amount }.sum() - return Triple(amount, 0.0, amount) + return Triple(amount, 0.0, amount) } } diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt index 401f8dc46c..a0ab6080c7 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt @@ -202,5 +202,4 @@ class SwapPricingCcpExample { 100000000.0, // the notional amount 0.015) // the fixed interest rate } - } diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt index 0588497341..ea1d85c52e 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt @@ -48,7 +48,6 @@ object IRSTradeFlow { session, TwoPartyDealFlow.AutoOffer(notary, offer))) } - } @InitiatedBy(Requester::class) diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt index 6c8883dad6..138b6642b2 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt @@ -55,7 +55,6 @@ fun MarketData.toCordaCompatible(): CordaMarketData { return CordaMarketData(valuationDate = this.valuationDate, values = values) } - /** * A very basic modifier of InitialMarginTriple in order to ignore everything past the 2nd decimal place. */ diff --git a/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt b/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt index 4eeee5b563..33ad329d25 100644 --- a/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt +++ b/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt @@ -43,7 +43,7 @@ class SimmValuationTest : IntegrationTest() { val valuationDate: LocalDate = LocalDate.parse("2016-06-06") val nodeALegalName = DUMMY_BANK_A_NAME val nodeBLegalName = DUMMY_BANK_B_NAME - val testTradeId = "trade1" + const val testTradeId = "trade1" @ClassRule @JvmField diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt index 0b6fc3a666..a4ff7fc23b 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt @@ -56,7 +56,7 @@ class PortfolioApiUtils(private val ownParty: Party) { val yieldCurves = mapOf( "name" to "EUR", - "values" to completeSubgroups.get("EUR")!!.filter { !it.key.contains("Fixing") }.map { + "values" to completeSubgroups["EUR"]!!.filter { !it.key.contains("Fixing") }.map { mapOf( "tenor" to it.key, "rate" to it.value @@ -66,7 +66,7 @@ class PortfolioApiUtils(private val ownParty: Party) { val fixings = mapOf( "name" to "EUR", - "values" to completeSubgroups.get("EUR")!!.filter { it.key.contains("Fixing") }.map { + "values" to completeSubgroups["EUR"]!!.filter { it.key.contains("Fixing") }.map { mapOf( "tenor" to it.key, "rate" to it.value diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt index 47bacf9dd7..f8195fdad3 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt @@ -19,6 +19,6 @@ class CurrencyParameterSensitivitiesSerializer : SerializationCustomSerializer { data class Proxy(val sensitivities: List) - override fun fromProxy(proxy: Proxy) = CurrencyParameterSensitivities.of(proxy.sensitivities) + override fun fromProxy(proxy: Proxy): CurrencyParameterSensitivities = CurrencyParameterSensitivities.of(proxy.sensitivities) override fun toProxy(obj: CurrencyParameterSensitivities) = Proxy(obj.sensitivities) } \ No newline at end of file diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt index c5cad7fec9..48635f962c 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt @@ -24,13 +24,12 @@ class CurrencyParameterSensitivitySerializer : val parameterMetadata: List, val sensitivity: DoubleArray) - override fun fromProxy(proxy: CurrencyParameterSensitivitySerializer.Proxy) = + override fun fromProxy(proxy: CurrencyParameterSensitivitySerializer.Proxy): CurrencyParameterSensitivity = CurrencyParameterSensitivity.of( proxy.marketDataName, proxy.parameterMetadata, proxy.currency, proxy.sensitivity) - override fun toProxy(obj: CurrencyParameterSensitivity) = Proxy((obj as CurrencyParameterSensitivity).currency, - obj.marketDataName, obj.parameterMetadata, obj.sensitivity) + override fun toProxy(obj: CurrencyParameterSensitivity) = Proxy(obj.currency, obj.marketDataName, obj.parameterMetadata, obj.sensitivity) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt index 98ce7b6c56..d32bae9eda 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt @@ -17,6 +17,6 @@ import net.corda.core.serialization.SerializationCustomSerializer class CurrencySerializer : SerializationCustomSerializer { data class Proxy(val currency: String) - override fun fromProxy(proxy: Proxy) = Currency.parse(proxy.currency) + override fun fromProxy(proxy: Proxy): Currency = Currency.parse(proxy.currency) override fun toProxy(obj: Currency) = Proxy(obj.toString()) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt index 9771b777f5..0351421bed 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt @@ -12,11 +12,28 @@ package net.corda.vega.plugin.customserializers import net.corda.core.serialization.SerializationCustomSerializer import com.opengamma.strata.collect.array.DoubleArray +import java.util.* @Suppress("UNUSED") class DoubleArraySerializer : SerializationCustomSerializer { - data class Proxy(val amount: kotlin.DoubleArray) + data class Proxy(val amount: kotlin.DoubleArray) { - override fun fromProxy(proxy: Proxy) = DoubleArray.copyOf(proxy.amount) + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Proxy + + if (!Arrays.equals(amount, other.amount)) return false + + return true + } + + override fun hashCode(): Int { + return Arrays.hashCode(amount) + } + } + + override fun fromProxy(proxy: Proxy): DoubleArray = DoubleArray.copyOf(proxy.amount) override fun toProxy(obj: DoubleArray) = Proxy(obj.toArray()) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt index f46a476e6b..1b523270c9 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt @@ -17,10 +17,10 @@ import net.corda.core.serialization.* @Suppress("UNUSED") class MultiCurrencyAmountSerializer : SerializationCustomSerializer { - data class Proxy(val curencies : Map) + data class Proxy(val curencies: Map) override fun toProxy(obj: MultiCurrencyAmount) = Proxy(obj.toMap()) - override fun fromProxy(proxy: Proxy) = MultiCurrencyAmount.of(proxy.curencies) + override fun fromProxy(proxy: Proxy): MultiCurrencyAmount = MultiCurrencyAmount.of(proxy.curencies) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt index f774ee1aaf..447e754141 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt @@ -21,5 +21,5 @@ class TenorDateParameterMetadataSerializer : data class Proxy(val tenor: Tenor, val date: LocalDate, val identifier: Tenor, val label: String) override fun toProxy(obj: TenorDateParameterMetadata) = Proxy(obj.tenor, obj.date, obj.identifier, obj.label) - override fun fromProxy(proxy: Proxy) = TenorDateParameterMetadata.of(proxy.date, proxy.tenor, proxy.label) + override fun fromProxy(proxy: Proxy): TenorDateParameterMetadata = TenorDateParameterMetadata.of(proxy.date, proxy.tenor, proxy.label) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt index 9340201090..1574ddf93e 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt @@ -19,5 +19,5 @@ class TenorSerializer : SerializationCustomSerializer) { diff --git a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt index 08ac4da427..f458b9df70 100644 --- a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt +++ b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt @@ -72,7 +72,7 @@ class TransactionGraphSearch(private val transactions: TransactionStorage, results += tx val inputsLeadingToUnvisitedTx: Iterable = tx.inputs.filter { it.txhash !in alreadyVisited } - val unvisitedInputTxs: Map = inputsLeadingToUnvisitedTx.map { it.txhash }.toHashSet().map { transactions.getTransaction(it) }.filterNotNull().associateBy { it.id } + val unvisitedInputTxs: Map = inputsLeadingToUnvisitedTx.map { it.txhash }.toHashSet().mapNotNull { transactions.getTransaction(it) }.associateBy { it.id } val unvisitedInputTxsWithInputIndex: Iterable> = inputsLeadingToUnvisitedTx.filter { it.txhash in unvisitedInputTxs.keys }.map { Pair(unvisitedInputTxs[it.txhash]!!, it.index) } next += (unvisitedInputTxsWithInputIndex.filter { (stx, idx) -> query.followInputsOfType == null || stx.tx.outputs[idx].data.javaClass == query.followInputsOfType diff --git a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt index 3856e4dd99..6f9dfda5aa 100644 --- a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt +++ b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt @@ -70,13 +70,12 @@ class CommercialPaperIssueFlow(private val amount: Amount, } // Now make a dummy transaction that moves it to a new key, just to show that resolving dependencies works. - val move: SignedTransaction = run { + + return run { val builder = TransactionBuilder(notary) CommercialPaper().generateMove(builder, issuance.tx.outRef(0), recipient) val stx = serviceHub.signInitialTransaction(builder) subFlow(FinalityFlow(stx)) } - - return move } } diff --git a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt index 63c83179a0..5a6daae6be 100644 --- a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt +++ b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt @@ -66,8 +66,7 @@ class SideEffectFlow : FlowLogic>() { // Expected to be on stack @Suppress("UNUSED_VARIABLE") val unusedVar = Constants.IN_CALL_VALUE - val numberOfFullFrames = retrieveStackSnapshot() - return numberOfFullFrames + return retrieveStackSnapshot() } @Suspendable @@ -94,8 +93,7 @@ class NoSideEffectFlow : FlowLogic>() { // Using the [Constants] object here is considered by Quasar as a side effect. Thus explicit initialization @Suppress("UNUSED_VARIABLE") val unusedVar = "inCall" - val numberOfFullFrames = retrieveStackSnapshot() - return numberOfFullFrames + return retrieveStackSnapshot() } @Suspendable @@ -109,11 +107,11 @@ class NoSideEffectFlow : FlowLogic>() { } object Constants { - val IN_PERSIST_VALUE = "inPersist" - val IN_CALL_VALUE = "inCall" - val IN_RETRIEVE_STACK_SNAPSHOT_VALUE = "inRetrieveStackSnapshot" - val USER = "User" - val PASSWORD = "Password" + const val IN_PERSIST_VALUE = "inPersist" + const val IN_CALL_VALUE = "inCall" + const val IN_RETRIEVE_STACK_SNAPSHOT_VALUE = "inRetrieveStackSnapshot" + const val USER = "User" + const val PASSWORD = "Password" } @@ -196,7 +194,7 @@ class FlowStackSnapshotSerializationTestingFlow : FlowLogic() { @Suspendable override fun call() { - val flowStackSnapshot = flowStackSnapshot() + flowStackSnapshot() val mySession = initiateFlow(ourIdentity) mySession.sendAndReceive("Ping") } diff --git a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt index a4c4d2d326..c893999040 100644 --- a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt +++ b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt @@ -12,7 +12,6 @@ package net.corda.testing.node import net.corda.core.internal.div import net.corda.testing.common.internal.ProjectStructure.projectRootDir -import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.ProcessUtilities.startJavaProcess import org.junit.Test import kotlin.test.assertEquals diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt index 3cd9b47c6d..0953f0e329 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt @@ -12,7 +12,6 @@ package net.corda.testing.driver -import net.corda.core.CordaInternal import net.corda.core.DoNotImplement import net.corda.core.concurrent.CordaFuture import net.corda.core.flows.FlowLogic @@ -27,6 +26,7 @@ import net.corda.core.utilities.getOrThrow import net.corda.node.internal.Node import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.driver.PortAllocation.Incremental import net.corda.testing.driver.internal.internalServices import net.corda.testing.node.NotarySpec import net.corda.testing.node.User @@ -35,8 +35,6 @@ import net.corda.testing.node.internal.genericDriver import net.corda.testing.node.internal.getTimestampAsDirectoryName import net.corda.testing.node.internal.newContext import rx.Observable -import java.net.InetSocketAddress -import java.net.ServerSocket import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.atomic.AtomicInteger @@ -353,20 +351,20 @@ data class DriverParameters( jmxPolicy: JmxPolicy, networkParameters: NetworkParameters ) = this.copy( - isDebug, - driverDirectory, - portAllocation, - debugPortAllocation, - systemProperties, - useTestClock, - true, - startNodesInProcess, - waitForAllNodesToFinish, - notarySpecs, - extraCordappPackagesToScan, - jmxPolicy, - networkParameters, - emptyMap() + isDebug = isDebug, + driverDirectory = driverDirectory, + portAllocation = portAllocation, + debugPortAllocation = debugPortAllocation, + systemProperties = systemProperties, + useTestClock = useTestClock, + initialiseSerialization = true, + startNodesInProcess = startNodesInProcess, + waitForAllNodesToFinish = waitForAllNodesToFinish, + notarySpecs = notarySpecs, + extraCordappPackagesToScan = extraCordappPackagesToScan, + jmxPolicy = jmxPolicy, + networkParameters = networkParameters, + notaryCustomOverrides = emptyMap() ) fun copy( @@ -384,19 +382,19 @@ data class DriverParameters( jmxPolicy: JmxPolicy, networkParameters: NetworkParameters ) = this.copy( - isDebug, - driverDirectory, - portAllocation, - debugPortAllocation, - systemProperties, - useTestClock, - initialiseSerialization, - startNodesInProcess, - waitForAllNodesToFinish, - notarySpecs, - extraCordappPackagesToScan, - jmxPolicy, - networkParameters, - emptyMap() + isDebug = isDebug, + driverDirectory = driverDirectory, + portAllocation = portAllocation, + debugPortAllocation = debugPortAllocation, + systemProperties = systemProperties, + useTestClock = useTestClock, + initialiseSerialization = initialiseSerialization, + startNodesInProcess = startNodesInProcess, + waitForAllNodesToFinish = waitForAllNodesToFinish, + notarySpecs = notarySpecs, + extraCordappPackagesToScan = extraCordappPackagesToScan, + jmxPolicy = jmxPolicy, + networkParameters = networkParameters, + notaryCustomOverrides = emptyMap() ) } diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt index de3828a2de..79edc85bbe 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt @@ -100,6 +100,7 @@ interface DriverDSL { fun startNode(parameters: NodeParameters): CordaFuture = startNode(defaultParameters = parameters) /** Call [startWebserver] with a default maximumHeapSize. */ + @Suppress("DEPRECATION") fun startWebserver(handle: NodeHandle): CordaFuture = startWebserver(handle, "200m") /** @@ -107,6 +108,7 @@ interface DriverDSL { * @param handle The handle for the node that this webserver connects to via RPC. * @param maximumHeapSize Argument for JVM -Xmx option e.g. "200m". */ + @Suppress("DEPRECATION") fun startWebserver(handle: NodeHandle, maximumHeapSize: String): CordaFuture /** diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt index 94b0257edd..6506d56e4c 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt @@ -12,22 +12,23 @@ package net.corda.testing.node -import net.corda.core.concurrent.CordaFuture import net.corda.core.context.Actor import net.corda.core.context.AuthServiceId import net.corda.core.context.InvocationContext -import net.corda.core.flows.FlowLogic import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.node.ServiceHub import net.corda.core.serialization.internal.effectiveSerializationEnv import net.corda.core.transactions.TransactionBuilder -import net.corda.core.utilities.getOrThrow -import net.corda.node.services.api.StartedNodeServices import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.core.TestIdentity -import net.corda.testing.dsl.* -import net.corda.testing.internal.chooseIdentity +import net.corda.testing.dsl.EnforceVerifyOrFail +import net.corda.testing.dsl.LedgerDSL +import net.corda.testing.dsl.LedgerDSLInterpreter +import net.corda.testing.dsl.TestLedgerDSLInterpreter +import net.corda.testing.dsl.TestTransactionDSLInterpreter +import net.corda.testing.dsl.TransactionDSL +import net.corda.testing.dsl.TransactionDSLInterpreter /** * Creates and tests a ledger built by the passed in dsl. diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt index 7e48180ac0..659d258e0a 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt @@ -121,7 +121,7 @@ class DriverDSLImpl( interface Waitable { @Throws(InterruptedException::class) - fun waitFor(): Unit + fun waitFor() } class State { @@ -303,15 +303,17 @@ class DriverDSLImpl( val notaryConfig = ConfigFactory.parseMap(cordform.notary).parseAs() // We need to first group the nodes that form part of a cluster. We assume for simplicity that nodes of the // same cluster type and validating flag are part of the same cluster. - if (notaryConfig.raft != null) { - val key = if (notaryConfig.validating) VALIDATING_RAFT else NON_VALIDATING_RAFT - clusterNodes.put(key, name) - } else if (notaryConfig.bftSMaRt != null) { - clusterNodes.put(ClusterType.NON_VALIDATING_BFT, name) - } else { - // We have all we need here to generate the identity for single node notaries - val identity = DevIdentityGenerator.installKeyStoreWithNodeIdentity(baseDirectory(name), legalName = name) - notaryInfos += NotaryInfo(identity, notaryConfig.validating) + when { + notaryConfig.raft != null -> { + val key = if (notaryConfig.validating) VALIDATING_RAFT else NON_VALIDATING_RAFT + clusterNodes.put(key, name) + } + notaryConfig.bftSMaRt != null -> clusterNodes.put(ClusterType.NON_VALIDATING_BFT, name) + else -> { + // We have all we need here to generate the identity for single node notaries + val identity = DevIdentityGenerator.installKeyStoreWithNodeIdentity(baseDirectory(name), legalName = name) + notaryInfos += NotaryInfo(identity, notaryConfig.validating) + } } } @@ -380,6 +382,7 @@ class DriverDSLImpl( return startNodeInternal(config, webAddress, null, "512m", localNetworkMap) } + @Suppress("DEPRECATION") private fun queryWebserver(handle: NodeHandle, process: Process): WebserverHandle { val protocol = if ((handle as NodeHandleInternal).useHTTPS) "https://" else "http://" val url = URL("$protocol${handle.webAddress}/api/status") @@ -397,6 +400,7 @@ class DriverDSLImpl( throw IllegalStateException("Webserver at ${handle.webAddress} has died") } + @Suppress("DEPRECATION") override fun startWebserver(handle: NodeHandle, maximumHeapSize: String): CordaFuture { val debugPort = if (isDebug) debugPortAllocation.nextPort() else null val process = startWebserver(handle as NodeHandleInternal, debugPort, maximumHeapSize) @@ -721,6 +725,7 @@ class DriverDSLImpl( * A sub-set of permissions that grant most of the essential operations used in the unit/integration tests as well as * in demo application like NodeExplorer. */ + @Suppress("DEPRECATION") private val DRIVER_REQUIRED_PERMISSIONS = setOf( Permissions.invokeRpc(CordaRPCOps::nodeInfo), Permissions.invokeRpc(CordaRPCOps::networkMapFeed), @@ -933,6 +938,9 @@ private class NetworkVisibilityController { visibleNodeCount-- checkIfAllVisible() } + is NetworkMapCache.MapChange.Modified -> { + // Nothing to do here but better being exhaustive. + } } } return future diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt index 51dd476c6e..82b2bf4f77 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt @@ -275,7 +275,7 @@ open class InternalMockNetwork(private val cordappPackages: List, // We only need to override the messaging service here, as currently everything that hits disk does so // through the java.nio API which we are already mocking via Jimfs. override fun makeMessagingService(database: CordaPersistence, info: NodeInfo, nodeProperties: NodePropertiesStore, networkParameters: NetworkParameters): MessagingService { - require(id >= 0) { "Node ID must be zero or positive, was passed: " + id } + require(id >= 0) { "Node ID must be zero or positive, was passed: $id" } return mockNet.messagingNetwork.createNodeWithID( !mockNet.threadPerNode, id, diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt index a280ec1383..9998c9ef2f 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt @@ -57,7 +57,7 @@ object ProcessUtilities { } return ProcessBuilder(command).apply { inheritIO() - environment().put("CLASSPATH", classpath) + environment()["CLASSPATH"] = classpath if (workingDirectory != null) { redirectError((workingDirectory / "$className.stderr.log").toFile()) redirectOutput((workingDirectory / "$className.stdout.log").toFile()) diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt index 194d639145..643c140102 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt @@ -85,7 +85,7 @@ inline fun RPCDriverDSL.startRpcClient( configuration: CordaRPCClientConfigurationImpl = CordaRPCClientConfigurationImpl.default ) = startRpcClient(I::class.java, rpcAddress, username, password, configuration) -inline fun RPCDriverDSL.startRpcClient( +inline fun RPCDriverDSL.startRpcClient( haAddressPool: List, username: String = rpcTestUser.username, password: String = rpcTestUser.password, diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt index 6446ef8f9b..f6b3865360 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt @@ -20,20 +20,15 @@ import kotlin.concurrent.thread fun startReporter(shutdownManager: ShutdownManager, metricRegistry: MetricRegistry = MetricRegistry()): MetricRegistry { val jmxReporter = thread { - JmxReporter. - forRegistry(metricRegistry). - inDomain("net.corda"). - createsObjectNamesWith { _, domain, name -> - // Make the JMX hierarchy a bit better organised. - val category = name.substringBefore('.') - val subName = name.substringAfter('.', "") - if (subName == "") - ObjectName("$domain:name=$category") - else - ObjectName("$domain:type=$category,name=$subName") - }. - build(). - start() + JmxReporter.forRegistry(metricRegistry).inDomain("net.corda").createsObjectNamesWith { _, domain, name -> + // Make the JMX hierarchy a bit better organised. + val category = name.substringBefore('.') + val subName = name.substringAfter('.', "") + if (subName == "") + ObjectName("$domain:name=$category") + else + ObjectName("$domain:type=$category,name=$subName") + }.build().start() } shutdownManager.registerShutdown { jmxReporter.interrupt() } val consoleReporter = thread { diff --git a/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java b/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java index e33c2bc038..40f5eec945 100644 --- a/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java +++ b/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java @@ -10,8 +10,6 @@ package net.corda.testing.node; -import org.jetbrains.annotations.NotNull; - import static java.util.Collections.emptyList; @SuppressWarnings("unused") diff --git a/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt b/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt index a155aa5ba1..30ae9a8f7a 100644 --- a/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt +++ b/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt @@ -17,6 +17,7 @@ import com.typesafe.config.ConfigValue import com.typesafe.config.ConfigValueFactory import net.corda.core.identity.CordaX500Name import net.corda.nodeapi.internal.config.User +import net.corda.nodeapi.internal.config.toConfig class NodeConfig( val legalName: CordaX500Name, @@ -47,7 +48,7 @@ class NodeConfig( .withValue("address", addressValueFor(rpcPort)) .withValue("adminAddress", addressValueFor(rpcAdminPort)) .root()) - .withValue("rpcUsers", valueFor(users.map(User::toMap).toList())) + .withValue("rpcUsers", valueFor(users.map { it.toConfig().root().unwrapped() }.toList())) .withValue("database", valueFor(mapOf("runMigration" to runMigration))) .withValue("useTestClock", valueFor(true)) .withValue("jarDirs", valueFor(jarDirs)) diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt index d964863120..c9af615234 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt @@ -10,8 +10,13 @@ package net.corda.testing.contracts -import net.corda.core.contracts.* -import net.corda.core.crypto.SecureHash +import net.corda.core.contracts.AlwaysAcceptAttachmentConstraint +import net.corda.core.contracts.AttachmentConstraint +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.ContractClassName +import net.corda.core.contracts.ContractState +import net.corda.core.contracts.TypeOnlyCommandData +import net.corda.core.contracts.UpgradedContractWithLegacyConstraint import net.corda.core.identity.AbstractParty import net.corda.core.transactions.LedgerTransaction diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt index 46c2926702..5a0a0be4f2 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt @@ -253,7 +253,7 @@ private sealed class ExpectComposeState { null } else if (next.second is Finished) { if (index == sequential.sequence.size - 1) { - Pair(next.first, Finished()) + Pair(next.first, Finished()) } else { val nextState = fromExpectCompose(sequential.sequence[index + 1]) if (nextState is Finished) { @@ -281,10 +281,10 @@ private sealed class ExpectComposeState { val nextStates = states.mapIndexed { i, expectComposeState -> if (i == stateIndex) next.second else expectComposeState } - if (nextStates.all { it is Finished }) { - return Pair(next.first, Finished()) + return if (nextStates.all { it is Finished }) { + Pair(next.first, Finished()) } else { - return Pair(next.first, Parallel(parallel, nextStates)) + Pair(next.first, Parallel(parallel, nextStates)) } } } @@ -303,14 +303,14 @@ private sealed class ExpectComposeState { Single(uncheckedCast(expectCompose)) } is ExpectCompose.Sequential -> { - if (expectCompose.sequence.size > 0) { + if (expectCompose.sequence.isNotEmpty()) { Sequential(expectCompose, 0, fromExpectCompose(expectCompose.sequence[0])) } else { Finished() } } is ExpectCompose.Parallel -> { - if (expectCompose.parallel.size > 0) { + if (expectCompose.parallel.isNotEmpty()) { Parallel(expectCompose, expectCompose.parallel.map { fromExpectCompose(it) }) } else { Finished() diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt index e62e43742f..39334d3dd3 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt @@ -16,9 +16,7 @@ import net.corda.core.contracts.Command import net.corda.core.contracts.TypeOnlyCommandData import net.corda.core.crypto.generateKeyPair import net.corda.core.identity.CordaX500Name -import net.corda.nodeapi.internal.crypto.CertificateAndKeyPair import java.security.PublicKey -import java.time.Instant /** A test notary name **/ @JvmField diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt index 9732810c9e..2fe3c54399 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt @@ -17,6 +17,7 @@ import net.corda.core.crypto.* import net.corda.core.crypto.NullKeys.NULL_SIGNATURE import net.corda.core.flows.FlowException import net.corda.core.identity.Party +import net.corda.core.internal.UNKNOWN_UPLOADER import net.corda.core.internal.uncheckedCast import net.corda.core.node.ServiceHub import net.corda.core.node.ServicesForResolution @@ -291,7 +292,7 @@ data class TestLedgerDSLInterpreter private constructor( copy().dsl() override fun attachment(attachment: InputStream): SecureHash { - return services.attachments.importAttachment(attachment) + return services.attachments.importAttachment(attachment, UNKNOWN_UPLOADER, null) } override fun verifies(): EnforceVerifyOrFail { diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt index e736697c46..65be58fef9 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt @@ -185,7 +185,7 @@ private fun getFrameOffsets(stack: Stack): List> { return offsets } -private val MASK_FULL: Long = -1L +private const val MASK_FULL: Long = -1L private fun getNumSlots(record: Long): Int { return getUnsignedBits(record, 14, 16).toInt() diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt index 6ec419829d..5060191f08 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt @@ -19,4 +19,4 @@ val DEV_ROOT_CA: CertificateAndKeyPair by lazy { net.corda.nodeapi.internal.DEV_ /** A dummy time at which we will be pretending test transactions are created. **/ @JvmField -val TEST_TX_TIME = Instant.parse("2015-04-17T12:00:00.00Z") \ No newline at end of file +val TEST_TX_TIME: Instant = Instant.parse("2015-04-17T12:00:00.00Z") \ No newline at end of file diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt index 8e9c8a1999..19c7d15fff 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt @@ -72,5 +72,4 @@ object LogHelper { Configurator.setLevel(logName, oldLevel) } } - } diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt index 651ba4ee43..db560cbd48 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt @@ -15,11 +15,11 @@ import com.typesafe.config.ConfigFactory import net.corda.node.internal.cordapp.CordappConfigProvider class MockCordappConfigProvider : CordappConfigProvider { - val cordappConfigs = mutableMapOf () + val cordappConfigs = mutableMapOf() override fun getConfigByName(name: String): Config { - return if(cordappConfigs.containsKey(name)) { - cordappConfigs[name]!! + return if (cordappConfigs.containsKey(name)) { + cordappConfigs[name]!! } else { ConfigFactory.empty() } diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt index 7dff26c811..3d82444d34 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt @@ -21,7 +21,7 @@ import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder import net.corda.finance.contracts.DealState -val DUMMY_DEAL_PROGRAM_ID = "net.corda.testing.internal.vault.DummyDealContract" +const val DUMMY_DEAL_PROGRAM_ID = "net.corda.testing.internal.vault.DummyDealContract" class DummyDealContract : Contract { override fun verify(tx: LedgerTransaction) {} diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt index 91b4d1a111..bcc229487d 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt @@ -35,9 +35,7 @@ object DummyDealStateSchemaV1 : MappedSchema(schemaFamily = DummyDealStateSchema /** parent attributes */ @ElementCollection @Column(name = "participants") - @CollectionTable(name = "dummy_deal_states_parts", joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))) + @CollectionTable(name = "dummy_deal_states_parts", joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))]) override var participants: MutableSet? = null, @Transient diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt index 7de684e93d..28a273614a 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt @@ -31,9 +31,7 @@ object DummyLinearStateSchemaV2 : MappedSchema(schemaFamily = DummyLinearStateSc @ElementCollection @Column(name = "participants") - @CollectionTable(name = "dummy_linear_states_v2_parts", joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))) + @CollectionTable(name = "dummy_linear_states_v2_parts", joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))]) override var participants: MutableSet? = null, @Column(name = "linear_string") var linearString: String, diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt index a24cb439ff..30f685c6ba 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt @@ -37,11 +37,12 @@ class MockAttachmentStorage : AttachmentStorage, SingletonSerializeAsToken() { /** A map of the currently stored files by their [SecureHash] */ val files: Map> get() = _files + @Suppress("OverridingDeprecatedMember") override fun importAttachment(jar: InputStream): AttachmentId = importAttachment(jar, UNKNOWN_UPLOADER, null) override fun importAttachment(jar: InputStream, uploader: String, filename: String?): AttachmentId { return withContractsInJar(jar) { contractClassNames, inputStream -> - importAttachmentInternal(inputStream, uploader, filename, contractClassNames) + importAttachmentInternal(inputStream, uploader, contractClassNames) } } @@ -53,21 +54,22 @@ class MockAttachmentStorage : AttachmentStorage, SingletonSerializeAsToken() { override fun hasAttachment(attachmentId: AttachmentId) = files.containsKey(attachmentId) + @Suppress("OverridingDeprecatedMember") override fun importOrGetAttachment(jar: InputStream): AttachmentId { - try { - return importAttachment(jar) - } catch (faee: java.nio.file.FileAlreadyExistsException) { - return AttachmentId.parse(faee.message!!) + return try { + importAttachment(jar, UNKNOWN_UPLOADER, null) + } catch (e: java.nio.file.FileAlreadyExistsException) { + AttachmentId.parse(e.message!!) } } - fun importContractAttachment(contractClassNames: List, uploader: String, jar: InputStream): AttachmentId = importAttachmentInternal(jar, uploader, null, contractClassNames) + fun importContractAttachment(contractClassNames: List, uploader: String, jar: InputStream): AttachmentId = importAttachmentInternal(jar, uploader, contractClassNames) fun getAttachmentIdAndBytes(jar: InputStream): Pair = jar.readFully().let { bytes -> Pair(bytes.sha256(), bytes) } private class MockAttachment(dataLoader: () -> ByteArray, override val id: SecureHash) : AbstractAttachment(dataLoader) - private fun importAttachmentInternal(jar: InputStream, uploader: String, filename: String?, contractClassNames: List? = null): AttachmentId { + private fun importAttachmentInternal(jar: InputStream, uploader: String, contractClassNames: List? = null): AttachmentId { // JIS makes read()/readBytes() return bytes of the current file, but we want to hash the entire container here. require(jar !is JarInputStream) diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt index 5bb314014d..8604024463 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt @@ -21,7 +21,7 @@ import tornadofx.* * This class will create paths that it needs to poll and to where it needs to copy files in case those * don't exist yet. */ -class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()): Controller() { +class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()) : Controller() { private val nodeInfoFilesCopier = NodeInfoFilesCopier(scheduler) @@ -31,7 +31,7 @@ class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()): Cont * Its nodeInfo file will be copied to other nodes' additional-node-infos directory, and conversely, * other nodes' nodeInfo files will be copied to this node additional-node-infos directory. */ - fun addConfig(nodeConfig: NodeConfigWrapper) : Unit = nodeInfoFilesCopier.addConfig(nodeConfig.nodeDir) + fun addConfig(nodeConfig: NodeConfigWrapper): Unit = nodeInfoFilesCopier.addConfig(nodeConfig.nodeDir) /** * @param nodeConfig the configuration to be removed. @@ -39,7 +39,7 @@ class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()): Cont * No files written by that node will be copied to other nodes, nor files from other nodes will be copied to this * one. */ - fun removeConfig(nodeConfig: NodeConfigWrapper) : Unit = nodeInfoFilesCopier.removeConfig(nodeConfig.nodeDir) + fun removeConfig(nodeConfig: NodeConfigWrapper): Unit = nodeInfoFilesCopier.removeConfig(nodeConfig.nodeDir) - fun reset() : Unit = nodeInfoFilesCopier.reset() + fun reset(): Unit = nodeInfoFilesCopier.reset() } \ No newline at end of file diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt index 1d4e13f01e..881499dd33 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt @@ -48,7 +48,7 @@ data class NodeConfig( companion object { val renderOptions: ConfigRenderOptions = ConfigRenderOptions.defaults().setOriginComments(false) val defaultUser = user("guest") - val cordappDirName = "cordapps" + const val cordappDirName = "cordapps" } @Suppress("unused") diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt index bcab464385..b47628aa95 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt @@ -53,11 +53,12 @@ class CordappController : Controller() { @Throws(IOException::class) fun useCordappsFor(config: HasCordapps): List { if (!config.cordappsDir.isDirectory()) return emptyList() - return config.cordappsDir.walk(1) { paths -> paths - .filter(Path::isCordapp) - .filter { !bankOfCorda.endsWith(it.fileName) } - .filter { !finance.endsWith(it.fileName) } - .toList() + return config.cordappsDir.walk(1) { paths -> + paths + .filter(Path::isCordapp) + .filter { !bankOfCorda.endsWith(it.fileName) } + .filter { !finance.endsWith(it.fileName) } + .toList() } } } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt index 7d77392109..d4610a7793 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt @@ -40,5 +40,4 @@ class PtyProcessTtyConnector( ) } } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt index c673f55aaf..131eeba89f 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt @@ -76,5 +76,4 @@ class R3Pty(val name: CordaX500Name, settings: SettingsProvider, dimension: Dime @Suppress("unused") @Throws(InterruptedException::class) fun waitFor(): Int? = terminal.ttyConnector?.waitFor() - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt index 0bc4ee1c36..a2909fa59d 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt @@ -48,7 +48,6 @@ private class ZeroFilter(output: OutputStream) : FilterOutputStream(output) { super.write(filtered, 0, count) } - } /** @@ -73,7 +72,6 @@ private class ZeroFilteringProcess(private val process: Process) : Process() { override fun destroy() = process.destroy() override fun exitValue() = process.exitValue() - } /** diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt index 0da67d335c..8fef9c63d6 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt @@ -68,5 +68,4 @@ class NodeRPC(config: NodeConfigWrapper, start: (NodeConfigWrapper, CordaRPCOps) log.error("Failed to close RPC connection (Error: {})", e.message) } } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt index 6aa99aa8e5..8bc339205a 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt @@ -31,5 +31,4 @@ class CloseableTab(text: String, content: Node) : Tab(text, content) { behaviour.closeTab(this) } } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt index 0fd68864e9..d033dbf20b 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt @@ -37,5 +37,4 @@ class PropertyLabel : HBox() { children.addAll(nameLabel, valueLabel) styleClass.add("property-label") } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt index a5502c2e67..20d851cbdc 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt @@ -63,5 +63,4 @@ class DBViewer : AutoCloseable { Server.openBrowser(url) } } - } diff --git a/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt b/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt index df1f5f6ce4..47a1e8eba8 100644 --- a/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt +++ b/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt @@ -25,7 +25,6 @@ class LocalWebServer : WebServer() { session.connection = conn session.put("url", conn.metaData.url) val s = session.get("sessionId") as String - return url + "/frame.jsp?jsessionid=" + s + return "$url/frame.jsp?jsessionid=$s" } - } diff --git a/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt b/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt index 545c2b37d9..d3424d712f 100644 --- a/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt +++ b/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt @@ -38,5 +38,4 @@ class LoggingTestSuite { LoggingConfig() } } - } 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 6a013b34c7..c0c20fb65a 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt @@ -91,10 +91,10 @@ class Main : App(MainView::class) { } private fun asInteger(s: String?): Int? { - try { - return s?.toInt() + return try { + s?.toInt() } catch (e: NumberFormatException) { - return null + null } } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt index e1a328b54d..f614663d1b 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt @@ -10,7 +10,6 @@ package net.corda.explorer.formatters - interface Formatter { fun format(value: T): String } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt index 8be5984a84..d284f0e183 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt @@ -76,17 +76,17 @@ object IdenticonRenderer { byteArrayOf(0, 2, 10, 0), byteArrayOf(0, 4, 24, 20, 0)).map(::Patch) - private val PATCH_CELLS = 4 + private const val PATCH_CELLS = 4 private val PATCH_GRIDS = PATCH_CELLS + 1 - private val PATCH_SYMMETRIC: Byte = 1 - private val PATCH_INVERTED: Byte = 2 + private const val PATCH_SYMMETRIC: Byte = 1 + private const val PATCH_INVERTED: Byte = 2 private val patchFlags = byteArrayOf(PATCH_SYMMETRIC, 0, 0, 0, PATCH_SYMMETRIC, 0, 0, 0, PATCH_SYMMETRIC, 0, 0, 0, 0, 0, 0, (PATCH_SYMMETRIC + PATCH_INVERTED).toByte()) - private val renderingSize = 30.0 + private const val renderingSize = 30.0 private val cache = Caffeine.newBuilder().build(CacheLoader { key -> - key?.let { render(key.hashCode(), renderingSize) } + key.let { render(key.hashCode(), renderingSize) } }) private class Patch(private val byteArray: ByteArray) { diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt index 85c30e5d05..1d180b58b3 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt @@ -15,13 +15,8 @@ import net.corda.client.jfx.model.ExchangeRate import net.corda.client.jfx.model.ExchangeRateModel import net.corda.client.jfx.model.observableValue import net.corda.client.jfx.utils.AmountBindings -import net.corda.core.contracts.* -import net.corda.finance.CHF -import net.corda.finance.EUR -import net.corda.finance.GBP -import net.corda.finance.USD +import net.corda.core.contracts.Amount import org.fxmisc.easybind.EasyBind -import tornadofx.* import java.util.* class ReportingCurrencyModel { diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt index ce45b4d693..5b553acf1d 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt @@ -11,6 +11,7 @@ package net.corda.explorer.ui import javafx.beans.binding.Bindings +import javafx.beans.binding.ObjectBinding import javafx.beans.value.ObservableValue import javafx.scene.Node import javafx.scene.control.TableCell @@ -58,7 +59,7 @@ fun Formatter.toTableCellFactory() = Callback, Tabl } } -fun TableView.singleRowSelection() = Bindings.createObjectBinding({ +fun TableView.singleRowSelection(): ObjectBinding> = Bindings.createObjectBinding({ if (selectionModel.selectedItems.size == 0) { SingleRowSelection.None() } else { diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt index b075c3aa7c..932125fa83 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt @@ -19,7 +19,6 @@ import javafx.util.Callback import net.corda.explorer.formatters.Formatter import org.fxmisc.easybind.EasyBind - fun TreeTableView.setColumnPrefWidthPolicy( getColumnWidth: (tableWidthWithoutPaddingAndBorder: Number, column: TreeTableColumn) -> Number ) { 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 f81b753be6..13e4cae29f 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 @@ -61,5 +61,4 @@ class Dashboard : CordaView() { } } } - } \ No newline at end of file diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt index 9048ebe6f8..4c058c94cd 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt @@ -35,7 +35,7 @@ const val WINDOW_TITLE = "Corda Node Explorer" * Helper method to reduce boiler plate code */ fun stringConverter(fromStringFunction: ((String?) -> T)? = null, toStringFunction: (T) -> String): StringConverter { - val converter = object : StringConverter() { + return object : StringConverter() { override fun fromString(string: String?): T { return fromStringFunction?.invoke(string) ?: throw UnsupportedOperationException("not implemented") } @@ -44,7 +44,6 @@ fun stringConverter(fromStringFunction: ((String?) -> T)? = null, toStringFu return toStringFunction(o) } } - return converter } /** 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 976bbc7532..fcb7e978c4 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 @@ -82,7 +82,7 @@ class Network : CordaView() { private val peerButtons = peerComponents.filtered { myIdentity.value !in it.nodeInfo.legalIdentitiesAndCerts.map { it.party } }.map { it.button } private val allComponents = FXCollections.observableArrayList(notaryComponents, peerComponents).concatenate().apply { addListener(ListChangeListener { - if(it.next()){ + if (it.next()) { it.removed.forEach { mapPane.children.remove(it.label) } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt index f6c82c1273..8c9c0dee58 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt @@ -78,7 +78,7 @@ class SearchField(private val data: ObservableList, vararg filterCriteria: }) textField.promptTextProperty().bind(searchCategory.valueProperty().map { val category = if (it == ALL) { - filterCriteria.map { it.first.toLowerCase() }.joinToString(", ") + filterCriteria.joinToString(", ") { it.first.toLowerCase() } } else { it.toLowerCase() } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt index f3492fb18d..63834509ab 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt @@ -23,7 +23,6 @@ import net.corda.client.jfx.model.observableList import net.corda.client.jfx.utils.map import net.corda.explorer.model.CordaView import net.corda.explorer.model.IssuerModel -import net.corda.explorer.model.ReportingCurrencyModel import net.corda.explorer.model.SettingsModel import java.util.* 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 9758a79a7f..e451532923 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt @@ -40,10 +40,10 @@ fun setupJSchWithSshAgent(): JSch { return JSch().apply { identityRepository = object : IdentityRepository { override fun getStatus(): Int { - if (connector.isAvailable) { - return IdentityRepository.RUNNING + return if (connector.isAvailable) { + IdentityRepository.RUNNING } else { - return IdentityRepository.UNAVAILABLE + IdentityRepository.UNAVAILABLE } } 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 9175de568d..68bf94ca2b 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt @@ -10,9 +10,8 @@ package net.corda.loadtest -import net.corda.client.mock.* +import net.corda.client.mock.Generator import net.corda.core.utilities.loggerFor -import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.Callable import java.util.concurrent.Executors diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt index 25a0c8f2aa..56ac732daa 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt @@ -188,15 +188,15 @@ fun runLoadTests(configuration: LoadTestConfiguration, tests: List acc + "\n" + elem.name + ": " + elem.owningKey.toBase58String() } - }.joinToString("\n") + } log.info("${connection.remoteNode.hostname} waiting for network map") connection.proxy.waitUntilNetworkReady().get() log.info("${connection.remoteNode.hostname} sees\n$pubKeysString") - hostNodeMap.put(connection.remoteNode.hostname, connection) + hostNodeMap[connection.remoteNode.hostname] = connection } val notaryIdentity = hostNodeMap.values.first().proxy.notaryIdentities().single() 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 746a19403f..f5bfa1476d 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 @@ -158,13 +158,13 @@ val crossCashTest = LoadTest( } }, - interpret = { state, command -> - when (command.request) { + interpret = { state, (request, node) -> + when (request) { is IssueAndPaymentRequest -> { val newDiffQueues = state.copyQueues() - val originators = newDiffQueues.getOrPut(command.request.recipient, { HashMap() }) - val issuer = command.node.mainIdentity - val quantity = command.request.amount.quantity + val originators = newDiffQueues.getOrPut(request.recipient, { HashMap() }) + val issuer = node.mainIdentity + val quantity = request.amount.quantity val queue = originators.getOrPut(issuer, { ArrayList() }) queue.add(Pair(issuer, quantity)) CrossCashState(state.nodeVaults, newDiffQueues) @@ -172,25 +172,25 @@ val crossCashTest = LoadTest( is PaymentRequest -> { val newNodeVaults = state.copyVaults() val newDiffQueues = state.copyQueues() - val recipientOriginators = newDiffQueues.getOrPut(command.request.recipient, { HashMap() }) - val senderQuantities = newNodeVaults[command.node.mainIdentity]!! - val amount = command.request.amount - val issuer = command.request.issuerConstraint.single() - val originator = command.node.mainIdentity + val recipientOriginators = newDiffQueues.getOrPut(request.recipient, { HashMap() }) + val senderQuantities = newNodeVaults[node.mainIdentity]!! + val amount = request.amount + val issuer = request.issuerConstraint.single() + val originator = node.mainIdentity val senderQuantity = senderQuantities[issuer] ?: throw Exception( - "Generated payment of ${command.request.amount} from ${command.node.mainIdentity}, " + + "Generated payment of ${request.amount} from ${node.mainIdentity}, " + "however there is no cash from $issuer!" ) if (senderQuantity < amount.quantity) { throw Exception( - "Generated payment of ${command.request.amount} from ${command.node.mainIdentity}, " + + "Generated payment of ${request.amount} from ${node.mainIdentity}, " + "however they only have $senderQuantity!" ) } if (senderQuantity == amount.quantity) { senderQuantities.remove(issuer) } else { - senderQuantities.put(issuer, senderQuantity - amount.quantity) + senderQuantities[issuer] = senderQuantity - amount.quantity } val recipientQueue = recipientOriginators.getOrPut(originator, { ArrayList() }) recipientQueue.add(Pair(issuer, amount.quantity)) @@ -198,26 +198,26 @@ val crossCashTest = LoadTest( } is ExitRequest -> { val newNodeVaults = state.copyVaults() - val issuer = command.node.mainIdentity - val quantity = command.request.amount.quantity + val issuer = node.mainIdentity + val quantity = request.amount.quantity val issuerQuantities = newNodeVaults[issuer]!! val issuerQuantity = issuerQuantities[issuer] ?: throw Exception( - "Generated exit of ${command.request.amount} from $issuer, however there is no cash to exit!" + "Generated exit of ${request.amount} from $issuer, however there is no cash to exit!" ) if (issuerQuantity < quantity) { throw Exception( - "Generated payment of ${command.request.amount} from $issuer, " + + "Generated payment of ${request.amount} from $issuer, " + "however they only have $issuerQuantity!" ) } if (issuerQuantity == quantity) { issuerQuantities.remove(issuer) } else { - issuerQuantities.put(issuer, issuerQuantity - quantity) + issuerQuantities[issuer] = issuerQuantity - quantity } CrossCashState(newNodeVaults, state.diffQueues) } - else -> throw IllegalArgumentException("Unexpected request type: ${command.request}") + else -> throw IllegalArgumentException("Unexpected request type: ${request}") } }, @@ -245,9 +245,9 @@ val crossCashTest = LoadTest( vault.forEach { val state = it.state.data val issuer = state.amount.token.issuer.party - quantities.put(issuer, (quantities[issuer] ?: 0L) + state.amount.quantity) + quantities[issuer] = (quantities[issuer] ?: 0L) + state.amount.quantity } - currentNodeVaults.put(it.mainIdentity, quantities) + currentNodeVaults[it.mainIdentity] = quantities } val (consistentVaults, diffQueues) = if (previousState == null) { Pair(currentNodeVaults, mapOf>>>()) @@ -268,7 +268,7 @@ val crossCashTest = LoadTest( "\nActual gathered state:\n${CrossCashState(currentNodeVaults, mapOf())}" ) // TODO We should terminate here with an exception, we cannot carry on as we have an inconsistent model. We carry on currently because we always diverge due to notarisation failures - return@LoadTest CrossCashState(currentNodeVaults, mapOf>>>()) + return@LoadTest CrossCashState(currentNodeVaults, mapOf()) } if (matches.size > 1) { log.warn("Multiple predicted states match the remote state") @@ -289,7 +289,7 @@ val crossCashTest = LoadTest( newNodeDiffQueues!! for (i in 0 until consumedTxs) { val (issuer, quantity) = newNodeDiffQueues[originator]!!.removeAt(0) - newNodeVault.put(issuer, (newNodeVault[issuer] ?: 0L) + quantity) + newNodeVault[issuer] = (newNodeVault[issuer] ?: 0L) + quantity } } } @@ -357,6 +357,6 @@ private fun applyDiff( if (searchedQuantity == null || newQuantity > searchedQuantity) { return null } - newState.put(issuer, newQuantity) + newState[issuer] = newQuantity return newState } 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 db81cfd9c5..734c75ee3c 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 @@ -65,7 +65,7 @@ val selfIssueTest = LoadTest( interpret = { state, (request, node) -> val vaults = state.copyVaults() val issuer = node.mainIdentity - vaults.put(issuer, (vaults[issuer] ?: 0L) + request.amount.quantity) + vaults[issuer] = (vaults[issuer] ?: 0L) + request.amount.quantity SelfIssueState(vaults) }, @@ -86,7 +86,7 @@ val selfIssueTest = LoadTest( val state = it.state.data val issuer = state.amount.token.issuer.party if (issuer == connection.mainIdentity as AbstractParty) { - selfIssueVaults.put(issuer, (selfIssueVaults[issuer] ?: 0L) + state.amount.quantity) + selfIssueVaults[issuer] = (selfIssueVaults[issuer] ?: 0L) + state.amount.quantity } } } diff --git a/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java b/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java index d967a3bf1e..4addbdde41 100644 --- a/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java +++ b/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java @@ -21,7 +21,10 @@ import org.crsh.cli.Usage; import org.crsh.command.InvocationContext; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; import static java.util.Comparator.comparing; @@ -54,7 +57,7 @@ public class RunShellCommand extends InteractiveShellCommand { // Sends data down the pipeline about what commands are available. CRaSH will render it nicely. // Each element we emit is a map of column -> content. Set> entries = parser.getAvailableCommands().entrySet(); - ArrayList> entryList = new ArrayList<>(entries); + List> entryList = new ArrayList<>(entries); entryList.sort(comparing(Map.Entry::getKey)); for (Map.Entry entry : entryList) { // Skip these entries as they aren't really interesting for the user. diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt index b8acfb5ba8..ae3dcf9113 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt @@ -17,7 +17,7 @@ import org.crsh.auth.AuthInfo import org.crsh.auth.AuthenticationPlugin import org.crsh.plugin.CRaSHPlugin -class CordaAuthenticationPlugin(private val rpcOps: (username: String, credential: String) -> CordaRPCOps): CRaSHPlugin>(), AuthenticationPlugin { +class CordaAuthenticationPlugin(private val rpcOps: (username: String, credential: String) -> CordaRPCOps) : CRaSHPlugin>(), AuthenticationPlugin { companion object { private val logger = loggerFor() diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt index b2d665089b..646b1c5e31 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt @@ -152,7 +152,7 @@ object InteractiveShell { val extraCommandsPath = shellCommands.toAbsolutePath().createDirectories() val commandsFS = FS.Builder() .register("file", fileDriver) - .mount("file:" + extraCommandsPath) + .mount("file:$extraCommandsPath") .register("classpath", classpathDriver) .mount("classpath:/net/corda/tools/shell/") .mount("classpath:/crash/commands/") @@ -312,7 +312,7 @@ object InteractiveShell { try { // Attempt construction with the given arguments. paramNamesFromConstructor = parser.paramNamesFromConstructor(ctor) - val args = parser.parseArguments(clazz.name, paramNamesFromConstructor!!.zip(ctor.parameterTypes), inputData) + val args = parser.parseArguments(clazz.name, paramNamesFromConstructor.zip(ctor.parameterTypes), inputData) if (args.size != ctor.parameterTypes.size) { errors.add("${getPrototype()}: Wrong number of arguments (${args.size} provided, ${ctor.parameterTypes.size} needed)") continue @@ -385,7 +385,7 @@ object InteractiveShell { val parser = StringToMethodCallParser(CordaRPCOps::class.java, om) val call = parser.parse(cordaRPCOps, cmd) result = call.call() - if (result != null && result !is kotlin.Unit && result !is Void) { + if (result != null && result !== kotlin.Unit && result !is Void) { result = printAndFollowRPCResponse(result, out) } if (result is Future<*>) { @@ -439,9 +439,9 @@ object InteractiveShell { log.error(error.message) throw error } - .doOnNext { remaining -> + .doOnNext { (first, second) -> display { - println("...remaining: ${remaining.first}/${remaining.second}") + println("...remaining: ${first}/${second}") } } .doOnCompleted { diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt index 90e08363fa..82800e5ab1 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt @@ -11,7 +11,7 @@ data class SSHDConfiguration(val port: Int) { */ @JvmStatic fun parse(str: String): SSHDConfiguration { - require(!str.isNullOrBlank()) { SSHDConfiguration.MISSING_PORT_FORMAT.format(str) } + require(!str.isBlank()) { SSHDConfiguration.MISSING_PORT_FORMAT.format(str) } val port = try { str.toInt() } catch (ex: NumberFormatException) { diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt index bf9bd2563d..332841026c 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt @@ -81,10 +81,10 @@ class StandaloneShell(private val configuration: ShellConfiguration) { val cordappJarPaths = getCordappsInDirectory(configuration.cordappsDirectory) val classLoader: ClassLoader = URLClassLoader(cordappJarPaths.toTypedArray(), javaClass.classLoader) with(configuration) { - if (user.isNullOrEmpty()) { + if (user.isEmpty()) { user = readLine("User:") } - if (password.isNullOrEmpty()) { + if (password.isEmpty()) { password = String(readPassword("Password:")) } } diff --git a/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt b/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt index 0c85d67be7..4c21a08243 100644 --- a/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt +++ b/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt @@ -47,11 +47,12 @@ class InteractiveShellTest { } private val ids = InMemoryIdentityService(arrayOf(megaCorp.identity), DEV_ROOT_CA.certificate) + @Suppress("DEPRECATION") private val om = JacksonSupport.createInMemoryMapper(ids, YAMLFactory()) private fun check(input: String, expected: String) { var output: String? = null - InteractiveShell.runFlowFromString( { clazz, args -> + InteractiveShell.runFlowFromString({ clazz, args -> val instance = clazz.getConstructor(*args.map { it!!::class.java }.toTypedArray()).newInstance(*args) as FlowA output = instance.a diff --git a/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt b/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt index 68f2d3ad70..ac4a9cd3eb 100644 --- a/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt +++ b/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt @@ -8,6 +8,8 @@ * Distribution of this file or any portion thereof via any medium without the express permission of R3 is strictly prohibited. */ +@file:Suppress("DEPRECATION") + package net.corda.webserver import net.corda.core.utilities.NetworkHostAndPort @@ -28,7 +30,7 @@ import java.util.concurrent.ScheduledExecutorService class WebserverDriverTests : IntegrationTest() { companion object { - val executorService: ScheduledExecutorService = Executors.newScheduledThreadPool(2) + private val executorService: ScheduledExecutorService = Executors.newScheduledThreadPool(2) fun webserverMustBeUp(webserverHandle: WebserverHandle) { addressMustBeBound(executorService, webserverHandle.listenAddress, webserverHandle.process) diff --git a/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt b/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt index eb032a02a0..a837ac36fa 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt @@ -47,6 +47,6 @@ class WebServerConfig(override val baseDirectory: Path, val config: Config) : No } else { config.getConfigList("security.authService.dataSource.users") } - runAs = users.first().parseAs() + runAs = users.first().parseAs() } } diff --git a/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt b/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt index c9218391de..b4b6178683 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt @@ -101,5 +101,4 @@ interface APIServer { @Path("states") @Produces(MediaType.APPLICATION_JSON) fun states(): List> - } \ No newline at end of file diff --git a/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt b/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt index 9a90327ab2..1633c76af6 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt @@ -18,16 +18,25 @@ import net.corda.core.utilities.contextLogger import net.corda.webserver.WebServerConfig import net.corda.webserver.converters.CordaConverterProvider import net.corda.webserver.services.WebServerPluginRegistry -import net.corda.webserver.servlets.* +import net.corda.webserver.servlets.AttachmentDownloadServlet +import net.corda.webserver.servlets.CorDappInfoServlet +import net.corda.webserver.servlets.DataUploadServlet +import net.corda.webserver.servlets.ObjectMapperConfig +import net.corda.webserver.servlets.ResponseFilter import org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException -import org.eclipse.jetty.server.* +import org.eclipse.jetty.server.Connector +import org.eclipse.jetty.server.HttpConfiguration +import org.eclipse.jetty.server.HttpConnectionFactory +import org.eclipse.jetty.server.SecureRequestCustomizer +import org.eclipse.jetty.server.Server +import org.eclipse.jetty.server.ServerConnector +import org.eclipse.jetty.server.SslConnectionFactory import org.eclipse.jetty.server.handler.ErrorHandler import org.eclipse.jetty.server.handler.HandlerCollection import org.eclipse.jetty.servlet.DefaultServlet import org.eclipse.jetty.servlet.ServletContextHandler import org.eclipse.jetty.servlet.ServletHolder import org.eclipse.jetty.util.ssl.SslContextFactory -import org.eclipse.jetty.webapp.WebAppContext import org.glassfish.jersey.server.ResourceConfig import org.glassfish.jersey.server.ServerProperties import org.glassfish.jersey.servlet.ServletContainer @@ -38,7 +47,6 @@ import java.lang.reflect.InvocationTargetException import java.nio.file.NoSuchFileException import java.util.* import javax.servlet.http.HttpServletRequest -import javax.ws.rs.core.MediaType class NodeWebServer(val config: WebServerConfig) { private companion object { diff --git a/webserver/src/main/kotlin/net/corda/webserver/service/WebServerPluginRegistry.kt b/webserver/src/main/kotlin/net/corda/webserver/services/WebServerPluginRegistry.kt similarity index 96% rename from webserver/src/main/kotlin/net/corda/webserver/service/WebServerPluginRegistry.kt rename to webserver/src/main/kotlin/net/corda/webserver/services/WebServerPluginRegistry.kt index b5b42e186e..249b0746c8 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/service/WebServerPluginRegistry.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/services/WebServerPluginRegistry.kt @@ -36,6 +36,5 @@ interface WebServerPluginRegistry { * Optionally register extra JSON serializers to the default ObjectMapper provider * @param om The [ObjectMapper] to register custom types against. */ - fun customizeJSONSerialization(om: ObjectMapper): Unit {} - + fun customizeJSONSerialization(om: ObjectMapper) {} } \ No newline at end of file diff --git a/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt b/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt index e1cd8f7d9a..cc0071e319 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt @@ -45,7 +45,7 @@ class CorDappInfoServlet(val plugins: List, val rpc: Co plugin.webApis.forEach { api -> val resource = Resource.from(api.apply(rpc)::class.java) p { +"${resource.name}:" } - val endpoints = processEndpoints("", resource, mutableListOf()) + val endpoints = processEndpoints("", resource, mutableListOf()) ul { endpoints.forEach { li { a(it.uri) { +"${it.method}\t${it.text}" } } diff --git a/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt b/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt index e532624c43..732a97be47 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt @@ -39,7 +39,5 @@ class ResponseFilter : ContainerResponseFilter { headers.add("Access-Control-Allow-Headers", "Content-Type,Accept,Origin") headers.add("Access-Control-Allow-Methods", "POST,PUT,GET,OPTIONS") } - } - }