diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 356d4cafaab..e1cb19e8bea 100644
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -127,6 +127,8 @@
+
+
diff --git a/build.gradle b/build.gradle
index a960fb5c55d..16451c70592 100644
--- a/build.gradle
+++ b/build.gradle
@@ -172,6 +172,7 @@ allprojects {
jvmTarget = "1.8"
javaParameters = true // Useful for reflection.
freeCompilerArgs = ['-Xjvm-default=compatibility']
+ allWarningsAsErrors = true
}
}
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 ab405af19bd..8f5c1fe4ddb 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
@@ -3,7 +3,6 @@ package net.corda.client.jfx
import net.corda.client.jfx.model.NodeMonitorModel
import net.corda.client.jfx.model.ProgressTrackingEvent
import net.corda.core.context.InvocationOrigin
-import net.corda.core.contracts.Amount
import net.corda.core.contracts.ContractState
import net.corda.core.crypto.isFulfilledBy
import net.corda.core.crypto.keys
@@ -22,12 +21,9 @@ import net.corda.core.transactions.SignedTransaction
import net.corda.core.utilities.OpaqueBytes
import net.corda.core.utilities.getOrThrow
import net.corda.finance.DOLLARS
-import net.corda.finance.USD
-import net.corda.finance.flows.CashExitFlow
import net.corda.finance.flows.CashIssueFlow
import net.corda.finance.flows.CashPaymentFlow
-import net.corda.node.services.Permissions.Companion.invokeRpc
-import net.corda.node.services.Permissions.Companion.startFlow
+import net.corda.node.services.Permissions.Companion.all
import net.corda.testing.core.*
import net.corda.testing.driver.DriverParameters
import net.corda.testing.driver.driver
@@ -54,18 +50,7 @@ class NodeMonitorModelTest {
private fun setup(runTest: () -> Unit) {
driver(DriverParameters(extraCordappPackagesToScan = listOf("net.corda.finance"))) {
- val cashUser = User("user1", "test", permissions = setOf(
- startFlow(),
- startFlow(),
- startFlow(),
- invokeRpc(CordaRPCOps::notaryIdentities),
- invokeRpc("vaultTrackBy"),
- invokeRpc("vaultQueryBy"),
- invokeRpc(CordaRPCOps::internalVerifiedTransactionsFeed),
- invokeRpc(CordaRPCOps::stateMachineRecordedTransactionMappingFeed),
- invokeRpc(CordaRPCOps::stateMachinesFeed),
- invokeRpc(CordaRPCOps::networkMapFeed))
- )
+ val cashUser = User("user1", "test", permissions = setOf(all()))
val aliceNodeHandle = startNode(providedName = ALICE_NAME, rpcUsers = listOf(cashUser)).getOrThrow()
aliceNode = aliceNodeHandle.nodeInfo
newNode = { nodeName -> startNode(providedName = nodeName).getOrThrow().nodeInfo }
@@ -114,11 +99,7 @@ class NodeMonitorModelTest {
@Test
fun `cash issue works end to end`() = setup {
- rpc.startFlow(::CashIssueFlow,
- Amount(100, USD),
- OpaqueBytes(ByteArray(1, { 1 })),
- notaryParty
- )
+ rpc.startFlow(::CashIssueFlow, 100.DOLLARS, OpaqueBytes.of(1), notaryParty)
vaultUpdates.expectEvents(isStrict = false) {
sequence(
diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt
index 26d9bf09d50..eb8e78898f3 100644
--- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt
+++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NodeMonitorModel.kt
@@ -101,12 +101,12 @@ class NodeMonitorModel : AutoCloseable {
* TODO provide an unsubscribe mechanism
*/
fun register(nodeHostAndPort: NetworkHostAndPort, username: String, password: String) {
-
// `retryableStateMachineUpdatesSubject` will change it's upstream subscriber in case of RPC connection failure, this `Observable` should
// never produce an error.
// `stateMachineUpdatesSubject` will stay firmly subscribed to `retryableStateMachineUpdatesSubject`
retryableStateMachineUpdatesSubject.subscribe(stateMachineUpdatesSubject)
+ @Suppress("DEPRECATION")
// Proxy may change during re-connect, ensure that subject wiring accurately reacts to this activity.
proxyObservable.addListener { _, _, wrapper ->
if (wrapper != null) {
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 900ed8fd42e..7d208748c8b 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
@@ -48,7 +48,7 @@ data class PartiallyResolvedTransaction(
return PartiallyResolvedTransaction(
transaction = transaction,
inputs = transaction.inputs.map { stateRef ->
- val tx = inputTransactions.get(stateRef)
+ val tx = inputTransactions[stateRef]
if (tx == null) {
InputResolution.Unresolved(stateRef)
} else {
@@ -64,7 +64,7 @@ data class PartiallyResolvedTransaction(
val outputCount = transaction.coreTransaction.inputs.size
val stateRefs = (0 until outputCount).map { StateRef(transaction.id, it) }
stateRefs.map { stateRef ->
- val tx = inputTransactions.get(stateRef)
+ val tx = inputTransactions[stateRef]
if (tx == null) {
OutputResolution.Unresolved(stateRef)
} else {
@@ -84,6 +84,7 @@ class TransactionDataModel {
private val collectedTransactions = transactions.recordInSequence().distinctBy { it.id }
private val rpcProxy by observableValue(NodeMonitorModel::proxyObservable)
+ @Suppress("DEPRECATION")
val partiallyResolvedTransactions = collectedTransactions.map {
PartiallyResolvedTransaction.fromSignedTransaction(it,
it.inputs.map { stateRef ->
diff --git a/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt b/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt
index 98bb3223237..2d9cde9b38e 100644
--- a/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt
+++ b/client/rpc/src/integration-test/kotlin/net/corda/client/rpc/FlowsExecutionModeRpcTest.kt
@@ -54,14 +54,12 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract
@Before
fun setup() {
-
node = startNode(ALICE_NAME, rpcUsers = listOf(rpcUser))
- client = CordaRPCClient(node.internals.configuration.rpcOptions.address!!)
+ client = CordaRPCClient(node.internals.configuration.rpcOptions.address)
}
@Test
fun `flows draining mode can be enabled and queried`() {
-
asALoggerUser { rpcOps ->
val newValue = true
rpcOps.setFlowsDrainingModeEnabled(true)
@@ -74,7 +72,6 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract
@Test
fun `flows draining mode can be disabled and queried`() {
-
asALoggerUser { rpcOps ->
rpcOps.setFlowsDrainingModeEnabled(true)
val newValue = false
@@ -88,7 +85,6 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract
@Test
fun `node starts with flows draining mode disabled`() {
-
asALoggerUser { rpcOps ->
val defaultStartingMode = rpcOps.isFlowsDrainingModeEnabled()
@@ -97,14 +93,12 @@ class FlowsExecutionModeTests : NodeBasedTest(listOf("net.corda.finance.contract
}
private fun login(username: String, password: String, externalTrace: Trace? = null, impersonatedActor: Actor? = null): CordaRPCConnection {
-
return client.start(username, password, externalTrace, impersonatedActor)
}
private fun asALoggerUser(action: (CordaRPCOps) -> Unit) {
-
login(rpcUser.username, rpcUser.password).use {
action(it.proxy)
}
}
-}
\ No newline at end of file
+}
diff --git a/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt b/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt
index 7b4801b1128..14ba9b21c01 100644
--- a/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt
+++ b/core/src/main/kotlin/net/corda/core/node/services/KeyManagementService.kt
@@ -2,11 +2,15 @@ package net.corda.core.node.services
import co.paralleluniverse.fibers.Suspendable
import net.corda.core.DoNotImplement
+import net.corda.core.crypto.CompositeKey
import net.corda.core.crypto.DigitalSignature
import net.corda.core.crypto.SignableData
import net.corda.core.crypto.TransactionSignature
import net.corda.core.identity.PartyAndCertificate
+import java.security.KeyPair
+import java.security.PrivateKey
import java.security.PublicKey
+import java.security.cert.X509Certificate
/**
* The KMS is responsible for storing and using private keys to sign things. An implementation of this may, for example,
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 6e6e7ea34f7..a4f7391f404 100644
--- a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt
+++ b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt
@@ -122,7 +122,7 @@ object MappedSchemaValidator {
fieldsFromOtherMappedSchema(schema) + methodsFromOtherMappedSchema(schema)
/** Returns true if [javax.persistence] annotation expect [javax.persistence.Transient] is found. */
- private inline fun hasJpaAnnotation(annotations: Array) =
+ private fun hasJpaAnnotation(annotations: Array) =
annotations.any { annotation -> annotation.toString().startsWith("@javax.persistence.") && annotation !is javax.persistence.Transient }
class SchemaCrossReferenceReport(private val schema: String, private val entity: String, private val referencedSchema: String,
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 6f4a63b8988..e3697f9d00a 100644
--- a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt
+++ b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt
@@ -48,7 +48,7 @@ class WireTransaction(componentGroups: List, val privacySalt: Pr
@DeleteForDJVM
constructor(componentGroups: List) : this(componentGroups, PrivacySalt())
- @Deprecated("Required only in some unit-tests and for backwards compatibility purposes.", ReplaceWith("WireTransaction(val componentGroups: List, override val privacySalt: PrivacySalt)"), DeprecationLevel.WARNING)
+ @Deprecated("Required only for backwards compatibility purposes.", ReplaceWith("WireTransaction(val componentGroups: List, override val privacySalt: PrivacySalt)"), DeprecationLevel.WARNING)
@DeleteForDJVM
constructor(inputs: List,
attachments: List,
diff --git a/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt b/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt
index bfb54e5e78f..57320d7eb9f 100644
--- a/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt
+++ b/core/src/test/kotlin/net/corda/core/contracts/ContractsDSLTests.kt
@@ -31,7 +31,8 @@ class ContractsDSLTests {
}
@RunWith(Parameterized::class)
- class RequireSingleCommandTests(private val testFunction: (Collection>) -> CommandWithParties, description: String) {
+ class RequireSingleCommandTests(private val testFunction: (Collection>) -> CommandWithParties,
+ @Suppress("UNUSED_PARAMETER") description: String) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{1}")
@@ -64,7 +65,8 @@ class ContractsDSLTests {
}
@RunWith(Parameterized::class)
- class SelectWithSingleInputsTests(private val testFunction: (Collection>, PublicKey?, AbstractParty?) -> Iterable>, description: String) {
+ class SelectWithSingleInputsTests(private val testFunction: (Collection>, PublicKey?, AbstractParty?) -> Iterable>,
+ @Suppress("UNUSED_PARAMETER") description: String) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{1}")
@@ -112,7 +114,8 @@ class ContractsDSLTests {
}
@RunWith(Parameterized::class)
- class SelectWithMultipleInputsTests(private val testFunction: (Collection>, Collection?, Collection?) -> Iterable>, description: String) {
+ class SelectWithMultipleInputsTests(private val testFunction: (Collection>, Collection?, Collection?) -> Iterable>,
+ @Suppress("UNUSED_PARAMETER") description: String) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{1}")
diff --git a/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt b/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt
index 3c7275a819f..70648b07be8 100644
--- a/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt
+++ b/core/src/test/kotlin/net/corda/core/crypto/PartialMerkleTreeTest.kt
@@ -20,6 +20,7 @@ import net.corda.testing.dsl.LedgerDSL
import net.corda.testing.dsl.TestLedgerDSLInterpreter
import net.corda.testing.dsl.TestTransactionDSLInterpreter
import net.corda.testing.internal.TEST_TX_TIME
+import net.corda.testing.internal.createWireTransaction
import net.corda.testing.internal.rigorousMock
import net.corda.testing.node.MockServices
import net.corda.testing.node.ledger
@@ -264,7 +265,7 @@ class PartialMerkleTreeTest {
timeWindow: TimeWindow? = null,
attachments: List = emptyList()
): WireTransaction {
- return WireTransaction(
+ return createWireTransaction(
inputs = testTx.inputs,
attachments = attachments,
outputs = testTx.outputs,
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 06f3907b215..6029897303f 100644
--- a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt
+++ b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt
@@ -57,7 +57,7 @@ class AttachmentTests {
bobNode.registerInitiatedFlow(FetchAttachmentsResponse::class.java)
// Insert an attachment into node zero's store directly.
val id = aliceNode.database.transaction {
- aliceNode.attachments.importAttachment(fakeAttachment().inputStream())
+ aliceNode.attachments.importAttachment(fakeAttachment().inputStream(), "test", null)
}
// Get node one to run a flow to fetch it and insert it.
@@ -110,7 +110,7 @@ class AttachmentTests {
val attachment = fakeAttachment()
// Insert an attachment into node zero's store directly.
val id = aliceNode.database.transaction {
- aliceNode.attachments.importAttachment(attachment.inputStream())
+ aliceNode.attachments.importAttachment(attachment.inputStream(), "test", null)
}
// Corrupt its store.
diff --git a/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt b/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt
index b6529591562..8172bbc9bea 100644
--- a/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt
+++ b/core/src/test/kotlin/net/corda/core/internal/ResolveTransactionsFlowTest.kt
@@ -146,7 +146,7 @@ class ResolveTransactionsFlowTest {
}
// TODO: this operation should not require an explicit transaction
val id = megaCorpNode.transaction {
- megaCorpNode.services.attachments.importAttachment(makeJar())
+ megaCorpNode.services.attachments.importAttachment(makeJar(), "test", null)
}
val stx2 = makeTransactions(withAttachment = id).second
val p = TestFlow(stx2, megaCorp)
@@ -201,6 +201,7 @@ class ResolveTransactionsFlowTest {
}
}
+ @Suppress("unused")
@InitiatedBy(TestFlow::class)
private class TestResponseFlow(val otherSideSession: FlowSession) : FlowLogic() {
@Suspendable
diff --git a/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt b/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt
index 1c4f76cad90..6237a1a0194 100644
--- a/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt
+++ b/core/src/test/kotlin/net/corda/core/internal/TopologicalSortTest.kt
@@ -21,10 +21,10 @@ import rx.Observable
import java.util.*
class TopologicalSortTest {
- class DummyTransaction(
+ class DummyTransaction constructor(
override val id: SecureHash,
override val inputs: List,
- val numberOfOutputs: Int,
+ @Suppress("CanBeParameter") private val numberOfOutputs: Int,
override val notary: Party
) : CoreTransaction() {
override val outputs: List> = (1..numberOfOutputs).map {
@@ -78,7 +78,7 @@ class TopologicalSortTest {
}
// Swap two random items
- transactions.combine(Generator.intRange(0, N - 1), Generator.intRange(0, N - 2)) { txs, i, j ->
+ transactions.combine(Generator.intRange(0, N - 1), Generator.intRange(0, N - 2)) { txs, i, _ ->
val k = 0 // if (i == j) i + 1 else j
val tmp = txs[i]
txs[i] = txs[k]
@@ -94,7 +94,7 @@ class TopologicalSortTest {
}
}
- fun checkTopologicallyOrdered(txs: List) {
+ private fun checkTopologicallyOrdered(txs: List) {
val outputs = HashSet()
for (tx in txs) {
if (!outputs.containsAll(tx.inputs)) {
diff --git a/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt b/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt
index cbda60638f5..3f6f40bf513 100644
--- a/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt
+++ b/core/src/test/kotlin/net/corda/core/transactions/TransactionTests.kt
@@ -8,6 +8,7 @@ import net.corda.core.crypto.CompositeKey
import net.corda.core.identity.Party
import net.corda.testing.contracts.DummyContract
import net.corda.testing.core.*
+import net.corda.testing.internal.createWireTransaction
import net.corda.testing.internal.rigorousMock
import org.junit.Rule
import org.junit.Test
@@ -53,7 +54,7 @@ class TransactionTests {
val cpub = ck.public
val c1 = CompositeKey.Builder().addKeys(apub, bpub).build(2)
val compKey = CompositeKey.Builder().addKeys(c1, cpub).build(1)
- val wtx = WireTransaction(
+ val wtx = createWireTransaction(
inputs = listOf(StateRef(SecureHash.randomSHA256(), 0)),
attachments = emptyList(),
outputs = emptyList(),
@@ -79,7 +80,7 @@ class TransactionTests {
@Test
fun `signed transaction missing signatures`() {
- val wtx = WireTransaction(
+ val wtx = createWireTransaction(
inputs = listOf(StateRef(SecureHash.randomSHA256(), 0)),
attachments = emptyList(),
outputs = emptyList(),
@@ -119,8 +120,8 @@ class TransactionTests {
}, DummyContract.PROGRAM_ID))
val id = SecureHash.randomSHA256()
val timeWindow: TimeWindow? = null
- val privacySalt: PrivacySalt = PrivacySalt()
- val transaction: LedgerTransaction = LedgerTransaction(
+ val privacySalt = PrivacySalt()
+ val transaction = LedgerTransaction(
inputs,
outputs,
commands,
@@ -137,7 +138,7 @@ class TransactionTests {
@Test
fun `transaction cannot have duplicate inputs`() {
val stateRef = StateRef(SecureHash.randomSHA256(), 0)
- fun buildTransaction() = WireTransaction(
+ fun buildTransaction() = createWireTransaction(
inputs = listOf(stateRef, stateRef),
attachments = emptyList(),
outputs = emptyList(),
@@ -160,7 +161,7 @@ class TransactionTests {
val attachments = emptyList()
val id = SecureHash.randomSHA256()
val timeWindow: TimeWindow? = null
- val privacySalt: PrivacySalt = PrivacySalt()
+ val privacySalt = PrivacySalt()
fun buildTransaction() = LedgerTransaction(
inputs,
outputs,
@@ -178,7 +179,7 @@ class TransactionTests {
@Test
fun `transactions with identical contents must have different ids`() {
val outputState = TransactionState(DummyContract.SingleOwnerState(0, ALICE), DummyContract.PROGRAM_ID, DUMMY_NOTARY)
- fun buildTransaction() = WireTransaction(
+ fun buildTransaction() = createWireTransaction(
inputs = emptyList(),
attachments = emptyList(),
outputs = listOf(outputState),
diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt
index 8cc5f3ab61b..093b4bc8d0c 100644
--- a/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt
+++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/ClientRpcTutorial.kt
@@ -40,6 +40,7 @@ enum class PrintOrVisualise {
Visualise
}
+@Suppress("DEPRECATION")
fun main(args: Array) {
require(args.isNotEmpty()) { "Usage: [Print|Visualise]" }
val printOrVisualise = PrintOrVisualise.valueOf(args[0])
@@ -99,6 +100,7 @@ fun main(args: Array) {
}
}
// END 5
+ Unit
}
}
diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt
index 40f74879469..c2b20467246 100644
--- a/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt
+++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/FlowCookbook.kt
@@ -1,4 +1,4 @@
-@file:Suppress("UNUSED_VARIABLE", "unused")
+@file:Suppress("UNUSED_VARIABLE", "unused", "DEPRECATION")
package net.corda.docs
diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt
index e6826fa2136..8e94e82b32f 100644
--- a/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt
+++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/LaunchSpaceshipFlow.kt
@@ -1,3 +1,5 @@
+@file:Suppress("DEPRECATION")
+
package net.corda.docs
import co.paralleluniverse.fibers.Suspendable
diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt
index 0635c136f37..d4f67c02a0c 100644
--- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt
+++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/tearoffs/TutorialTearOffs.kt
@@ -1,3 +1,5 @@
+@file:Suppress("UNUSED_VARIABLE")
+
package net.corda.docs.tutorial.tearoffs
import net.corda.core.contracts.Command
@@ -42,4 +44,4 @@ fun main(args: Array) {
} catch (e: FilteredTransactionVerificationException) {
throw MerkleTreeException("Rate Fix Oracle: Couldn't verify partial Merkle tree.")
}
-}
\ No newline at end of file
+}
diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt
index 71f3dca79bb..6af97417eb9 100644
--- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt
+++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Substeps.kt
@@ -2,22 +2,21 @@ package net.corda.behave.scenarios.helpers
import net.corda.behave.scenarios.ScenarioState
import net.corda.core.messaging.CordaRPCOps
-import net.corda.core.utilities.contextLogger
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
abstract class Substeps(protected val state: ScenarioState) {
+ protected val log: Logger = LoggerFactory.getLogger(javaClass)
- protected val log = contextLogger()
-
- protected fun withNetwork(action: ScenarioState.() -> Unit) =
- state.withNetwork(action)
+ protected fun withNetwork(action: ScenarioState.() -> Unit) = state.withNetwork(action)
protected fun withClient(nodeName: String, action: ScenarioState.(CordaRPCOps) -> T): T {
- return state.withClient(nodeName, {
- return@withClient try {
+ return state.withClient(nodeName) {
+ try {
action(state, it)
} catch (ex: Exception) {
- state.error(ex.message ?: "Failed to execute RPC call")
+ state.error(ex.message ?: "Failed to execute RPC call")
}
- })
+ }
}
-}
\ No newline at end of file
+}
diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt
index 0d560b4b743..747c82cdaed 100644
--- a/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt
+++ b/experimental/behave/src/test/kotlin/net/corda/behave/process/CommandTests.kt
@@ -5,7 +5,6 @@ import org.junit.Test
import rx.observers.TestSubscriber
class CommandTests {
-
@Test
fun `successful command returns zero`() {
val exitCode = Command(listOf("ls", "/")).run()
@@ -21,7 +20,7 @@ class CommandTests {
@Test
fun `output stream for command can be observed`() {
val subscriber = TestSubscriber()
- val exitCode = Command(listOf("ls", "/")).use(subscriber) { _, output ->
+ val exitCode = Command(listOf("ls", "/")).use(subscriber) { _, _ ->
subscriber.awaitTerminalEvent()
subscriber.assertCompleted()
subscriber.assertNoErrors()
diff --git a/experimental/kryo-hook/build.gradle b/experimental/kryo-hook/build.gradle
index 040b2e5f805..ab36a754b62 100644
--- a/experimental/kryo-hook/build.gradle
+++ b/experimental/kryo-hook/build.gradle
@@ -3,7 +3,6 @@ ext {
}
apply plugin: 'kotlin'
-apply plugin: 'kotlin-kapt'
apply plugin: 'idea'
description 'A javaagent to allow hooking into Kryo'
diff --git a/experimental/quasar-hook/build.gradle b/experimental/quasar-hook/build.gradle
index c2387079a83..dfe49fa9703 100644
--- a/experimental/quasar-hook/build.gradle
+++ b/experimental/quasar-hook/build.gradle
@@ -3,7 +3,6 @@ ext {
}
apply plugin: 'kotlin'
-apply plugin: 'kotlin-kapt'
apply plugin: 'idea'
description 'A javaagent to allow hooking into the instrumentation by Quasar'
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 3632bfa6a72..9c043ffd483 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
@@ -2,12 +2,12 @@ package net.corda.finance.contracts.universal
import net.corda.core.crypto.toStringShort
import net.corda.core.identity.Party
+import net.corda.core.internal.uncheckedCast
import java.math.BigDecimal
import java.security.PublicKey
import java.time.Instant
private class PrettyPrint(arr : Arrangement) {
-
val parties = involvedParties(arr)
private val sb = StringBuilder()
@@ -16,21 +16,21 @@ private class PrettyPrint(arr : Arrangement) {
private var atStart = true
private fun print(msg: String) {
if (atStart)
- repeat(indentLevel, { sb.append(' ') })
+ repeat(indentLevel) { sb.append(' ') }
sb.append(msg)
atStart = false
}
private fun println(message: Any?) {
if (atStart)
- repeat(indentLevel, { sb.append(' ') })
+ repeat(indentLevel) { sb.append(' ') }
sb.appendln(message)
atStart = true
}
private fun print(msg: Any?) {
if (atStart)
- repeat(indentLevel, { sb.append(' ') })
+ repeat(indentLevel) { sb.append(' ') }
sb.append(msg)
atStart = false
}
@@ -45,8 +45,7 @@ private class PrettyPrint(arr : Arrangement) {
val partyMap = mutableMapOf()
val usedPartyNames = mutableSetOf()
- fun createPartyName(party : Party) : String
- {
+ fun createPartyName(party : Party): String {
val parts = party.name.organisation.toLowerCase().split(' ')
var camelName = parts.drop(1).fold(parts.first()) {
@@ -69,38 +68,38 @@ private class PrettyPrint(arr : Arrangement) {
}
}
- fun prettyPrint(per: Perceivable, x: Boolean? = null) {
+ fun prettyPrintBoolean(per: Perceivable) {
when (per) {
is Const -> print("\"${per.value}\"")
is PerceivableOr -> {
- prettyPrint(per.left)
+ prettyPrintBoolean(per.left)
print(" or ")
- prettyPrint(per.right)
+ prettyPrintBoolean(per.right)
}
is PerceivableAnd -> {
- prettyPrint(per.left)
+ prettyPrintBoolean(per.left)
print(" and ")
- prettyPrint(per.right)
+ prettyPrintBoolean(per.right)
}
is TimePerceivable -> {
when (per.cmp) {
Comparison.GT, Comparison.GTE -> {
print("after(")
- prettyPrint(per.instant)
+ prettyPrintInstant(per.instant)
print(")")
}
Comparison.LT, Comparison.LTE -> {
print("before(")
- prettyPrint(per.instant)
+ prettyPrintInstant(per.instant)
print(")")
}
}
}
is PerceivableComparison<*> -> {
when (per.type) {
- BigDecimal::class.java -> prettyPrint(per.left as Perceivable)
- Instant::class.java -> prettyPrint(per.left as Perceivable)
- Boolean::class.java -> prettyPrint(per.left as Perceivable)
+ BigDecimal::class.java -> prettyPrintBigDecimal(uncheckedCast(per.left))
+ Instant::class.java -> prettyPrintInstant(uncheckedCast(per.left))
+ Boolean::class.java -> prettyPrintBoolean(uncheckedCast(per.left))
}
when (per.cmp) {
Comparison.GT -> print(" > ")
@@ -109,9 +108,9 @@ private class PrettyPrint(arr : Arrangement) {
Comparison.LTE -> print(" <= ")
}
when (per.type) {
- BigDecimal::class.java -> prettyPrint(per.right as Perceivable)
- Instant::class.java -> prettyPrint(per.right as Perceivable)
- Boolean::class.java -> prettyPrint(per.right as Perceivable)
+ BigDecimal::class.java -> prettyPrintBigDecimal(uncheckedCast(per.right))
+ Instant::class.java -> prettyPrintInstant(uncheckedCast(per.right))
+ Boolean::class.java -> prettyPrintBoolean(uncheckedCast(per.right))
}
}
is TerminalEvent -> print("TerminalEvent(${partyMap[per.reference.owningKey]}, \"${per.source}\")")
@@ -120,7 +119,7 @@ private class PrettyPrint(arr : Arrangement) {
}
}
- fun prettyPrint(per: Perceivable, x: Instant? = null) {
+ fun prettyPrintInstant(per: Perceivable) {
when (per) {
is Const -> print("\"${per.value}\"")
is StartDate -> print("startDate")
@@ -129,34 +128,33 @@ private class PrettyPrint(arr : Arrangement) {
}
}
- fun prettyPrint(per: Perceivable, x: BigDecimal? = null) {
+ fun prettyPrintBigDecimal(per: Perceivable) {
when (per) {
is PerceivableOperation -> {
- prettyPrint(per.left)
+ prettyPrintBigDecimal(per.left)
when (per.op) {
Operation.PLUS -> print(" + ")
Operation.MINUS -> print(" - ")
Operation.DIV -> print(" / ")
Operation.TIMES -> print(" * ")
- else -> print(per.op)
}
- prettyPrint(per.right)
+ prettyPrintBigDecimal(per.right)
}
is UnaryPlus -> {
print("(")
- prettyPrint(per.arg)
+ prettyPrintBigDecimal(per.arg)
print(".).plus()")
}
is Const -> print(per.value)
is Interest -> {
print("Interest(")
- prettyPrint(per.amount)
+ prettyPrintBigDecimal(per.amount)
print(", \"${per.dayCountConvention}\", ")
- prettyPrint(per.amount)
+ prettyPrintBigDecimal(per.amount)
print(", ")
- prettyPrint(per.start)
+ prettyPrintInstant(per.start)
print(", ")
- prettyPrint(per.end)
+ prettyPrintInstant(per.end)
print(")")
}
is CurrencyCross -> print("${per.foreign}/${per.domestic}")
@@ -165,7 +163,6 @@ private class PrettyPrint(arr : Arrangement) {
}
fun prettyPrint(arr: Arrangement) {
-
when (arr) {
is Zero -> println("zero")
is RollOut -> {
@@ -183,7 +180,7 @@ private class PrettyPrint(arr : Arrangement) {
is Continuation -> println("next()")
is Obligation -> {
print("${partyMap[arr.from.owningKey]}.gives( ${partyMap[arr.to.owningKey]}, ")
- prettyPrint(arr.amount)
+ prettyPrintBigDecimal(arr.amount)
println(", ${arr.currency})")
}
is Actions -> {
@@ -191,7 +188,7 @@ private class PrettyPrint(arr : Arrangement) {
indent {
for ((name, condition, arrangement) in arr.actions) {
print("\"$name\".givenThat(")
- prettyPrint(condition)
+ prettyPrintBoolean(condition)
println(") {")
indent {
prettyPrint(arrangement)
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 ef37f3114b0..f73805b9672 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
@@ -36,46 +36,45 @@ class UniversalContract : Contract {
class Split(val ratio: BigDecimal) : Commands
}
- fun eval(@Suppress("UNUSED_PARAMETER") tx: LedgerTransaction, expr: Perceivable): Instant? = when (expr) {
+ fun evalInstant(expr: Perceivable): Instant? = when (expr) {
is Const -> expr.value
is StartDate -> null
is EndDate -> null
else -> throw Error("Unable to evaluate")
}
- fun eval(tx: LedgerTransaction, expr: Perceivable): Boolean = when (expr) {
- is PerceivableAnd -> eval(tx, expr.left) && eval(tx, expr.right)
- is PerceivableOr -> eval(tx, expr.left) || eval(tx, expr.right)
+ fun evalBoolean(tx: LedgerTransaction, expr: Perceivable): Boolean = when (expr) {
+ is PerceivableAnd -> evalBoolean(tx, expr.left) && evalBoolean(tx, expr.right)
+ is PerceivableOr -> evalBoolean(tx, expr.left) || evalBoolean(tx, expr.right)
is Const -> expr.value
is TimePerceivable -> when (expr.cmp) {
- Comparison.LTE -> tx.timeWindow!!.fromTime!! <= eval(tx, expr.instant)
- Comparison.GTE -> tx.timeWindow!!.untilTime!! >= eval(tx, expr.instant)
+ Comparison.LTE -> tx.timeWindow!!.fromTime!! <= evalInstant(expr.instant)
+ Comparison.GTE -> tx.timeWindow!!.untilTime!! >= evalInstant(expr.instant)
else -> throw NotImplementedError("eval special")
}
is ActorPerceivable -> tx.commands.single().signers.contains(expr.actor.owningKey)
else -> throw NotImplementedError("eval - Boolean - " + expr.javaClass.name)
}
- fun eval(tx: LedgerTransaction, expr: Perceivable): BigDecimal =
+ fun evalBigDecimal(tx: LedgerTransaction, expr: Perceivable): BigDecimal =
when (expr) {
is Const -> expr.value
is UnaryPlus -> {
- val x = eval(tx, expr.arg)
+ val x = evalBigDecimal(tx, expr.arg)
if (x > BigDecimal.ZERO)
x
else
BigDecimal.ZERO
}
is PerceivableOperation -> {
- val l = eval(tx, expr.left)
- val r = eval(tx, expr.right)
+ val l = evalBigDecimal(tx, expr.left)
+ val r = evalBigDecimal(tx, expr.right)
when (expr.op) {
Operation.DIV -> l / r
Operation.MINUS -> l - r
Operation.PLUS -> l + r
Operation.TIMES -> l * r
- else -> throw NotImplementedError("eval - amount - operation " + expr.op)
}
}
is Fixing -> {
@@ -83,8 +82,8 @@ class UniversalContract : Contract {
0.0.bd
}
is Interest -> {
- val a = eval(tx, expr.amount)
- val i = eval(tx, expr.interest)
+ val a = evalBigDecimal(tx, expr.amount)
+ val i = evalBigDecimal(tx, expr.interest)
//TODO
@@ -95,7 +94,7 @@ class UniversalContract : Contract {
fun validateImmediateTransfers(tx: LedgerTransaction, arrangement: Arrangement): Arrangement = when (arrangement) {
is Obligation -> {
- val amount = eval(tx, arrangement.amount)
+ val amount = evalBigDecimal(tx, arrangement.amount)
requireThat { "transferred quantity is non-negative" using (amount >= BigDecimal.ZERO) }
Obligation(const(amount), arrangement.currency, arrangement.from, arrangement.to)
}
@@ -210,7 +209,7 @@ class UniversalContract : Contract {
"action must have a time-window" using (tx.timeWindow != null)
// "action must be authorized" by (cmd.signers.any { action.actors.any { party -> party.owningKey == it } })
// todo perhaps merge these two requirements?
- "condition must be met" using (eval(tx, action.condition))
+ "condition must be met" using evalBoolean(tx, action.condition)
}
// verify that any resulting transfers can be resolved
@@ -287,7 +286,7 @@ class UniversalContract : Contract {
perceivable.dayCountConvention, replaceFixing(tx, perceivable.interest, fixings, unusedFixings),
perceivable.start, perceivable.end))
is Fixing -> {
- val dt = eval(tx, perceivable.date)
+ val dt = evalInstant(perceivable.date)
if (dt != null && fixings.containsKey(FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor))) {
unusedFixings.remove(FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor))
uncheckedCast(Const(fixings[FixOf(perceivable.source, dt.toLocalDate(), perceivable.tenor)]!!))
diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt
index 1205a649470..52a85cc5d21 100644
--- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt
+++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/IRS.kt
@@ -14,13 +14,12 @@ class IRS {
@Rule
@JvmField
val testSerialization = SerializationEnvironmentRule()
- val TEST_TX_TIME_1: Instant get() = Instant.parse("2017-09-02T12:00:00.00Z")
- val notional = 50.M
- val currency = EUR
-
- val tradeDate: LocalDate = LocalDate.of(2016, 9, 1)
+ private val testTxTime1: Instant = Instant.parse("2017-09-02T12:00:00.00Z")
+ private val notional = 50.M
+ private val currency = EUR
+ private val tradeDate: LocalDate = LocalDate.of(2016, 9, 1)
/*
@@ -33,7 +32,7 @@ class IRS {
*/
- val contractInitial = arrange {
+ private val contractInitial = arrange {
rollOut("2016-09-01".ld, "2018-09-01".ld, Frequency.Quarterly) {
actions {
(acmeCorp or highStreetBank) may {
@@ -52,7 +51,8 @@ class IRS {
}
}
}
- val contractAfterFixingFirst = arrange {
+
+ private val contractAfterFixingFirst = arrange {
actions {
(acmeCorp or highStreetBank) may {
val floating = interest(notional, "act/365", 1.0.bd, "2016-09-01", "2016-12-01")
@@ -83,15 +83,15 @@ class IRS {
rollOut("2016-12-01".ld, "2018-09-01".ld, Frequency.Quarterly) {
actions {
(acmeCorp or highStreetBank) may {
- val floating = interest(notional, "act/365", fix("LIBOR", start, Tenor("3M")), start, end)
- val fixed = interest(notional, "act/365", 0.5.bd, start, end)
+ val nextFloating = interest(notional, "act/365", fix("LIBOR", start, Tenor("3M")), start, end)
+ val nextFixed = interest(notional, "act/365", 0.5.bd, start, end)
"pay floating" anytime {
- highStreetBank.owes(acmeCorp, floating - fixed, currency)
+ highStreetBank.owes(acmeCorp, nextFloating - nextFixed, currency)
next()
}
"pay fixed" anytime {
- highStreetBank.owes(acmeCorp, fixed - floating, currency)
+ highStreetBank.owes(acmeCorp, nextFixed - nextFloating, currency)
next()
}
}
@@ -102,7 +102,7 @@ class IRS {
}
}
- val contractAfterExecutionFirst = arrange {
+ private val contractAfterExecutionFirst = arrange {
rollOut("2016-12-01".ld, "2018-09-01".ld, Frequency.Quarterly) {
actions {
(acmeCorp or highStreetBank) may {
@@ -122,19 +122,20 @@ class IRS {
}
}
- val paymentFirst = arrange { highStreetBank.owes(acmeCorp, 250.K, EUR) }
+ private val paymentFirst = arrange { highStreetBank.owes(acmeCorp, 250.K, EUR) }
+
+ private val stateInitial = UniversalContract.State(listOf(DUMMY_NOTARY), contractInitial)
- val stateInitial = UniversalContract.State(listOf(DUMMY_NOTARY), contractInitial)
+ private val stateAfterFixingFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterFixingFirst)
+ private val stateAfterExecutionFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterExecutionFirst)
- val stateAfterFixingFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterFixingFirst)
- val stateAfterExecutionFirst = UniversalContract.State(listOf(DUMMY_NOTARY), contractAfterExecutionFirst)
+ private val statePaymentFirst = UniversalContract.State(listOf(DUMMY_NOTARY), paymentFirst)
- val statePaymentFirst = UniversalContract.State(listOf(DUMMY_NOTARY), paymentFirst)
@Test
fun issue() {
transaction {
output(UNIVERSAL_PROGRAM_ID, stateInitial)
- timeWindow(TEST_TX_TIME_1)
+ timeWindow(testTxTime1)
tweak {
command(acmeCorp.owningKey, UniversalContract.Commands.Issue())
@@ -150,7 +151,7 @@ class IRS {
transaction {
input(UNIVERSAL_PROGRAM_ID, stateInitial)
output(UNIVERSAL_PROGRAM_ID, stateAfterFixingFirst)
- timeWindow(TEST_TX_TIME_1)
+ timeWindow(testTxTime1)
tweak {
command(highStreetBank.owningKey, UniversalContract.Commands.Action("some undefined name"))
@@ -190,7 +191,7 @@ class IRS {
input(UNIVERSAL_PROGRAM_ID, stateAfterFixingFirst)
output(UNIVERSAL_PROGRAM_ID, stateAfterExecutionFirst)
output(UNIVERSAL_PROGRAM_ID, statePaymentFirst)
- timeWindow(TEST_TX_TIME_1)
+ timeWindow(testTxTime1)
tweak {
command(highStreetBank.owningKey, UniversalContract.Commands.Action("some undefined name"))
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 3750d76ef22..7f0972a175b 100644
--- a/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt
+++ b/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt
@@ -47,6 +47,7 @@ class AuthDBTests : NodeBasedTest() {
fun encFormats() = arrayOf(PasswordEncryption.NONE, PasswordEncryption.SHIRO_1_CRYPT)
}
+ @Suppress("MemberVisibilityCanBePrivate")
@Parameterized.Parameter
lateinit var passwordEncryption: PasswordEncryption
@@ -94,7 +95,7 @@ class AuthDBTests : NodeBasedTest() {
)
node = startNode(ALICE_NAME, rpcUsers = emptyList(), configOverrides = securityConfig)
- client = CordaRPCClient(node.internals.configuration.rpcOptions.address!!)
+ client = CordaRPCClient(node.internals.configuration.rpcOptions.address)
}
@Test
@@ -227,9 +228,8 @@ private data class RoleAndPermissions(val role: String, val permissions: List = emptyList(), roleAndPermissions: List = emptyList()) : AutoCloseable {
+ val jdbcUrl = "jdbc:h2:mem:$name;DB_CLOSE_DELAY=-1"
companion object {
const val DB_CREATE_SCHEMA = """
@@ -279,11 +279,7 @@ private class UsersDB : AutoCloseable {
}
}
- constructor(name: String,
- users: List = emptyList(),
- roleAndPermissions: List = emptyList()) {
-
- jdbcUrl = "jdbc:h2:mem:$name;DB_CLOSE_DELAY=-1"
+ init {
dataSource = DataSourceFactory.createDataSource(Properties().apply {
put("dataSourceClassName", "org.h2.jdbcx.JdbcDataSource")
put("dataSource.url", jdbcUrl)
@@ -291,11 +287,9 @@ private class UsersDB : AutoCloseable {
session {
it.execute(DB_CREATE_SCHEMA)
}
-
require(users.map { it.username }.toSet().size == users.size) {
"Duplicate username in input"
}
-
users.forEach { insert(it) }
roleAndPermissions.forEach { insert(it) }
}
diff --git a/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt b/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt
index 1e751a1658e..6f0246660dd 100644
--- a/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt
+++ b/node/src/integration-test/kotlin/net/corda/node/utilities/registration/NodeRegistrationTest.kt
@@ -20,7 +20,6 @@ import net.corda.testing.core.singleIdentity
import net.corda.testing.driver.PortAllocation
import net.corda.testing.internal.DEV_ROOT_CA
import net.corda.testing.node.NotarySpec
-import net.corda.testing.node.internal.CompatibilityZoneParams
import net.corda.testing.node.internal.SharedCompatibilityZoneParams
import net.corda.testing.node.internal.internalDriver
import net.corda.testing.node.internal.network.NetworkMapServer
@@ -51,7 +50,6 @@ class NodeRegistrationTest {
private val notaryName = CordaX500Name("NotaryService", "Zurich", "CH")
private val aliceName = CordaX500Name("Alice", "London", "GB")
private val genevieveName = CordaX500Name("Genevieve", "London", "GB")
- private val log = contextLogger()
}
@Rule
@@ -69,7 +67,7 @@ class NodeRegistrationTest {
pollInterval = 1.seconds,
hostAndPort = portAllocation.nextHostAndPort(),
myHostNameValue = "localhost",
- additionalServices = registrationHandler)
+ additionalServices = *arrayOf(registrationHandler))
serverHostAndPort = server.start()
}
diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt
index 8bc80d99b7b..6325ff723e3 100644
--- a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt
+++ b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsNodeTest.kt
@@ -68,7 +68,7 @@ class MQSecurityAsNodeTest : P2PMQSecurityTest() {
@Test
fun `login to a non ssl port as a node user`() {
- val attacker = clientTo(alice.internals.configuration.rpcOptions.address!!, sslConfiguration = null)
+ val attacker = clientTo(alice.internals.configuration.rpcOptions.address, sslConfiguration = null)
assertThatExceptionOfType(ActiveMQSecurityException::class.java).isThrownBy {
attacker.start(NODE_P2P_USER, NODE_P2P_USER, enableSSL = false)
}
@@ -76,7 +76,7 @@ class MQSecurityAsNodeTest : P2PMQSecurityTest() {
@Test
fun `login to a non ssl port as a peer user`() {
- val attacker = clientTo(alice.internals.configuration.rpcOptions.address!!, sslConfiguration = null)
+ val attacker = clientTo(alice.internals.configuration.rpcOptions.address, sslConfiguration = null)
assertThatExceptionOfType(ActiveMQSecurityException::class.java).isThrownBy {
attacker.start(PEER_USER, PEER_USER, enableSSL = false) // Login as a peer
}
diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt
index e06d21eee66..9eee5fd05de 100644
--- a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt
+++ b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityAsRPCTest.kt
@@ -8,7 +8,7 @@ import org.junit.Test
*/
class MQSecurityAsRPCTest : RPCMQSecurityTest() {
override fun createAttacker(): SimpleMQClient {
- return clientTo(alice.internals.configuration.rpcOptions.address!!)
+ return clientTo(alice.internals.configuration.rpcOptions.address)
}
@Test
diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt
index 44da2d4e7ec..179fe0b7f08 100644
--- a/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt
+++ b/node/src/integration-test/kotlin/net/corda/services/messaging/MQSecurityTest.kt
@@ -29,6 +29,7 @@ import net.corda.testing.node.internal.NodeBasedTest
import net.corda.testing.node.internal.startFlow
import org.apache.activemq.artemis.api.core.ActiveMQNonExistentQueueException
import org.apache.activemq.artemis.api.core.ActiveMQSecurityException
+import org.apache.activemq.artemis.api.core.RoutingType
import org.apache.activemq.artemis.api.core.SimpleString
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.After
@@ -111,9 +112,9 @@ abstract class MQSecurityTest : NodeBasedTest() {
}
fun loginToRPCAndGetClientQueue(): String {
- loginToRPC(alice.internals.configuration.rpcOptions.address!!, rpcUser)
+ loginToRPC(alice.internals.configuration.rpcOptions.address, rpcUser)
val clientQueueQuery = SimpleString("${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.${rpcUser.username}.*")
- val client = clientTo(alice.internals.configuration.rpcOptions.address!!)
+ val client = clientTo(alice.internals.configuration.rpcOptions.address)
client.start(rpcUser.username, rpcUser.password, false)
return client.session.addressQuery(clientQueueQuery).queueNames.single().toString()
}
@@ -126,7 +127,7 @@ abstract class MQSecurityTest : NodeBasedTest() {
fun assertTempQueueCreationAttackFails(queue: String) {
assertAttackFails(queue, "CREATE_NON_DURABLE_QUEUE") {
- attacker.session.createTemporaryQueue(queue, queue)
+ attacker.session.createTemporaryQueue(queue, RoutingType.MULTICAST, queue)
}
// Double-check
assertThatExceptionOfType(ActiveMQNonExistentQueueException::class.java).isThrownBy {
@@ -143,7 +144,7 @@ abstract class MQSecurityTest : NodeBasedTest() {
fun assertNonTempQueueCreationAttackFails(queue: String, durable: Boolean) {
val permission = if (durable) "CREATE_DURABLE_QUEUE" else "CREATE_NON_DURABLE_QUEUE"
assertAttackFails(queue, permission) {
- attacker.session.createQueue(queue, queue, durable)
+ attacker.session.createQueue(queue, RoutingType.MULTICAST, queue, durable)
}
// Double-check
assertThatExceptionOfType(ActiveMQNonExistentQueueException::class.java).isThrownBy {
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 46e889e06f8..b4de9fbea42 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
@@ -4,11 +4,10 @@ import com.typesafe.config.Config
import com.typesafe.config.ConfigException
import net.corda.core.context.AuthServiceId
import net.corda.core.identity.CordaX500Name
-import net.corda.core.internal.div
+import net.corda.core.internal.TimedFlow
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.loggerFor
import net.corda.core.utilities.seconds
-import net.corda.node.internal.artemis.CertificateChainCheckPolicy
import net.corda.node.services.config.rpc.NodeRpcOptions
import net.corda.nodeapi.BrokerRpcSslOptions
import net.corda.nodeapi.internal.config.NodeSSLConfiguration
@@ -40,6 +39,7 @@ interface NodeConfiguration : NodeSSLConfiguration {
val devModeOptions: DevModeOptions?
val compatibilityZoneURL: URL?
val networkServices: NetworkServicesConfig?
+ @Suppress("DEPRECATION")
val certificateChainCheckPolicies: List
val verifierType: VerifierType
val flowTimeout: FlowTimeoutConfiguration
@@ -179,6 +179,7 @@ data class NodeConfigurationImpl(
override val messagingServerAddress: NetworkHostAndPort?,
override val messagingServerExternal: Boolean = (messagingServerAddress != null),
override val notary: NotaryConfig?,
+ @Suppress("DEPRECATION")
@Deprecated("Do not configure")
override val certificateChainCheckPolicies: List = emptyList(),
override val devMode: Boolean = false,
@@ -329,6 +330,7 @@ data class NodeConfigurationImpl(
require(security == null || rpcUsers.isEmpty()) {
"Cannot specify both 'rpcUsers' and 'security' in configuration"
}
+ @Suppress("DEPRECATION")
if(certificateChainCheckPolicies.isNotEmpty()) {
logger.warn("""You are configuring certificateChainCheckPolicies. This is a setting that is not used, and will be removed in a future version.
|Please contact the R3 team on the public slack to discuss your use case.
@@ -383,18 +385,7 @@ enum class CertChainPolicyType {
}
@Deprecated("Do not use")
-data class CertChainPolicyConfig(val role: String, private val policy: CertChainPolicyType, private val trustedAliases: Set) {
- val certificateChainCheckPolicy: CertificateChainCheckPolicy
- get() {
- return when (policy) {
- CertChainPolicyType.Any -> CertificateChainCheckPolicy.Any
- CertChainPolicyType.RootMustMatch -> CertificateChainCheckPolicy.RootMustMatch
- CertChainPolicyType.LeafMustMatch -> CertificateChainCheckPolicy.LeafMustMatch
- CertChainPolicyType.MustContainOneOf -> CertificateChainCheckPolicy.MustContainOneOf(trustedAliases)
- CertChainPolicyType.UsernameMustMatch -> CertificateChainCheckPolicy.UsernameMustMatchCommonName
- }
- }
-}
+data class CertChainPolicyConfig(val role: String, private val policy: CertChainPolicyType, private val trustedAliases: Set)
// Supported types of authentication/authorization data providers
enum class AuthDataSourceType {
@@ -431,8 +422,6 @@ data class SecurityConfiguration(val authService: SecurityConfiguration.AuthServ
}
}
- fun copyWithAdditionalUser(user: User) = AuthService(dataSource.copyWithAdditionalUser(user), id, options)
-
// Optional components: cache
data class Options(val cache: Options.Cache?) {
@@ -460,12 +449,6 @@ data class SecurityConfiguration(val authService: SecurityConfiguration.AuthServ
AuthDataSourceType.DB -> require(users == null && connection != null)
}
}
-
- fun copyWithAdditionalUser(user: User): DataSource {
- val extendedList = this.users?.toMutableList() ?: mutableListOf()
- extendedList.add(user)
- return DataSource(this.type, this.passwordEncryption, this.connection, listOf(*extendedList.toTypedArray()))
- }
}
companion object {
@@ -485,4 +468,4 @@ data class SecurityConfiguration(val authService: SecurityConfiguration.AuthServ
id = AuthServiceId("NODE_CONFIG"))
}
}
-}
\ No newline at end of file
+}
diff --git a/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt b/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt
index e7ab13fa4c2..adcc86892ad 100644
--- a/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt
+++ b/node/src/main/kotlin/net/corda/node/services/identity/InMemoryIdentityService.kt
@@ -24,7 +24,7 @@ import javax.annotation.concurrent.ThreadSafe
*/
// TODO There is duplicated logic between this and PersistentIdentityService
@ThreadSafe
-class InMemoryIdentityService(identities: List = emptyList(),
+class InMemoryIdentityService(identities: List = emptyList(),
override val trustRoot: X509Certificate) : SingletonSerializeAsToken(), IdentityService {
companion object {
private val log = contextLogger()
diff --git a/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt b/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt
index 0c0eb617789..d900d2c73b5 100644
--- a/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt
+++ b/node/src/main/kotlin/net/corda/node/services/keys/E2ETestKeyManagementService.kt
@@ -53,7 +53,7 @@ class E2ETestKeyManagementService(val identityService: IdentityService,
}
override fun freshKeyAndCert(identity: PartyAndCertificate, revocationEnabled: Boolean): PartyAndCertificate {
- return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey), revocationEnabled)
+ return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey))
}
private fun getSigner(publicKey: PublicKey): ContentSigner = getSigner(getSigningKeyPair(publicKey))
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 5bf1a3d0432..851d0872a2d 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
@@ -30,8 +30,7 @@ import java.time.Duration
fun freshCertificate(identityService: IdentityService,
subjectPublicKey: PublicKey,
issuer: PartyAndCertificate,
- issuerSigner: ContentSigner,
- revocationEnabled: Boolean = false): PartyAndCertificate {
+ issuerSigner: ContentSigner): PartyAndCertificate {
val issuerRole = CertRole.extract(issuer.certificate)
require(issuerRole == CertRole.LEGAL_IDENTITY) { "Confidential identities can only be issued from well known identities, provided issuer ${issuer.name} has role $issuerRole" }
val issuerCert = issuer.certificate
diff --git a/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt b/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt
index e2d7509bb9a..c6d0aaaa86a 100644
--- a/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt
+++ b/node/src/main/kotlin/net/corda/node/services/keys/PersistentKeyManagementService.kt
@@ -87,8 +87,9 @@ class PersistentKeyManagementService(val identityService: IdentityService,
return keyPair.public
}
- override fun freshKeyAndCert(identity: PartyAndCertificate, revocationEnabled: Boolean): PartyAndCertificate =
- freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey), revocationEnabled)
+ override fun freshKeyAndCert(identity: PartyAndCertificate, revocationEnabled: Boolean): PartyAndCertificate {
+ return freshCertificate(identityService, freshKey(), identity, getSigner(identity.owningKey))
+ }
private fun getSigner(publicKey: PublicKey): ContentSigner = getSigner(getSigningKeyPair(publicKey))
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 51ad2460c47..40d1c92b99e 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
@@ -56,10 +56,10 @@ import kotlin.streams.toList
@ThreadSafe
class SingleThreadedStateMachineManager(
val serviceHub: ServiceHubInternal,
- val checkpointStorage: CheckpointStorage,
+ private val checkpointStorage: CheckpointStorage,
val executor: ExecutorService,
val database: CordaPersistence,
- val secureRandom: SecureRandom,
+ private val secureRandom: SecureRandom,
private val unfinishedFibers: ReusableLatch = ReusableLatch(),
private val classloader: ClassLoader = SingleThreadedStateMachineManager::class.java.classLoader
) : StateMachineManager, StateMachineManagerInternal {
@@ -135,7 +135,7 @@ class SingleThreadedStateMachineManager(
}
serviceHub.networkMapCache.nodeReady.then {
resumeRestoredFlows(fibers)
- flowMessaging.start { receivedMessage, deduplicationHandler ->
+ flowMessaging.start { _, deduplicationHandler ->
executor.execute {
deliverExternalEvent(deduplicationHandler.externalCause)
}
@@ -286,10 +286,10 @@ class SingleThreadedStateMachineManager(
}
private fun checkQuasarJavaAgentPresence() {
- check(SuspendableHelper.isJavaAgentActive(), {
+ check(SuspendableHelper.isJavaAgentActive()) {
"""Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM.
#See https://docs.corda.net/troubleshooting.html - 'Fiber classes not instrumented' for more details.""".trimMargin("#")
- })
+ }
}
private fun decrementLiveFibers() {
@@ -304,8 +304,7 @@ class SingleThreadedStateMachineManager(
return checkpointStorage.getAllCheckpoints().map { (id, serializedCheckpoint) ->
// If a flow is added before start() then don't attempt to restore it
mutex.locked { if (flows.containsKey(id)) return@map null }
- val checkpoint = deserializeCheckpoint(serializedCheckpoint)
- if (checkpoint == null) return@map null
+ val checkpoint = deserializeCheckpoint(serializedCheckpoint) ?: return@map null
logger.debug { "Restored $checkpoint" }
createFlowFromCheckpoint(
id = id,
@@ -524,12 +523,6 @@ class SingleThreadedStateMachineManager(
isStartIdempotent: Boolean
): CordaFuture> {
val flowId = StateMachineRunId.createRandom()
- val deduplicationSeed = when (flowStart) {
- FlowStart.Explicit -> flowId.uuid.toString()
- is FlowStart.Initiated ->
- "${flowStart.initiatingMessage.initiatorSessionId.toLong}-" +
- "${flowStart.initiatingMessage.initiationEntropy}"
- }
// Before we construct the state machine state by freezing the FlowLogic we need to make sure that lazy properties
// have access to the fiber (and thereby the service hub)
@@ -541,7 +534,7 @@ class SingleThreadedStateMachineManager(
val flowCorDappVersion = createSubFlowVersion(serviceHub.cordappProvider.getCordappForFlow(flowLogic), serviceHub.myInfo.platformVersion)
- val initialCheckpoint = Checkpoint.create(invocationContext, flowStart, flowLogic.javaClass, frozenFlowLogic, ourIdentity, deduplicationSeed, flowCorDappVersion).getOrThrow()
+ val initialCheckpoint = Checkpoint.create(invocationContext, flowStart, flowLogic.javaClass, frozenFlowLogic, ourIdentity, flowCorDappVersion).getOrThrow()
val startedFuture = openFuture()
val initialState = StateMachineState(
checkpoint = initialCheckpoint,
diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt
index 2779cee9164..75493c1cfb3 100644
--- a/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt
+++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StaffedFlowHospital.kt
@@ -2,6 +2,7 @@ package net.corda.node.services.statemachine
import net.corda.core.flows.StateMachineRunId
import net.corda.core.internal.ThreadBox
+import net.corda.core.internal.TimedFlow
import net.corda.core.internal.bufferUntilSubscribed
import net.corda.core.messaging.DataFeed
import net.corda.core.utilities.contextLogger
@@ -100,12 +101,6 @@ class StaffedFlowHospital {
private data class ConsultationReport(val error: Throwable, val diagnosis: Diagnosis, val by: List)
- /**
- * The flow running in [flowFiber] has cleaned, possibly as a result of a flow hospital resume.
- */
- // It's okay for flows to be cleaned... we fix them now!
- fun flowCleaned(flowFiber: FlowFiber) = Unit
-
/**
* The flow has been removed from the state machine.
*/
diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt
index e4de7f953ab..5684910f440 100644
--- a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt
+++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineState.kt
@@ -69,7 +69,6 @@ data class Checkpoint(
flowLogicClass: Class>,
frozenFlowLogic: SerializedBytes>,
ourIdentity: Party,
- deduplicationSeed: String,
subFlowVersion: SubFlowVersion
): Try {
return SubFlow.create(flowLogicClass, subFlowVersion).map { topLevelSubFlow ->
diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt
index db6cbed48b0..93f78f36924 100644
--- a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt
+++ b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/HospitalisingInterceptor.kt
@@ -45,9 +45,7 @@ class HospitalisingInterceptor(
when (nextState.checkpoint.errorState) {
is ErrorState.Clean -> {
- if (hospitalisedFlows.remove(fiber.id) != null) {
- flowHospital.flowCleaned(fiber)
- }
+ hospitalisedFlows.remove(fiber.id)
}
is ErrorState.Errored -> {
val exceptionsToHandle = nextState.checkpoint.errorState.errors.map { it.exception }
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 945cc2135a3..19db9ef18dc 100644
--- a/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt
+++ b/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt
@@ -76,7 +76,7 @@ abstract class AppendOnlyPersistentMapBase(
Transactional.Committed(value)
} else {
// Some database transactions, including us, writing, with readers seeing whatever is in the database and writers seeing the (in memory) value.
- Transactional.InFlight(this, key, { loadValue(key) }).apply { alsoWrite(value) }
+ Transactional.InFlight(this, key, _readerValueLoader = { loadValue(key) }).apply { alsoWrite(value) }
}
}
@@ -146,13 +146,13 @@ abstract class AppendOnlyPersistentMapBase(
}
// Helpers to know if transaction(s) are currently writing the given key.
- protected fun weAreWriting(key: K): Boolean = pendingKeys.get(key)?.contains(contextTransaction) ?: false
- protected fun anyoneWriting(key: K): Boolean = pendingKeys.get(key)?.isNotEmpty() ?: false
+ protected fun weAreWriting(key: K): Boolean = pendingKeys[key]?.contains(contextTransaction) ?: false
+ protected fun anyoneWriting(key: K): Boolean = pendingKeys[key]?.isNotEmpty() ?: false
// Indicate this database transaction is a writer of this key.
private fun addPendingKey(key: K, databaseTransaction: DatabaseTransaction): Boolean {
var added = true
- pendingKeys.compute(key) { k, oldSet ->
+ pendingKeys.compute(key) { _, oldSet ->
if (oldSet == null) {
val newSet = HashSet(0)
newSet += databaseTransaction
@@ -167,7 +167,7 @@ abstract class AppendOnlyPersistentMapBase(
// Remove this database transaction as a writer of this key, because the transaction committed or rolled back.
private fun removePendingKey(key: K, databaseTransaction: DatabaseTransaction) {
- pendingKeys.compute(key) { k, oldSet ->
+ pendingKeys.compute(key) { _, oldSet ->
if (oldSet == null) {
oldSet
} else {
@@ -199,7 +199,7 @@ abstract class AppendOnlyPersistentMapBase(
}
// No one can see it.
- class Missing() : Transactional() {
+ class Missing : Transactional() {
override val value: T
get() = throw NoSuchElementException("Not present")
override val isPresent: Boolean
@@ -228,7 +228,7 @@ abstract class AppendOnlyPersistentMapBase(
fun alsoWrite(_value: T) {
// Make the lazy loader the writers see actually just return the value that has been set.
- writerValueLoader.set({ _value })
+ writerValueLoader.set { _value }
// We make all these vals so that the lambdas do not need a reference to this, and so the onCommit only has a weak ref to the value.
// We want this so that the cache could evict the value (due to memory constraints etc) without the onCommit callback
// retaining what could be a large memory footprint object.
@@ -242,10 +242,9 @@ abstract class AppendOnlyPersistentMapBase(
// and then stop saying the transaction is writing the key.
tx.onCommit {
if (strongComitted.compareAndSet(false, true)) {
- val dereferencedKey = strongKey
val dereferencedValue = weakValue.get()
if (dereferencedValue != null) {
- strongMap.cache.put(dereferencedKey, Committed(dereferencedValue))
+ strongMap.cache.put(strongKey, Committed(dereferencedValue))
}
}
strongMap.removePendingKey(strongKey, tx)
@@ -262,7 +261,7 @@ abstract class AppendOnlyPersistentMapBase(
private fun loadAsWriter(): T {
val _value = writerValueLoader.get()()
if (writerValueLoader.get() == _writerValueLoader) {
- writerValueLoader.set({ _value })
+ writerValueLoader.set { _value }
}
return _value
}
@@ -272,7 +271,7 @@ abstract class AppendOnlyPersistentMapBase(
private fun loadAsReader(): T? {
val _value = readerValueLoader.get()()
if (readerValueLoader.get() == _readerValueLoader) {
- readerValueLoader.set({ _value })
+ readerValueLoader.set { _value }
}
return _value
}
@@ -310,7 +309,7 @@ open class AppendOnlyPersistentMap(
toPersistentEntity,
persistentEntityClass) {
//TODO determine cacheBound based on entity class later or with node config allowing tuning, or using some heuristic based on heap size
- override val cache = NonInvalidatingCache>(
+ override val cache = NonInvalidatingCache(
bound = cacheBound,
loadFunction = { key: K ->
// This gets called if a value is read and the cache has no Transactional for this key yet.
@@ -321,10 +320,10 @@ open class AppendOnlyPersistentMap(
// If someone is writing (but not us)
// For those not writing, the value cannot be seen.
// For those writing, they need to re-load the value from the database (which their database transaction CAN see).
- Transactional.InFlight(this, key, { null }, { loadValue(key)!! })
+ Transactional.InFlight(this, key, { null }, { loadValue(key)!! })
} else {
// If no one is writing, then the value does not exist.
- Transactional.Missing()
+ Transactional.Missing()
}
} else {
// A value was found
@@ -332,10 +331,10 @@ open class AppendOnlyPersistentMap(
// If we are writing, it might not be globally visible, and was evicted from the cache.
// For those not writing, they need to check the database again.
// For those writing, they can see the value found.
- Transactional.InFlight(this, key, { loadValue(key) }, { value })
+ Transactional.InFlight(this, key, { loadValue(key) }, { value })
} else {
// If no one is writing, then make it globally visible.
- Transactional.Committed(value)
+ Transactional.Committed(value)
}
}
})
@@ -354,26 +353,22 @@ class WeightBasedAppendOnlyPersistentMap(
fromPersistentEntity,
toPersistentEntity,
persistentEntityClass) {
- override val cache = NonInvalidatingWeightBasedCache>(
+ override val cache = NonInvalidatingWeightBasedCache(
maxWeight = maxWeight,
- weigher = object : Weigher> {
- override fun weigh(key: K, value: Transactional): Int {
- return weighingFunc(key, value)
- }
- },
+ weigher = Weigher { key, value -> weighingFunc(key, value) },
loadFunction = { key: K ->
val value: V? = loadValue(key)
if (value == null) {
if (anyoneWriting(key)) {
- Transactional.InFlight(this, key, { null }, { loadValue(key)!! })
+ Transactional.InFlight(this, key, { null }, { loadValue(key)!! })
} else {
- Transactional.Missing()
+ Transactional.Missing()
}
} else {
if (weAreWriting(key)) {
- Transactional.InFlight(this, key, { loadValue(key) }, { value })
+ Transactional.InFlight(this, key, { loadValue(key) }, { value })
} else {
- Transactional.Committed(value)
+ Transactional.Committed(value)
}
}
})
diff --git a/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java b/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java
index 3c9b727313c..359a162c395 100644
--- a/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java
+++ b/node/src/test/java/net/corda/node/services/vault/VaultQueryJavaTests.java
@@ -35,9 +35,6 @@
import org.junit.Test;
import rx.Observable;
-import java.io.IOException;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.cert.CertificateException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -69,7 +66,7 @@ public class VaultQueryJavaTests {
private CordaPersistence database;
@Before
- public void setUp() throws CertificateException, InvalidAlgorithmParameterException {
+ public void setUp() {
List cordappPackages = asList("net.corda.testing.internal.vault", "net.corda.finance.contracts.asset", CashSchemaV1.class.getPackage().getName());
IdentityService identitySvc = makeTestIdentityService(MEGA_CORP.getIdentity(), DUMMY_CASH_ISSUER_INFO.getIdentity(), DUMMY_NOTARY.getIdentity());
Pair databaseAndServices = makeTestDatabaseAndMockServices(
@@ -85,14 +82,10 @@ public void setUp() throws CertificateException, InvalidAlgorithmParameterExcept
}
@After
- public void cleanUp() throws IOException {
+ public void cleanUp() {
database.close();
}
- /**
- * Sample Vault Query API tests
- */
-
/**
* Static queryBy() tests
*/
@@ -103,6 +96,7 @@ public void criteriaWithFieldFromMappedSuperclass() throws NoSuchFieldException
FieldInfo currency = getField("currency", SampleCashSchemaV2.PersistentCashState.class);
CriteriaExpression.AggregateFunctionExpression