mirror of
https://github.com/corda/corda.git
synced 2025-05-29 05:34:22 +00:00
Reformat files in node
This commit is contained in:
parent
7a372bed59
commit
cb9e27a84a
@ -36,7 +36,7 @@ class CordappScanningDriverTest {
|
||||
|
||||
@StartableByRPC
|
||||
@InitiatingFlow
|
||||
class ReceiveFlow(val otherParty: Party) :FlowLogic<String>() {
|
||||
class ReceiveFlow(val otherParty: Party) : FlowLogic<String>() {
|
||||
@Suspendable
|
||||
override fun call(): String = initiateFlow(otherParty).receive<String>().unwrap { it }
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ class NodeStartupPerformanceTests {
|
||||
driver(networkMapStartStrategy = NetworkMapStartStrategy.Dedicated(startAutomatically = false)) {
|
||||
startDedicatedNetworkMapService().get()
|
||||
val times = ArrayList<Long>()
|
||||
for (i in 1 .. 10) {
|
||||
for (i in 1..10) {
|
||||
val time = Stopwatch.createStarted().apply {
|
||||
startNode().get()
|
||||
}.stop().elapsed(TimeUnit.MICROSECONDS)
|
||||
|
@ -29,7 +29,9 @@ import kotlin.test.assertTrue
|
||||
|
||||
class NodeInfoWatcherTest : NodeBasedTest() {
|
||||
|
||||
@Rule @JvmField var folder = TemporaryFolder()
|
||||
@Rule
|
||||
@JvmField
|
||||
var folder = TemporaryFolder()
|
||||
|
||||
lateinit var keyManagementService: KeyManagementService
|
||||
lateinit var nodeInfoPath: Path
|
||||
|
@ -170,8 +170,7 @@ class PersistentNetworkMapCacheTest : NodeBasedTest() {
|
||||
(customRetryIntervalMs?.let { mapOf("activeMQServer.bridge.retryIntervalMs" to it.toString()) } ?: emptyMap())
|
||||
if (party == DUMMY_NOTARY) {
|
||||
startNetworkMapNode(party.name, configOverrides = configOverrides)
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
startNode(party.name,
|
||||
configOverrides = configOverrides,
|
||||
noNetworkMap = noNetworkMap,
|
||||
@ -184,7 +183,7 @@ class PersistentNetworkMapCacheTest : NodeBasedTest() {
|
||||
private fun checkConnectivity(nodes: List<StartedNode<*>>) {
|
||||
nodes.forEach { node1 ->
|
||||
nodes.forEach { node2 ->
|
||||
if(!(node1 === node2)) { // Do not check connectivity to itself
|
||||
if (!(node1 === node2)) { // Do not check connectivity to itself
|
||||
node2.internals.registerInitiatedFlow(SendBackFlow::class.java)
|
||||
val resultFuture = node1.services.startFlow(SendFlow(node2.info.chooseIdentity())).resultFuture
|
||||
assertThat(resultFuture.getOrThrow()).isEqualTo("Hello!")
|
||||
|
@ -21,7 +21,8 @@ import kotlin.test.assertEquals
|
||||
* transaction size limit (which should only consider the hashes).
|
||||
*/
|
||||
class LargeTransactionsTest {
|
||||
@StartableByRPC @InitiatingFlow
|
||||
@StartableByRPC
|
||||
@InitiatingFlow
|
||||
class SendLargeTransactionFlow(private val hash1: SecureHash,
|
||||
private val hash2: SecureHash,
|
||||
private val hash3: SecureHash,
|
||||
@ -44,7 +45,8 @@ class LargeTransactionsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@InitiatedBy(SendLargeTransactionFlow::class) @Suppress("UNUSED")
|
||||
@InitiatedBy(SendLargeTransactionFlow::class)
|
||||
@Suppress("UNUSED")
|
||||
class ReceiveLargeTransactionFlow(private val otherSide: FlowSession) : FlowLogic<Unit>() {
|
||||
@Suspendable
|
||||
override fun call() {
|
||||
|
@ -69,7 +69,7 @@ data class CmdLineOptions(val baseDirectory: Path,
|
||||
val isVersion: Boolean,
|
||||
val noLocalShell: Boolean,
|
||||
val sshdServer: Boolean,
|
||||
val justGenerateNodeInfo : Boolean) {
|
||||
val justGenerateNodeInfo: Boolean) {
|
||||
fun loadConfig() = ConfigHelper
|
||||
.loadConfig(baseDirectory, configFile)
|
||||
.parseAs<FullNodeConfiguration>()
|
||||
|
@ -277,7 +277,7 @@ abstract class AbstractNode(config: NodeConfiguration,
|
||||
/**
|
||||
* This customizes the ServiceHub for each CordaService that is initiating flows
|
||||
*/
|
||||
private class AppServiceHubImpl<T : SerializeAsToken>(val serviceHub: ServiceHubInternal): AppServiceHub, ServiceHub by serviceHub {
|
||||
private class AppServiceHubImpl<T : SerializeAsToken>(val serviceHub: ServiceHubInternal) : AppServiceHub, ServiceHub by serviceHub {
|
||||
lateinit var serviceInstance: T
|
||||
override fun <T> startTrackedFlow(flow: FlowLogic<T>): FlowProgressHandle<T> {
|
||||
val stateMachine = startFlowChecked(flow)
|
||||
|
@ -349,7 +349,7 @@ open class Node(override val configuration: FullNodeConfiguration,
|
||||
_startupComplete.set(Unit)
|
||||
}
|
||||
},
|
||||
{ th -> logger.error("Unexpected exception", th)}
|
||||
{ th -> logger.error("Unexpected exception", th) }
|
||||
)
|
||||
shutdownHook = addShutdownHook {
|
||||
stop()
|
||||
|
@ -110,13 +110,13 @@ open class NodeStartup(val args: Array<String>) {
|
||||
startedNode.internals.startupComplete.then {
|
||||
try {
|
||||
InteractiveShell.startShell(cmdlineOptions.baseDirectory, runShell, cmdlineOptions.sshdServer, startedNode)
|
||||
} catch(e: Throwable) {
|
||||
} catch (e: Throwable) {
|
||||
logger.error("Shell failed to start", e)
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
th -> logger.error("Unexpected exception during registration", th)
|
||||
{ th ->
|
||||
logger.error("Unexpected exception during registration", th)
|
||||
})
|
||||
startedNode.internals.run()
|
||||
}
|
||||
|
@ -111,7 +111,7 @@ class CordappLoader private constructor(private val cordappJarPaths: List<URL>)
|
||||
|
||||
/** Takes a package of classes and creates a JAR from them - only use in tests. */
|
||||
private fun createDevCordappJar(scanPackage: String, path: URL, jarPackageName: String): URI {
|
||||
if(!generatedCordapps.contains(path)) {
|
||||
if (!generatedCordapps.contains(path)) {
|
||||
val cordappDir = File("build/tmp/generated-test-cordapps")
|
||||
cordappDir.mkdirs()
|
||||
val cordappJAR = File(cordappDir, "$scanPackage-${UUID.randomUUID()}.jar")
|
||||
|
@ -19,7 +19,7 @@ open class CordappProviderImpl(private val cordappLoader: CordappLoader) : Singl
|
||||
// TODO: Use better supported APIs in Java 9
|
||||
Exception().stackTrace.forEach { stackFrame ->
|
||||
val cordapp = getCordappForClass(stackFrame.className)
|
||||
if(cordapp != null) {
|
||||
if (cordapp != null) {
|
||||
return getAppContext(cordapp)
|
||||
}
|
||||
}
|
||||
|
@ -118,6 +118,7 @@ data class FlowPermissionAuditEvent(override val timestamp: Instant,
|
||||
override val flowId: StateMachineRunId,
|
||||
val permissionRequested: String,
|
||||
val permissionGranted: Boolean) : AuditEvent(), FlowAuditInfo
|
||||
|
||||
/**
|
||||
* Minimal interface for recording audit information within the system. The AuditService is assumed to be available only
|
||||
* to trusted internal components via ServiceHubInternal.
|
||||
|
@ -122,7 +122,8 @@ enum class CertChainPolicyType {
|
||||
}
|
||||
|
||||
data class CertChainPolicyConfig(val role: String, private val policy: CertChainPolicyType, private val trustedAliases: Set<String>) {
|
||||
val certificateChainCheckPolicy: CertificateChainCheckPolicy get() {
|
||||
val certificateChainCheckPolicy: CertificateChainCheckPolicy
|
||||
get() {
|
||||
return when (policy) {
|
||||
CertChainPolicyType.Any -> CertificateChainCheckPolicy.Any
|
||||
CertChainPolicyType.RootMustMatch -> CertificateChainCheckPolicy.RootMustMatch
|
||||
|
@ -89,11 +89,11 @@ class NodeSchedulerService(private val services: ServiceHubInternal,
|
||||
try {
|
||||
// This will return when it times out, or when the clock mutates or when when the original future completes.
|
||||
originalFutureCompleted.get(nanos, TimeUnit.NANOSECONDS)
|
||||
} catch(e: ExecutionException) {
|
||||
} catch (e: ExecutionException) {
|
||||
// No need to take action as will fall out of the loop due to future.isDone
|
||||
} catch(e: CancellationException) {
|
||||
} catch (e: CancellationException) {
|
||||
// No need to take action as will fall out of the loop due to future.isDone
|
||||
} catch(e: TimeoutException) {
|
||||
} catch (e: TimeoutException) {
|
||||
// No need to take action as will fall out of the loop due to future.isDone
|
||||
}
|
||||
}
|
||||
@ -152,7 +152,7 @@ class NodeSchedulerService(private val services: ServiceHubInternal,
|
||||
private class InnerState {
|
||||
var scheduledStates = createMap()
|
||||
|
||||
var scheduledStatesQueue: PriorityQueue<ScheduledStateRef> = PriorityQueue( { a, b -> a.scheduledAt.compareTo(b.scheduledAt) } )
|
||||
var scheduledStatesQueue: PriorityQueue<ScheduledStateRef> = PriorityQueue({ a, b -> a.scheduledAt.compareTo(b.scheduledAt) })
|
||||
|
||||
var rescheduled: GuavaSettableFuture<Boolean>? = null
|
||||
}
|
||||
@ -162,7 +162,7 @@ class NodeSchedulerService(private val services: ServiceHubInternal,
|
||||
// We need the [StateMachineManager] to be constructed before this is called in case it schedules a flow.
|
||||
fun start() {
|
||||
mutex.locked {
|
||||
scheduledStatesQueue.addAll(scheduledStates.all().map { it.second } .toMutableList())
|
||||
scheduledStatesQueue.addAll(scheduledStates.all().map { it.second }.toMutableList())
|
||||
rescheduleWakeUp()
|
||||
}
|
||||
}
|
||||
@ -182,7 +182,7 @@ class NodeSchedulerService(private val services: ServiceHubInternal,
|
||||
if (action.scheduledAt.isBefore(previousEarliest?.scheduledAt ?: Instant.MAX)) {
|
||||
// We are earliest
|
||||
rescheduleWakeUp()
|
||||
} else if(previousEarliest?.ref == action.ref && previousEarliest.scheduledAt != action.scheduledAt) {
|
||||
} else if (previousEarliest?.ref == action.ref && previousEarliest.scheduledAt != action.scheduledAt) {
|
||||
// We were earliest but might not be any more
|
||||
rescheduleWakeUp()
|
||||
}
|
||||
|
@ -30,6 +30,7 @@ class InMemoryIdentityService(identities: Iterable<PartyAndCertificate> = emptyS
|
||||
constructor(wellKnownIdentities: Iterable<PartyAndCertificate> = emptySet(),
|
||||
confidentialIdentities: Iterable<PartyAndCertificate> = emptySet(),
|
||||
trustRoot: X509CertificateHolder) : this(wellKnownIdentities, confidentialIdentities, trustRoot.cert)
|
||||
|
||||
companion object {
|
||||
private val log = loggerFor<InMemoryIdentityService>()
|
||||
}
|
||||
@ -45,7 +46,7 @@ class InMemoryIdentityService(identities: Iterable<PartyAndCertificate> = emptyS
|
||||
init {
|
||||
val caCertificatesWithRoot: Set<X509Certificate> = caCertificates.toSet() + trustRoot
|
||||
caCertStore = CertStore.getInstance("Collection", CollectionCertStoreParameters(caCertificatesWithRoot))
|
||||
keyToParties.putAll(identities.associateBy { it.owningKey } )
|
||||
keyToParties.putAll(identities.associateBy { it.owningKey })
|
||||
principalToParties.putAll(identities.associateBy { it.name })
|
||||
confidentialIdentities.forEach { identity ->
|
||||
principalToParties.computeIfAbsent(identity.name) { identity }
|
||||
@ -94,6 +95,7 @@ class InMemoryIdentityService(identities: Iterable<PartyAndCertificate> = emptyS
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun wellKnownPartyFromAnonymous(partyRef: PartyAndReference) = wellKnownPartyFromAnonymous(partyRef.party)
|
||||
override fun requireWellKnownPartyFromAnonymous(party: AbstractParty): Party {
|
||||
return wellKnownPartyFromAnonymous(party) ?: throw IllegalStateException("Could not deanonymise party ${party.owningKey.toStringShort()}")
|
||||
|
@ -48,8 +48,10 @@ class PersistentKeyManagementService(val identityService: IdentityService,
|
||||
fun createKeyMap(): AppendOnlyPersistentMap<PublicKey, PrivateKey, PersistentKey, String> {
|
||||
return AppendOnlyPersistentMap(
|
||||
toPersistentEntityKey = { it.toBase58String() },
|
||||
fromPersistentEntity = { Pair(parsePublicKeyBase58(it.publicKey),
|
||||
it.privateKey.deserialize<PrivateKey>(context = SerializationDefaults.STORAGE_CONTEXT)) },
|
||||
fromPersistentEntity = {
|
||||
Pair(parsePublicKeyBase58(it.publicKey),
|
||||
it.privateKey.deserialize<PrivateKey>(context = SerializationDefaults.STORAGE_CONTEXT))
|
||||
},
|
||||
toPersistentEntity = { key: PublicKey, value: PrivateKey ->
|
||||
PersistentKey().apply {
|
||||
publicKey = key.toBase58String()
|
||||
|
@ -97,7 +97,8 @@ class ArtemisMessagingServer(override val config: NodeConfiguration,
|
||||
companion object {
|
||||
private val log = loggerFor<ArtemisMessagingServer>()
|
||||
/** 10 MiB maximum allowed file size for attachments, including message headers. TODO: acquire this value from Network Map when supported. */
|
||||
@JvmStatic val MAX_FILE_SIZE = 10485760
|
||||
@JvmStatic
|
||||
val MAX_FILE_SIZE = 10485760
|
||||
|
||||
val ipDetectRequestProperty = "ip-request-id"
|
||||
val ipDetectResponseProperty = "ip-address"
|
||||
|
@ -117,10 +117,12 @@ class NodeMessagingClient(override val config: NodeConfiguration,
|
||||
fun createMessageToRedeliver(): PersistentMap<Long, Pair<Message, MessageRecipients>, RetryMessage, Long> {
|
||||
return PersistentMap(
|
||||
toPersistentEntityKey = { it },
|
||||
fromPersistentEntity = { Pair(it.key,
|
||||
Pair(it.message.deserialize( context = SerializationDefaults.STORAGE_CONTEXT),
|
||||
it.recipients.deserialize( context = SerializationDefaults.STORAGE_CONTEXT))
|
||||
) },
|
||||
fromPersistentEntity = {
|
||||
Pair(it.key,
|
||||
Pair(it.message.deserialize(context = SerializationDefaults.STORAGE_CONTEXT),
|
||||
it.recipients.deserialize(context = SerializationDefaults.STORAGE_CONTEXT))
|
||||
)
|
||||
},
|
||||
toPersistentEntity = { _key: Long, (_message: Message, _recipient: MessageRecipients): Pair<Message, MessageRecipients> ->
|
||||
RetryMessage().apply {
|
||||
key = _key
|
||||
@ -241,7 +243,7 @@ class NodeMessagingClient(override val config: NodeConfiguration,
|
||||
log.info("Network map is complete, so removing filter from P2P consumer.")
|
||||
try {
|
||||
p2pConsumer!!.close()
|
||||
} catch(e: ActiveMQObjectClosedException) {
|
||||
} catch (e: ActiveMQObjectClosedException) {
|
||||
// Ignore it: this can happen if the server has gone away before we do.
|
||||
}
|
||||
p2pConsumer = makeP2PConsumer(session, false)
|
||||
@ -283,8 +285,8 @@ class NodeMessagingClient(override val config: NodeConfiguration,
|
||||
}
|
||||
|
||||
private fun resumeMessageRedelivery() {
|
||||
messagesToRedeliver.forEach {
|
||||
retryId, (message, target) -> send(message, target, retryId)
|
||||
messagesToRedeliver.forEach { retryId, (message, target) ->
|
||||
send(message, target, retryId)
|
||||
}
|
||||
}
|
||||
|
||||
@ -301,7 +303,7 @@ class NodeMessagingClient(override val config: NodeConfiguration,
|
||||
// It's safe to call into receive simultaneous with other threads calling send on a producer.
|
||||
val artemisMessage: ClientMessage = try {
|
||||
consumer.receive()
|
||||
} catch(e: ActiveMQObjectClosedException) {
|
||||
} catch (e: ActiveMQObjectClosedException) {
|
||||
null
|
||||
} ?: return false
|
||||
|
||||
@ -433,7 +435,7 @@ class NodeMessagingClient(override val config: NodeConfiguration,
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(e: Exception) {
|
||||
} catch (e: Exception) {
|
||||
log.error("Caught exception whilst executing message handler for ${msg.topicSession}", e)
|
||||
}
|
||||
return true
|
||||
@ -454,7 +456,7 @@ class NodeMessagingClient(override val config: NodeConfiguration,
|
||||
val c = p2pConsumer ?: throw IllegalStateException("stop can't be called twice")
|
||||
try {
|
||||
c.close()
|
||||
} catch(e: ActiveMQObjectClosedException) {
|
||||
} catch (e: ActiveMQObjectClosedException) {
|
||||
// Ignore it: this can happen if the server has gone away before we do.
|
||||
}
|
||||
p2pConsumer = null
|
||||
|
@ -86,6 +86,7 @@ class RPCServer(
|
||||
private companion object {
|
||||
val log = loggerFor<RPCServer>()
|
||||
}
|
||||
|
||||
private enum class State {
|
||||
UNSTARTED,
|
||||
STARTED,
|
||||
@ -350,6 +351,7 @@ class RPCServer(
|
||||
|
||||
// TODO remove this User once webserver doesn't need it
|
||||
private val nodeUser = User(NODE_USER, NODE_USER, setOf())
|
||||
|
||||
private fun getUser(message: ClientMessage): User {
|
||||
val validatedUser = message.getStringProperty(Message.HDR_VALIDATED_USER) ?: throw IllegalArgumentException("Missing validated user from the Artemis message")
|
||||
val rpcUser = userService.getUser(validatedUser)
|
||||
@ -365,6 +367,7 @@ class RPCServer(
|
||||
|
||||
@JvmField
|
||||
internal val CURRENT_RPC_CONTEXT: ThreadLocal<RpcContext> = ThreadLocal()
|
||||
|
||||
/**
|
||||
* Returns a context specific to the current RPC call. Note that trying to call this function outside of an RPC will
|
||||
* throw. If you'd like to use the context outside of the call (e.g. in another thread) then pass the returned reference
|
||||
@ -422,6 +425,7 @@ class ObservableContext(
|
||||
|
||||
object RpcServerObservableSerializer : Serializer<Observable<*>>() {
|
||||
private object RpcObservableContextKey
|
||||
|
||||
private val log = loggerFor<RpcServerObservableSerializer>()
|
||||
|
||||
fun createContext(observableContext: ObservableContext): SerializationContext {
|
||||
@ -448,9 +452,11 @@ object RpcServerObservableSerializer : Serializer<Observable<*>>() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(exception: Throwable) {
|
||||
log.error("onError called in materialize()d RPC Observable", exception)
|
||||
}
|
||||
|
||||
override fun onCompleted() {
|
||||
}
|
||||
}
|
||||
|
@ -99,7 +99,7 @@ class NodeInfoWatcher(private val nodePath: Path,
|
||||
return result
|
||||
}
|
||||
|
||||
private fun processFile(file: Path) : NodeInfo? {
|
||||
private fun processFile(file: Path): NodeInfo? {
|
||||
try {
|
||||
logger.info("Reading NodeInfo from file: $file")
|
||||
val signedData = file.readAll().deserialize<SignedData<NodeInfo>>()
|
||||
|
@ -118,6 +118,7 @@ open class PersistentNetworkMapCache(private val serviceHub: ServiceHubInternal)
|
||||
override fun getNodesByLegalName(name: CordaX500Name): List<NodeInfo> = serviceHub.database.transaction { queryByLegalName(name) }
|
||||
override fun getNodesByLegalIdentityKey(identityKey: PublicKey): List<NodeInfo> =
|
||||
serviceHub.database.transaction { queryByIdentityKey(identityKey) }
|
||||
|
||||
override fun getNodeByLegalIdentity(party: AbstractParty): NodeInfo? {
|
||||
val wellKnownParty = serviceHub.identityService.wellKnownPartyFromAnonymous(party)
|
||||
return wellKnownParty?.let {
|
||||
|
@ -32,7 +32,7 @@ class AbstractPartyToX500NameAsStringConverter(identitySvc: () -> IdentityServic
|
||||
if (dbData != null) {
|
||||
val party = identityService.wellKnownPartyFromX500Name(CordaX500Name.parse(dbData))
|
||||
if (party != null) return party
|
||||
log.warn ("Identity service unable to resolve X500name: $dbData")
|
||||
log.warn("Identity service unable to resolve X500name: $dbData")
|
||||
}
|
||||
return null // non resolvable anonymous parties are stored as nulls
|
||||
}
|
||||
|
@ -30,8 +30,10 @@ class DBTransactionStorage : WritableTransactionStorage, SingletonSerializeAsTok
|
||||
fun createTransactionsMap(): AppendOnlyPersistentMap<SecureHash, SignedTransaction, DBTransaction, String> {
|
||||
return AppendOnlyPersistentMap(
|
||||
toPersistentEntityKey = { it.toString() },
|
||||
fromPersistentEntity = { Pair(SecureHash.parse(it.txId),
|
||||
it.transaction.deserialize<SignedTransaction>( context = SerializationDefaults.STORAGE_CONTEXT)) },
|
||||
fromPersistentEntity = {
|
||||
Pair(SecureHash.parse(it.txId),
|
||||
it.transaction.deserialize<SignedTransaction>(context = SerializationDefaults.STORAGE_CONTEXT))
|
||||
},
|
||||
toPersistentEntity = { key: SecureHash, value: SignedTransaction ->
|
||||
DBTransaction().apply {
|
||||
txId = key.toString()
|
||||
@ -59,5 +61,6 @@ class DBTransactionStorage : WritableTransactionStorage, SingletonSerializeAsTok
|
||||
DataFeed(txStorage.allPersisted().map { it.second }.toList(), updatesPublisher.bufferUntilSubscribed().wrapWithDatabaseTransaction())
|
||||
|
||||
@VisibleForTesting
|
||||
val transactions: Iterable<SignedTransaction> get() = txStorage.allPersisted().map { it.second }.toList()
|
||||
val transactions: Iterable<SignedTransaction>
|
||||
get() = txStorage.allPersisted().map { it.second }.toList()
|
||||
}
|
||||
|
@ -32,7 +32,7 @@ class HibernateConfiguration(val schemaService: SchemaService, private val datab
|
||||
// TODO: make this a guava cache or similar to limit ability for this to grow forever.
|
||||
private val sessionFactories = ConcurrentHashMap<Set<MappedSchema>, SessionFactory>()
|
||||
|
||||
private val transactionIsolationLevel = parserTransactionIsolationLevel(databaseProperties.getProperty("transactionIsolationLevel") ?:"")
|
||||
private val transactionIsolationLevel = parserTransactionIsolationLevel(databaseProperties.getProperty("transactionIsolationLevel") ?: "")
|
||||
|
||||
init {
|
||||
logger.info("Init HibernateConfiguration for schemas: ${schemaService.schemaOptions.keys}")
|
||||
@ -61,7 +61,7 @@ class HibernateConfiguration(val schemaService: SchemaService, private val datab
|
||||
// necessarily remain and would likely be replaced by something like Liquibase. For now it is very convenient though.
|
||||
// TODO: replace auto schema generation as it isn't intended for production use, according to Hibernate docs.
|
||||
val config = Configuration(metadataSources).setProperty("hibernate.connection.provider_class", NodeDatabaseConnectionProvider::class.java.name)
|
||||
.setProperty("hibernate.hbm2ddl.auto", if (databaseProperties.getProperty("initDatabase","true") == "true") "update" else "validate")
|
||||
.setProperty("hibernate.hbm2ddl.auto", if (databaseProperties.getProperty("initDatabase", "true") == "true") "update" else "validate")
|
||||
.setProperty("hibernate.format_sql", "true")
|
||||
.setProperty("hibernate.connection.isolation", transactionIsolationLevel.toString())
|
||||
|
||||
@ -70,7 +70,7 @@ class HibernateConfiguration(val schemaService: SchemaService, private val datab
|
||||
schema.mappedTypes.forEach { config.addAnnotatedClass(it) }
|
||||
}
|
||||
|
||||
val sessionFactory = buildSessionFactory(config, metadataSources, databaseProperties.getProperty("serverNameTablePrefix",""))
|
||||
val sessionFactory = buildSessionFactory(config, metadataSources, databaseProperties.getProperty("serverNameTablePrefix", ""))
|
||||
logger.info("Created session factory for schemas: $schemas")
|
||||
return sessionFactory
|
||||
}
|
||||
|
@ -22,6 +22,7 @@ class InMemoryStateMachineRecordedTransactionMappingStorage : StateMachineRecord
|
||||
val stateMachineTransactionMap = HashMap<StateMachineRunId, HashSet<SecureHash>>()
|
||||
val updates = PublishSubject.create<StateMachineTransactionMapping>()!!
|
||||
}
|
||||
|
||||
private val mutex = ThreadBox(InnerState())
|
||||
|
||||
override fun addMapping(stateMachineRunId: StateMachineRunId, transactionId: SecureHash) {
|
||||
|
@ -69,7 +69,8 @@ class NodeAttachmentService(metrics: MetricRegistry) : AttachmentStorage, Single
|
||||
* around inside it, we haven't read the whole file, so we can't check the hash. But when copying it over the network
|
||||
* this will provide an additional safety check against user error.
|
||||
*/
|
||||
@VisibleForTesting @CordaSerializable
|
||||
@VisibleForTesting
|
||||
@CordaSerializable
|
||||
class HashCheckingStream(val expected: SecureHash.SHA256,
|
||||
val expectedSize: Int,
|
||||
input: InputStream,
|
||||
@ -110,7 +111,8 @@ class NodeAttachmentService(metrics: MetricRegistry) : AttachmentStorage, Single
|
||||
}
|
||||
|
||||
private var _hash: HashCode? = null // Backing field for hash property
|
||||
private val hash: HashCode get() {
|
||||
private val hash: HashCode
|
||||
get() {
|
||||
var h = _hash
|
||||
return if (h == null) {
|
||||
h = stream.hash()
|
||||
|
@ -67,8 +67,8 @@ class NodeSchemaService(customSchemas: Set<MappedSchema> = emptySet()) : SchemaS
|
||||
Pair(NodeInfoSchemaV1, SchemaService.SchemaOptions()),
|
||||
Pair(NodeServicesV1, SchemaService.SchemaOptions()))
|
||||
|
||||
override var schemaOptions: Map<MappedSchema, SchemaService.SchemaOptions> = requiredSchemas.plus(customSchemas.map {
|
||||
mappedSchema -> Pair(mappedSchema, SchemaService.SchemaOptions())
|
||||
override var schemaOptions: Map<MappedSchema, SchemaService.SchemaOptions> = requiredSchemas.plus(customSchemas.map { mappedSchema ->
|
||||
Pair(mappedSchema, SchemaService.SchemaOptions())
|
||||
})
|
||||
|
||||
// Currently returns all schemas supported by the state, with no filtering or enrichment.
|
||||
@ -94,8 +94,8 @@ class NodeSchemaService(customSchemas: Set<MappedSchema> = emptySet()) : SchemaS
|
||||
}
|
||||
|
||||
override fun registerCustomSchemas(_customSchemas: Set<MappedSchema>) {
|
||||
schemaOptions = schemaOptions.plus(_customSchemas.map {
|
||||
mappedSchema -> Pair(mappedSchema, SchemaService.SchemaOptions())
|
||||
schemaOptions = schemaOptions.plus(_customSchemas.map { mappedSchema ->
|
||||
Pair(mappedSchema, SchemaService.SchemaOptions())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -541,7 +541,8 @@ class FlowStateMachineImpl<R>(override val id: StateMachineRunId,
|
||||
}
|
||||
}
|
||||
|
||||
val Class<out FlowLogic<*>>.flowVersionAndInitiatingClass: Pair<Int, Class<out FlowLogic<*>>> get() {
|
||||
val Class<out FlowLogic<*>>.flowVersionAndInitiatingClass: Pair<Int, Class<out FlowLogic<*>>>
|
||||
get() {
|
||||
var current: Class<*> = this
|
||||
var found: Pair<Int, Class<out FlowLogic<*>>>? = null
|
||||
while (true) {
|
||||
@ -556,13 +557,14 @@ val Class<out FlowLogic<*>>.flowVersionAndInitiatingClass: Pair<Int, Class<out F
|
||||
?: throw IllegalArgumentException("$name, as a flow that initiates other flows, must be annotated with " +
|
||||
"${InitiatingFlow::class.java.name}. See https://docs.corda.net/api-flows.html#flowlogic-annotations.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val Class<out FlowLogic<*>>.appName: String get() {
|
||||
val Class<out FlowLogic<*>>.appName: String
|
||||
get() {
|
||||
val jarFile = Paths.get(protectionDomain.codeSource.location.toURI())
|
||||
return if (jarFile.isRegularFile() && jarFile.toString().endsWith(".jar")) {
|
||||
jarFile.fileName.toString().removeSuffix(".jar")
|
||||
} else {
|
||||
"<unknown>"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -631,7 +631,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal,
|
||||
val serialized = try {
|
||||
message.serialize()
|
||||
} catch (e: Exception) {
|
||||
when(e) {
|
||||
when (e) {
|
||||
// Handling Kryo and AMQP serialization problems. Unfortunately the two exception types do not share much of a common exception interface.
|
||||
is KryoException,
|
||||
is NotSerializableException -> {
|
||||
|
@ -112,7 +112,7 @@ class BFTNonValidatingNotaryService(override val services: ServiceHubInternal,
|
||||
name = CordaX500Name.parse(it.party.name),
|
||||
owningKey = parsePublicKeyBase58(it.party.owningKey))))
|
||||
},
|
||||
toPersistentEntity = { (txHash, index) : StateRef, (id, inputIndex, requestingParty): UniquenessProvider.ConsumingTx ->
|
||||
toPersistentEntity = { (txHash, index): StateRef, (id, inputIndex, requestingParty): UniquenessProvider.ConsumingTx ->
|
||||
PersistedCommittedState(
|
||||
id = PersistentStateRef(txHash.toString(), index),
|
||||
consumingTxHash = id.toString(),
|
||||
|
@ -24,7 +24,7 @@ import javax.persistence.*
|
||||
class PersistentUniquenessProvider : UniquenessProvider, SingletonSerializeAsToken() {
|
||||
|
||||
@MappedSuperclass
|
||||
open class PersistentUniqueness (
|
||||
open class PersistentUniqueness(
|
||||
@EmbeddedId
|
||||
var id: PersistentStateRef = PersistentStateRef(),
|
||||
|
||||
@ -45,11 +45,11 @@ class PersistentUniquenessProvider : UniquenessProvider, SingletonSerializeAsTok
|
||||
|
||||
@Column(name = "requesting_party_key", length = 255)
|
||||
var owningKey: String = ""
|
||||
): Serializable
|
||||
) : Serializable
|
||||
|
||||
@Entity
|
||||
@javax.persistence.Table(name = "${NODE_DATABASE_PREFIX}notary_commit_log")
|
||||
class PersistentNotaryCommit(id: PersistentStateRef, consumingTxHash: String, consumingIndex: Int, party: PersistentParty):
|
||||
class PersistentNotaryCommit(id: PersistentStateRef, consumingTxHash: String, consumingIndex: Int, party: PersistentParty) :
|
||||
PersistentUniqueness(id, consumingTxHash, consumingIndex, party)
|
||||
|
||||
|
||||
@ -77,7 +77,7 @@ class PersistentUniquenessProvider : UniquenessProvider, SingletonSerializeAsTok
|
||||
name = CordaX500Name.parse(it.party.name),
|
||||
owningKey = parsePublicKeyBase58(it.party.owningKey))))
|
||||
},
|
||||
toPersistentEntity = { (txHash, index) : StateRef, (id, inputIndex, requestingParty) : UniquenessProvider.ConsumingTx ->
|
||||
toPersistentEntity = { (txHash, index): StateRef, (id, inputIndex, requestingParty): UniquenessProvider.ConsumingTx ->
|
||||
PersistentNotaryCommit(
|
||||
id = PersistentStateRef(txHash.toString(), index),
|
||||
consumingTxHash = id.toString(),
|
||||
|
@ -97,7 +97,8 @@ class RaftUniquenessProvider(private val services: ServiceHubInternal, private v
|
||||
fun start() {
|
||||
log.info("Creating Copycat server, log stored in: ${storagePath.toFile()}")
|
||||
val stateMachineFactory = {
|
||||
DistributedImmutableMap(db, RaftUniquenessProvider.Companion::createMap) }
|
||||
DistributedImmutableMap(db, RaftUniquenessProvider.Companion::createMap)
|
||||
}
|
||||
val address = raftConfig.nodeAddress.let { Address(it.host, it.port) }
|
||||
val storage = buildStorage(storagePath)
|
||||
val transport = buildTransport(transportConfiguration)
|
||||
@ -110,6 +111,7 @@ class RaftUniquenessProvider(private val services: ServiceHubInternal, private v
|
||||
serializer: Serializer) {
|
||||
writeMap(obj.entries, buffer, serializer)
|
||||
}
|
||||
|
||||
override fun read(type: Class<DistributedImmutableMap.Commands.PutAll<*, *>>,
|
||||
buffer: BufferInput<out BufferInput<*>>,
|
||||
serializer: Serializer): DistributedImmutableMap.Commands.PutAll<Any, Any> {
|
||||
|
@ -36,11 +36,11 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
// incrementally build list of root entities (for later use in Sort parsing)
|
||||
private val rootEntities = mutableMapOf<Class<out PersistentState>, Root<*>>(Pair(VaultSchemaV1.VaultStates::class.java, vaultStates))
|
||||
private val aggregateExpressions = mutableListOf<Expression<*>>()
|
||||
private val commonPredicates = mutableMapOf<Pair<String,Operator>, Predicate>() // schema attribute Name, operator -> predicate
|
||||
private val commonPredicates = mutableMapOf<Pair<String, Operator>, Predicate>() // schema attribute Name, operator -> predicate
|
||||
|
||||
var stateTypes: Vault.StateStatus = Vault.StateStatus.UNCONSUMED
|
||||
|
||||
override fun parseCriteria(criteria: QueryCriteria.VaultQueryCriteria) : Collection<Predicate> {
|
||||
override fun parseCriteria(criteria: QueryCriteria.VaultQueryCriteria): Collection<Predicate> {
|
||||
log.trace { "Parsing VaultQueryCriteria: $criteria" }
|
||||
val predicateSet = mutableSetOf<Predicate>()
|
||||
|
||||
@ -48,7 +48,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
criteria.softLockingCondition?.let {
|
||||
val softLocking = criteria.softLockingCondition
|
||||
val type = softLocking!!.type
|
||||
when(type) {
|
||||
when (type) {
|
||||
QueryCriteria.SoftLockingType.UNLOCKED_ONLY ->
|
||||
predicateSet.add(criteriaBuilder.and(vaultStates.get<String>("lockId").isNull))
|
||||
QueryCriteria.SoftLockingType.LOCKED_ONLY ->
|
||||
@ -154,7 +154,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
}
|
||||
|
||||
private fun <O> parseExpression(entityRoot: Root<O>, expression: CriteriaExpression<O, Boolean>, predicateSet: MutableSet<Predicate>) {
|
||||
if (expression is CriteriaExpression.AggregateFunctionExpression<O,*>) {
|
||||
if (expression is CriteriaExpression.AggregateFunctionExpression<O, *>) {
|
||||
parseAggregateFunction(entityRoot, expression)
|
||||
} else {
|
||||
predicateSet.add(parseExpression(entityRoot, expression) as Predicate)
|
||||
@ -221,7 +221,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
}
|
||||
}
|
||||
|
||||
override fun parseCriteria(criteria: QueryCriteria.FungibleAssetQueryCriteria) : Collection<Predicate> {
|
||||
override fun parseCriteria(criteria: QueryCriteria.FungibleAssetQueryCriteria): Collection<Predicate> {
|
||||
log.trace { "Parsing FungibleAssetQueryCriteria: $criteria" }
|
||||
|
||||
val predicateSet = mutableSetOf<Predicate>()
|
||||
@ -265,7 +265,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
return predicateSet
|
||||
}
|
||||
|
||||
override fun parseCriteria(criteria: QueryCriteria.LinearStateQueryCriteria) : Collection<Predicate> {
|
||||
override fun parseCriteria(criteria: QueryCriteria.LinearStateQueryCriteria): Collection<Predicate> {
|
||||
log.trace { "Parsing LinearStateQueryCriteria: $criteria" }
|
||||
|
||||
val predicateSet = mutableSetOf<Predicate>()
|
||||
@ -314,8 +314,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
|
||||
// resolve general criteria expressions
|
||||
parseExpression(entityRoot, criteria.expression, predicateSet)
|
||||
}
|
||||
catch (e: Exception) {
|
||||
} catch (e: Exception) {
|
||||
e.message?.let { message ->
|
||||
if (message.contains("Not an entity"))
|
||||
throw VaultQueryException("""
|
||||
@ -386,8 +385,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
log.warn("Overriding previous attribute [${VaultSchemaV1.VaultStates::stateStatus.name}] value $existingStatus with ${criteria.status}")
|
||||
commonPredicates.replace(predicateID, criteriaBuilder.equal(vaultStates.get<Vault.StateStatus>(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status))
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
commonPredicates.put(predicateID, criteriaBuilder.equal(vaultStates.get<Vault.StateStatus>(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status))
|
||||
}
|
||||
}
|
||||
@ -417,7 +415,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
|
||||
sorting.columns.map { (sortAttribute, direction) ->
|
||||
val (entityStateClass, entityStateAttributeParent, entityStateAttributeChild) =
|
||||
when(sortAttribute) {
|
||||
when (sortAttribute) {
|
||||
is SortAttribute.Standard -> parse(sortAttribute.attribute)
|
||||
is SortAttribute.Custom -> Triple(sortAttribute.entityStateClass, sortAttribute.entityStateColumnName, null)
|
||||
}
|
||||
@ -451,8 +449,8 @@ class HibernateQueryCriteriaParser(val contractStateType: Class<out ContractStat
|
||||
}
|
||||
|
||||
private fun parse(sortAttribute: Sort.Attribute): Triple<Class<out PersistentState>, String, String?> {
|
||||
val entityClassAndColumnName : Triple<Class<out PersistentState>, String, String?> =
|
||||
when(sortAttribute) {
|
||||
val entityClassAndColumnName: Triple<Class<out PersistentState>, String, String?> =
|
||||
when (sortAttribute) {
|
||||
is Sort.CommonStateAttribute -> {
|
||||
Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeParent, sortAttribute.attributeChild)
|
||||
}
|
||||
|
@ -468,8 +468,7 @@ class NodeVaultService(private val clock: Clock, private val keyManagementServic
|
||||
vaultState.lockId,
|
||||
vaultState.lockUpdateTime))
|
||||
statesAndRefs.add(StateAndRef(state, stateRef))
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
// TODO: improve typing of returned other results
|
||||
log.debug { "OtherResults: ${Arrays.toString(result.toArray())}" }
|
||||
otherResults.addAll(result.toArray().asList())
|
||||
|
@ -59,7 +59,7 @@ class FlowWatchPrintingSubscriber(private val toStream: RenderPrintWriter) : Sub
|
||||
}
|
||||
|
||||
private fun createStateMachinesTable(): TableElement {
|
||||
val table = TableElement(1,2,1,2).overflow(Overflow.HIDDEN).rightCellPadding(1)
|
||||
val table = TableElement(1, 2, 1, 2).overflow(Overflow.HIDDEN).rightCellPadding(1)
|
||||
val header = RowElement(true).add("Id", "Flow name", "Initiator", "Status").style(Decoration.bold.fg(Color.black).bg(Color.white))
|
||||
table.add(header)
|
||||
return table
|
||||
@ -102,7 +102,7 @@ class FlowWatchPrintingSubscriber(private val toStream: RenderPrintWriter) : Sub
|
||||
}
|
||||
|
||||
private fun formatFlowId(flowId: StateMachineRunId): String {
|
||||
return flowId.toString().removeSurrounding("[","]")
|
||||
return flowId.toString().removeSurrounding("[", "]")
|
||||
}
|
||||
|
||||
private fun formatFlowInitiator(flowInitiator: FlowInitiator): String {
|
||||
@ -117,7 +117,7 @@ class FlowWatchPrintingSubscriber(private val toStream: RenderPrintWriter) : Sub
|
||||
|
||||
private fun formatFlowResult(flowResult: Try<*>): String {
|
||||
fun successFormat(value: Any?): String {
|
||||
return when(value) {
|
||||
return when (value) {
|
||||
is SignedTransaction -> "Tx ID: " + value.id.toString()
|
||||
is kotlin.Unit -> "No return value"
|
||||
null -> "No return value"
|
||||
|
@ -247,11 +247,11 @@ object InteractiveShell {
|
||||
// Wait for the flow to end and the progress tracker to notice. By the time the latch is released
|
||||
// the tracker is done with the screen.
|
||||
latch.await()
|
||||
} catch(e: InterruptedException) {
|
||||
} catch (e: InterruptedException) {
|
||||
ANSIProgressRenderer.progressTracker = null
|
||||
// TODO: When the flow framework allows us to kill flows mid-flight, do so here.
|
||||
}
|
||||
} catch(e: NoApplicableConstructor) {
|
||||
} catch (e: NoApplicableConstructor) {
|
||||
output.println("No matching constructor found:", Color.red)
|
||||
e.errors.forEach { output.println("- $it", Color.red) }
|
||||
} finally {
|
||||
@ -305,14 +305,14 @@ object InteractiveShell {
|
||||
continue
|
||||
}
|
||||
return invoke(flow)
|
||||
} catch(e: StringToMethodCallParser.UnparseableCallException.MissingParameter) {
|
||||
} catch (e: StringToMethodCallParser.UnparseableCallException.MissingParameter) {
|
||||
errors.add("${getPrototype()}: missing parameter ${e.paramName}")
|
||||
} catch(e: StringToMethodCallParser.UnparseableCallException.TooManyParameters) {
|
||||
} catch (e: StringToMethodCallParser.UnparseableCallException.TooManyParameters) {
|
||||
errors.add("${getPrototype()}: too many parameters")
|
||||
} catch(e: StringToMethodCallParser.UnparseableCallException.ReflectionDataMissing) {
|
||||
} catch (e: StringToMethodCallParser.UnparseableCallException.ReflectionDataMissing) {
|
||||
val argTypes = ctor.parameterTypes.map { it.simpleName }
|
||||
errors.add("$argTypes: <constructor missing parameter reflection data>")
|
||||
} catch(e: StringToMethodCallParser.UnparseableCallException) {
|
||||
} catch (e: StringToMethodCallParser.UnparseableCallException) {
|
||||
val argTypes = ctor.parameterTypes.map { it.simpleName }
|
||||
errors.add("$argTypes: ${e.message}")
|
||||
}
|
||||
@ -506,7 +506,7 @@ object InteractiveShell {
|
||||
} finally {
|
||||
try {
|
||||
value.close()
|
||||
} catch(e: IOException) {
|
||||
} catch (e: IOException) {
|
||||
// Ignore.
|
||||
}
|
||||
}
|
||||
|
@ -9,9 +9,9 @@ import java.util.*
|
||||
* behaviour is unpredictable! There is a best-effort check for double inserts, but this should *not* be relied on, so
|
||||
* ONLY USE THIS IF YOUR TABLE IS APPEND-ONLY
|
||||
*/
|
||||
class AppendOnlyPersistentMap<K, V, E, out EK> (
|
||||
class AppendOnlyPersistentMap<K, V, E, out EK>(
|
||||
val toPersistentEntityKey: (K) -> EK,
|
||||
val fromPersistentEntity: (E) -> Pair<K,V>,
|
||||
val fromPersistentEntity: (E) -> Pair<K, V>,
|
||||
val toPersistentEntity: (key: K, value: V) -> E,
|
||||
val persistentEntityClass: Class<E>,
|
||||
cacheBound: Long = 1024
|
||||
@ -48,10 +48,11 @@ class AppendOnlyPersistentMap<K, V, E, out EK> (
|
||||
return result.map { x -> fromPersistentEntity(x) }.asSequence()
|
||||
}
|
||||
|
||||
private tailrec fun set(key: K, value: V, logWarning: Boolean, store: (K,V) -> V?): Boolean {
|
||||
private tailrec fun set(key: K, value: V, logWarning: Boolean, store: (K, V) -> V?): Boolean {
|
||||
var insertionAttempt = false
|
||||
var isUnique = true
|
||||
val existingInCache = cache.get(key) { // Thread safe, if multiple threads may wait until the first one has loaded.
|
||||
val existingInCache = cache.get(key) {
|
||||
// Thread safe, if multiple threads may wait until the first one has loaded.
|
||||
insertionAttempt = true
|
||||
// Key wasn't in the cache and might be in the underlying storage.
|
||||
// Depending on 'store' method, this may insert without checking key duplication or it may avoid inserting a duplicated key.
|
||||
@ -85,8 +86,8 @@ class AppendOnlyPersistentMap<K, V, E, out EK> (
|
||||
* If the map previously contained a mapping for the key, the behaviour is unpredictable and may throw an error from the underlying storage.
|
||||
*/
|
||||
operator fun set(key: K, value: V) =
|
||||
set(key, value, logWarning = false) {
|
||||
k, v -> DatabaseTransactionManager.current().session.save(toPersistentEntity(k, v))
|
||||
set(key, value, logWarning = false) { k, v ->
|
||||
DatabaseTransactionManager.current().session.save(toPersistentEntity(k, v))
|
||||
null
|
||||
}
|
||||
|
||||
@ -96,8 +97,7 @@ class AppendOnlyPersistentMap<K, V, E, out EK> (
|
||||
* @return true if added key was unique, otherwise false
|
||||
*/
|
||||
fun addWithDuplicatesAllowed(key: K, value: V, logWarning: Boolean = true): Boolean =
|
||||
set(key, value, logWarning) {
|
||||
k, v ->
|
||||
set(key, value, logWarning) { k, v ->
|
||||
val existingEntry = DatabaseTransactionManager.current().session.find(persistentEntityClass, toPersistentEntityKey(k))
|
||||
if (existingEntry == null) {
|
||||
DatabaseTransactionManager.current().session.save(toPersistentEntity(k, v))
|
||||
@ -107,7 +107,7 @@ class AppendOnlyPersistentMap<K, V, E, out EK> (
|
||||
}
|
||||
}
|
||||
|
||||
fun putAll(entries: Map<K,V>) {
|
||||
fun putAll(entries: Map<K, V>) {
|
||||
entries.forEach {
|
||||
set(it.key, it.value)
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ const val NODE_DATABASE_PREFIX = "node_"
|
||||
|
||||
//HikariDataSource implements Closeable which allows CordaPersistence to be Closeable
|
||||
class CordaPersistence(var dataSource: HikariDataSource, private val schemaService: SchemaService,
|
||||
private val createIdentityService: ()-> IdentityService, databaseProperties: Properties): Closeable {
|
||||
private val createIdentityService: () -> IdentityService, databaseProperties: Properties) : Closeable {
|
||||
var transactionIsolationLevel = parserTransactionIsolationLevel(databaseProperties.getProperty("transactionIsolationLevel"))
|
||||
|
||||
val hibernateConfig: HibernateConfiguration by lazy {
|
||||
@ -70,8 +70,7 @@ class CordaPersistence(var dataSource: HikariDataSource, private val schemaServi
|
||||
|
||||
return if (outer != null) {
|
||||
outer.statement()
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
inTopLevelTransaction(transactionIsolation, repetitionAttempts, statement)
|
||||
}
|
||||
}
|
||||
@ -84,19 +83,16 @@ class CordaPersistence(var dataSource: HikariDataSource, private val schemaServi
|
||||
val answer = transaction.statement()
|
||||
transaction.commit()
|
||||
return answer
|
||||
}
|
||||
catch (e: SQLException) {
|
||||
} catch (e: SQLException) {
|
||||
transaction.rollback()
|
||||
repetitions++
|
||||
if (repetitions >= repetitionAttempts) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
catch (e: Throwable) {
|
||||
} catch (e: Throwable) {
|
||||
transaction.rollback()
|
||||
throw e
|
||||
}
|
||||
finally {
|
||||
} finally {
|
||||
transaction.close()
|
||||
}
|
||||
}
|
||||
@ -170,7 +166,7 @@ private class DatabaseTransactionWrappingSubscriber<U>(val db: CordaPersistence?
|
||||
}
|
||||
|
||||
// A subscriber that wraps another but does not pass on observations to it.
|
||||
private class NoOpSubscriber<U>(t: Subscriber<in U>): Subscriber<U>(t) {
|
||||
private class NoOpSubscriber<U>(t: Subscriber<in U>) : Subscriber<U>(t) {
|
||||
override fun onCompleted() {
|
||||
}
|
||||
|
||||
|
@ -30,7 +30,7 @@ class DatabaseTransaction(isolation: Int, val threadLocal: ThreadLocal<DatabaseT
|
||||
}
|
||||
|
||||
val session: Session by sessionDelegate
|
||||
private lateinit var hibernateTransaction : Transaction
|
||||
private lateinit var hibernateTransaction: Transaction
|
||||
|
||||
private val outerTransaction: DatabaseTransaction? = threadLocal.get()
|
||||
|
||||
|
@ -8,7 +8,7 @@ import com.google.common.util.concurrent.ListenableFuture
|
||||
|
||||
class NonInvalidatingCache<K, V> private constructor(
|
||||
val cache: LoadingCache<K, V>
|
||||
): LoadingCache<K, V> by cache {
|
||||
) : LoadingCache<K, V> by cache {
|
||||
|
||||
constructor(bound: Long, concurrencyLevel: Int, loadFunction: (K) -> V) :
|
||||
this(buildCache(bound, concurrencyLevel, loadFunction))
|
||||
@ -25,6 +25,7 @@ class NonInvalidatingCache<K, V> private constructor(
|
||||
override fun reload(key: K, oldValue: V): ListenableFuture<V> {
|
||||
throw IllegalStateException("Non invalidating cache refreshed")
|
||||
}
|
||||
|
||||
override fun load(key: K) = loadFunction(key)
|
||||
override fun loadAll(keys: Iterable<K>): MutableMap<K, V> {
|
||||
return super.loadAll(keys)
|
||||
|
@ -6,10 +6,10 @@ import com.google.common.util.concurrent.ListenableFuture
|
||||
|
||||
class NonInvalidatingUnboundCache<K, V> private constructor(
|
||||
val cache: LoadingCache<K, V>
|
||||
): LoadingCache<K, V> by cache {
|
||||
) : LoadingCache<K, V> by cache {
|
||||
|
||||
constructor(concurrencyLevel: Int, loadFunction: (K) -> V, removalListener: RemovalListener<K, V> = RemovalListener {},
|
||||
keysToPreload: () -> Iterable<K> = { emptyList() } ) :
|
||||
keysToPreload: () -> Iterable<K> = { emptyList() }) :
|
||||
this(buildCache(concurrencyLevel, loadFunction, removalListener, keysToPreload))
|
||||
|
||||
private companion object {
|
||||
@ -27,6 +27,7 @@ class NonInvalidatingUnboundCache<K, V> private constructor(
|
||||
override fun reload(key: K, oldValue: V): ListenableFuture<V> {
|
||||
throw IllegalStateException("Non invalidating cache refreshed")
|
||||
}
|
||||
|
||||
override fun load(key: K) = loadFunction(key)
|
||||
override fun loadAll(keys: Iterable<K>): MutableMap<K, V> {
|
||||
return super.loadAll(keys)
|
||||
|
@ -11,9 +11,9 @@ import java.util.*
|
||||
/**
|
||||
* Implements an unbound caching layer on top of a table accessed via Hibernate mapping.
|
||||
*/
|
||||
class PersistentMap<K, V, E, out EK> (
|
||||
class PersistentMap<K, V, E, out EK>(
|
||||
val toPersistentEntityKey: (K) -> EK,
|
||||
val fromPersistentEntity: (E) -> Pair<K,V>,
|
||||
val fromPersistentEntity: (E) -> Pair<K, V>,
|
||||
val toPersistentEntity: (key: K, value: V) -> E,
|
||||
val persistentEntityClass: Class<E>
|
||||
) : MutableMap<K, V>, AbstractMap<K, V>() {
|
||||
@ -34,7 +34,7 @@ class PersistentMap<K, V, E, out EK> (
|
||||
getAll(session.createQuery(criteriaQuery).resultList.map { e -> fromPersistentEntity(e as E).first }.asIterable())
|
||||
}
|
||||
|
||||
class ExplicitRemoval<K, V, E, EK>(private val toPersistentEntityKey: (K) -> EK, private val persistentEntityClass: Class<E>): RemovalListener<K,V> {
|
||||
class ExplicitRemoval<K, V, E, EK>(private val toPersistentEntityKey: (K) -> EK, private val persistentEntityClass: Class<E>) : RemovalListener<K, V> {
|
||||
override fun onRemoval(notification: RemovalNotification<K, V>?) {
|
||||
when (notification?.cause) {
|
||||
RemovalCause.EXPLICIT -> {
|
||||
@ -47,7 +47,8 @@ class PersistentMap<K, V, E, out EK> (
|
||||
RemovalCause.EXPIRED, RemovalCause.SIZE, RemovalCause.COLLECTED -> {
|
||||
log.error("Entry was removed from cache!!!")
|
||||
}
|
||||
RemovalCause.REPLACED -> {}
|
||||
RemovalCause.REPLACED -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -62,10 +63,11 @@ class PersistentMap<K, V, E, out EK> (
|
||||
|
||||
override val size get() = cache.size().toInt()
|
||||
|
||||
private tailrec fun set(key: K, value: V, logWarning: Boolean = true, store: (K,V) -> V?, replace: (K, V) -> Unit) : Boolean {
|
||||
private tailrec fun set(key: K, value: V, logWarning: Boolean = true, store: (K, V) -> V?, replace: (K, V) -> Unit): Boolean {
|
||||
var insertionAttempt = false
|
||||
var isUnique = true
|
||||
val existingInCache = cache.get(key) { // Thread safe, if multiple threads may wait until the first one has loaded.
|
||||
val existingInCache = cache.get(key) {
|
||||
// Thread safe, if multiple threads may wait until the first one has loaded.
|
||||
insertionAttempt = true
|
||||
// Value wasn't in the cache and wasn't in DB (because the cache is unbound).
|
||||
// Store the value, depending on store implementation this may replace existing entry in DB.
|
||||
@ -145,10 +147,10 @@ class PersistentMap<K, V, E, out EK> (
|
||||
private fun merge(key: K, value: V): V? {
|
||||
val existingEntry = DatabaseTransactionManager.current().session.find(persistentEntityClass, toPersistentEntityKey(key))
|
||||
return if (existingEntry != null) {
|
||||
DatabaseTransactionManager.current().session.merge(toPersistentEntity(key,value))
|
||||
DatabaseTransactionManager.current().session.merge(toPersistentEntity(key, value))
|
||||
fromPersistentEntity(existingEntry).second
|
||||
} else {
|
||||
DatabaseTransactionManager.current().session.save(toPersistentEntity(key,value))
|
||||
DatabaseTransactionManager.current().session.save(toPersistentEntity(key, value))
|
||||
null
|
||||
}
|
||||
}
|
||||
@ -193,7 +195,8 @@ class PersistentMap<K, V, E, out EK> (
|
||||
}
|
||||
}
|
||||
|
||||
override val keys: MutableSet<K> get() {
|
||||
override val keys: MutableSet<K>
|
||||
get() {
|
||||
return object : AbstractSet<K>() {
|
||||
override val size: Int get() = this@PersistentMap.size
|
||||
override fun iterator(): MutableIterator<K> {
|
||||
@ -210,7 +213,8 @@ class PersistentMap<K, V, E, out EK> (
|
||||
}
|
||||
}
|
||||
|
||||
override val values: MutableCollection<V> get() {
|
||||
override val values: MutableCollection<V>
|
||||
get() {
|
||||
return object : AbstractCollection<V>() {
|
||||
override val size: Int get() = this@PersistentMap.size
|
||||
override fun iterator(): MutableIterator<V> {
|
||||
@ -227,7 +231,8 @@ class PersistentMap<K, V, E, out EK> (
|
||||
}
|
||||
}
|
||||
|
||||
override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() {
|
||||
override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
|
||||
get() {
|
||||
return object : AbstractSet<MutableMap.MutableEntry<K, V>>() {
|
||||
override val size: Int get() = this@PersistentMap.size
|
||||
override fun iterator(): MutableIterator<MutableMap.MutableEntry<K, V>> {
|
||||
|
@ -21,7 +21,8 @@ class TestClock(private var delegateClock: Clock = Clock.systemUTC()) : MutableC
|
||||
|
||||
override fun toToken(context: SerializeAsTokenContext) = token.registerWithContext(context, this)
|
||||
|
||||
@Synchronized fun updateDate(date: LocalDate): Boolean {
|
||||
@Synchronized
|
||||
fun updateDate(date: LocalDate): Boolean {
|
||||
val currentDate = LocalDate.now(this)
|
||||
if (currentDate.isBefore(date)) {
|
||||
// It's ok to increment
|
||||
|
@ -157,7 +157,7 @@ public class VaultQueryJavaTests extends TestDependencyInjectionBase {
|
||||
UniqueIdentifier uid = linearState.component1().getData().getLinearId();
|
||||
|
||||
Vault<DealState> dealStates = VaultFiller.fillWithSomeTestDeals(services, dealIds);
|
||||
return new Triple(linearState,uid,dealStates);
|
||||
return new Triple(linearState, uid, dealStates);
|
||||
});
|
||||
database.transaction(tx -> {
|
||||
// consume states
|
||||
|
@ -272,6 +272,6 @@ class CordaRPCOpsImplTest {
|
||||
@StartableByRPC
|
||||
class VoidRPCFlow : FlowLogic<Void?>() {
|
||||
@Suspendable
|
||||
override fun call() : Void? = null
|
||||
override fun call(): Void? = null
|
||||
}
|
||||
}
|
||||
|
@ -84,4 +84,4 @@ class InteractiveShellTest {
|
||||
fun party() = check("party: \"${MEGA_CORP.name}\"", MEGA_CORP.name.toString())
|
||||
|
||||
class DummyFSM(val logic: FlowA) : FlowStateMachine<Any?> by mock()
|
||||
}
|
||||
}
|
||||
|
@ -9,25 +9,29 @@ import java.nio.file.Paths
|
||||
@InitiatingFlow
|
||||
class DummyFlow : FlowLogic<Unit>() {
|
||||
@Suspendable
|
||||
override fun call() { }
|
||||
override fun call() {
|
||||
}
|
||||
}
|
||||
|
||||
@InitiatedBy(DummyFlow::class)
|
||||
class LoaderTestFlow(unusedSession: FlowSession) : FlowLogic<Unit>() {
|
||||
@Suspendable
|
||||
override fun call() { }
|
||||
override fun call() {
|
||||
}
|
||||
}
|
||||
|
||||
@SchedulableFlow
|
||||
class DummySchedulableFlow : FlowLogic<Unit>() {
|
||||
@Suspendable
|
||||
override fun call() { }
|
||||
override fun call() {
|
||||
}
|
||||
}
|
||||
|
||||
@StartableByRPC
|
||||
class DummyRPCFlow : FlowLogic<Unit>() {
|
||||
@Suspendable
|
||||
override fun call() { }
|
||||
override fun call() {
|
||||
}
|
||||
}
|
||||
|
||||
class CordappLoaderTest {
|
||||
|
@ -80,6 +80,7 @@ class TwoPartyTradeFlowTests(val anonymous: Boolean) {
|
||||
return listOf(true, false)
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var mockNet: MockNetwork
|
||||
|
||||
@Before
|
||||
|
@ -153,7 +153,7 @@ class ScheduledFlowTests {
|
||||
val statesFromB: List<StateAndRef<ScheduledState>> = nodeB.database.transaction {
|
||||
queryStatesWithPaging(nodeB.services.vaultService)
|
||||
}
|
||||
assertEquals("Expect all states to be present",2 * N, statesFromA.count())
|
||||
assertEquals("Expect all states to be present", 2 * N, statesFromA.count())
|
||||
statesFromA.forEach { ref ->
|
||||
if (ref !in statesFromB) {
|
||||
throw IllegalStateException("State $ref is only present on node A.")
|
||||
|
@ -40,7 +40,9 @@ import kotlin.test.assertNull
|
||||
|
||||
//TODO This needs to be merged into P2PMessagingTest as that creates a more realistic environment
|
||||
class ArtemisMessagingTests : TestDependencyInjectionBase() {
|
||||
@Rule @JvmField val temporaryFolder = TemporaryFolder()
|
||||
@Rule
|
||||
@JvmField
|
||||
val temporaryFolder = TemporaryFolder()
|
||||
|
||||
val serverPort = freePort()
|
||||
val rpcPort = freePort()
|
||||
|
@ -44,7 +44,7 @@ abstract class AbstractNetworkMapServiceTest<out S : AbstractNetworkMapService>
|
||||
lateinit var alice: StartedNode<MockNode>
|
||||
|
||||
companion object {
|
||||
val subscriberLegalName = CordaX500Name(organisation ="Subscriber", locality ="New York", country ="US")
|
||||
val subscriberLegalName = CordaX500Name(organisation = "Subscriber", locality = "New York", country = "US")
|
||||
}
|
||||
|
||||
@Before
|
||||
|
@ -42,7 +42,8 @@ class DBTransactionStorageTests : TestDependencyInjectionBase() {
|
||||
database.transaction {
|
||||
|
||||
services = object : MockServices(BOB_KEY) {
|
||||
override val vaultService: VaultServiceInternal get() {
|
||||
override val vaultService: VaultServiceInternal
|
||||
get() {
|
||||
val vaultService = NodeVaultService(clock, keyManagementService, stateLoader, database.hibernateConfig)
|
||||
hibernatePersister = HibernateObserver(vaultService.rawUpdates, database.hibernateConfig)
|
||||
return vaultService
|
||||
|
@ -89,6 +89,7 @@ class HibernateConfigurationTest : TestDependencyInjectionBase() {
|
||||
// Refactored to use notifyAll() as we have no other unit test for that method with multiple transactions.
|
||||
vaultService.notifyAll(txs.map { it.tx })
|
||||
}
|
||||
|
||||
override fun jdbcSession() = database.createSession()
|
||||
}
|
||||
hibernatePersister = services.hibernatePersister
|
||||
@ -662,7 +663,8 @@ class HibernateConfigurationTest : TestDependencyInjectionBase() {
|
||||
queryResults.forEach {
|
||||
val contractState = it.contractState.deserialize<TransactionState<ContractState>>(context = SerializationDefaults.STORAGE_CONTEXT)
|
||||
val cashState = contractState.data as Cash.State
|
||||
println("${it.stateRef} with owner: ${cashState.owner.owningKey.toBase58String()}") }
|
||||
println("${it.stateRef} with owner: ${cashState.owner.owningKey.toBase58String()}")
|
||||
}
|
||||
|
||||
assertThat(queryResults).hasSize(12)
|
||||
}
|
||||
|
@ -41,7 +41,7 @@ class NodeSchemaServiceTest {
|
||||
*/
|
||||
@Test
|
||||
fun `auto scanning of custom schemas for testing with Driver`() {
|
||||
driver (startNodesInProcess = true) {
|
||||
driver(startNodesInProcess = true) {
|
||||
val node = startNode()
|
||||
val nodeHandle = node.getOrThrow()
|
||||
val result = nodeHandle.rpc.startFlow(::MappedSchemasFlow)
|
||||
@ -53,7 +53,7 @@ class NodeSchemaServiceTest {
|
||||
@StartableByRPC
|
||||
class MappedSchemasFlow : FlowLogic<List<String>>() {
|
||||
@Suspendable
|
||||
override fun call() : List<String> {
|
||||
override fun call(): List<String> {
|
||||
// returning MappedSchema's as String'ified family names to avoid whitelist serialization errors
|
||||
return (this.serviceHub as ServiceHubInternal).schemaService.schemaOptions.keys.map { it.name }
|
||||
}
|
||||
|
@ -702,8 +702,7 @@ class FlowFrameworkTests {
|
||||
private inline fun <reified P : FlowLogic<*>> StartedNode<*>.registerFlowFactory(
|
||||
initiatingFlowClass: KClass<out FlowLogic<*>>,
|
||||
initiatedFlowVersion: Int = 1,
|
||||
noinline flowFactory: (FlowSession) -> P): CordaFuture<P>
|
||||
{
|
||||
noinline flowFactory: (FlowSession) -> P): CordaFuture<P> {
|
||||
val observable = internals.internalRegisterFlowFactory(
|
||||
initiatingFlowClass.java,
|
||||
InitiatedFlowFactory.CorDapp(initiatedFlowVersion, "", flowFactory),
|
||||
@ -715,6 +714,7 @@ class FlowFrameworkTests {
|
||||
private fun sessionInit(clientFlowClass: KClass<out FlowLogic<*>>, flowVersion: Int = 1, payload: Any? = null): SessionInit {
|
||||
return SessionInit(0, clientFlowClass.java.name, flowVersion, "", payload)
|
||||
}
|
||||
|
||||
private fun sessionConfirm(flowVersion: Int = 1) = SessionConfirm(0, 0, flowVersion, "")
|
||||
private fun sessionData(payload: Any) = SessionData(0, payload)
|
||||
private val normalEnd = NormalSessionEnd(0)
|
||||
@ -766,7 +766,8 @@ class FlowFrameworkTests {
|
||||
private infix fun StartedNode<MockNode>.sent(message: SessionMessage): Pair<Int, SessionMessage> = Pair(internals.id, message)
|
||||
private infix fun Pair<Int, SessionMessage>.to(node: StartedNode<*>): SessionTransfer = SessionTransfer(first, second, node.network.myAddress)
|
||||
|
||||
private val FlowLogic<*>.progressSteps: CordaFuture<List<Notification<ProgressTracker.Step>>> get() {
|
||||
private val FlowLogic<*>.progressSteps: CordaFuture<List<Notification<ProgressTracker.Step>>>
|
||||
get() {
|
||||
return progressTracker!!.changes
|
||||
.ofType(Change.Position::class.java)
|
||||
.map { it.newStep }
|
||||
@ -782,7 +783,8 @@ class FlowFrameworkTests {
|
||||
}
|
||||
|
||||
private class NoOpFlow(val nonTerminating: Boolean = false) : FlowLogic<Unit>() {
|
||||
@Transient var flowStarted = false
|
||||
@Transient
|
||||
var flowStarted = false
|
||||
|
||||
@Suspendable
|
||||
override fun call() {
|
||||
@ -833,7 +835,8 @@ class FlowFrameworkTests {
|
||||
|
||||
override val progressTracker: ProgressTracker = ProgressTracker(START_STEP, RECEIVED_STEP)
|
||||
private var nonTerminating: Boolean = false
|
||||
@Transient var receivedPayloads: List<String> = emptyList()
|
||||
@Transient
|
||||
var receivedPayloads: List<String> = emptyList()
|
||||
|
||||
@Suspendable
|
||||
override fun call() {
|
||||
@ -879,6 +882,7 @@ class FlowFrameworkTests {
|
||||
@InitiatingFlow
|
||||
private class SendAndReceiveFlow(val otherParty: Party, val payload: Any, val otherPartySession: FlowSession? = null) : FlowLogic<Any>() {
|
||||
constructor(otherPartySession: FlowSession, payload: Any) : this(otherPartySession.counterparty, payload, otherPartySession)
|
||||
|
||||
@Suspendable
|
||||
override fun call(): Any = (otherPartySession ?: initiateFlow(otherParty)).sendAndReceive<Any>(payload).unwrap { it }
|
||||
}
|
||||
@ -891,8 +895,11 @@ class FlowFrameworkTests {
|
||||
@InitiatingFlow
|
||||
private class PingPongFlow(val otherParty: Party, val payload: Long, val otherPartySession: FlowSession? = null) : FlowLogic<Unit>() {
|
||||
constructor(otherPartySession: FlowSession, payload: Long) : this(otherPartySession.counterparty, payload, otherPartySession)
|
||||
@Transient var receivedPayload: Long? = null
|
||||
@Transient var receivedPayload2: Long? = null
|
||||
|
||||
@Transient
|
||||
var receivedPayload: Long? = null
|
||||
@Transient
|
||||
var receivedPayload2: Long? = null
|
||||
|
||||
@Suspendable
|
||||
override fun call() {
|
||||
@ -959,6 +966,7 @@ class FlowFrameworkTests {
|
||||
@InitiatingFlow(version = 2)
|
||||
private class UpgradedFlow(val otherParty: Party, val otherPartySession: FlowSession? = null) : FlowLogic<Pair<Any, Int>>() {
|
||||
constructor(otherPartySession: FlowSession) : this(otherPartySession.counterparty, otherPartySession)
|
||||
|
||||
@Suspendable
|
||||
override fun call(): Pair<Any, Int> {
|
||||
val otherPartySession = this.otherPartySession ?: initiateFlow(otherParty)
|
||||
|
@ -32,7 +32,8 @@ class PersistentUniquenessProviderTests : TestDependencyInjectionBase() {
|
||||
LogHelper.reset(PersistentUniquenessProvider::class)
|
||||
}
|
||||
|
||||
@Test fun `should commit a transaction with unused inputs without exception`() {
|
||||
@Test
|
||||
fun `should commit a transaction with unused inputs without exception`() {
|
||||
database.transaction {
|
||||
val provider = PersistentUniquenessProvider()
|
||||
val inputState = generateStateRef()
|
||||
@ -41,7 +42,8 @@ class PersistentUniquenessProviderTests : TestDependencyInjectionBase() {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `should report a conflict for a transaction with previously used inputs`() {
|
||||
@Test
|
||||
fun `should report a conflict for a transaction with previously used inputs`() {
|
||||
database.transaction {
|
||||
val provider = PersistentUniquenessProvider()
|
||||
val inputState = generateStateRef()
|
||||
|
@ -195,7 +195,7 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() {
|
||||
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId1).states).hasSize(3)
|
||||
}
|
||||
println("SOFT LOCK STATES #1 succeeded")
|
||||
} catch(e: Throwable) {
|
||||
} catch (e: Throwable) {
|
||||
println("SOFT LOCK STATES #1 failed")
|
||||
} finally {
|
||||
countDown.countDown()
|
||||
@ -211,7 +211,7 @@ class NodeVaultServiceTest : TestDependencyInjectionBase() {
|
||||
assertThat(vaultService.queryBy<Cash.State>(criteriaByLockId2).states).hasSize(3)
|
||||
}
|
||||
println("SOFT LOCK STATES #2 succeeded")
|
||||
} catch(e: Throwable) {
|
||||
} catch (e: Throwable) {
|
||||
println("SOFT LOCK STATES #2 failed")
|
||||
} finally {
|
||||
countDown.countDown()
|
||||
|
@ -1064,7 +1064,7 @@ class VaultQueryTests : TestDependencyInjectionBase() {
|
||||
}
|
||||
database.transaction {
|
||||
@Suppress("EXPECTED_CONDITION")
|
||||
val pagingSpec = PageSpecification(DEFAULT_PAGE_NUM, @Suppress("INTEGER_OVERFLOW")MAX_PAGE_SIZE + 1) // overflow = -2147483648
|
||||
val pagingSpec = PageSpecification(DEFAULT_PAGE_NUM, @Suppress("INTEGER_OVERFLOW") MAX_PAGE_SIZE + 1) // overflow = -2147483648
|
||||
val criteria = VaultQueryCriteria(status = Vault.StateStatus.ALL)
|
||||
vaultService.queryBy<ContractState>(criteria, paging = pagingSpec)
|
||||
}
|
||||
|
@ -174,7 +174,7 @@ class VaultWithCashTest : TestDependencyInjectionBase() {
|
||||
LOCKED: ${lockedStates2.count()} : $lockedStates2
|
||||
""")
|
||||
txn1
|
||||
} catch(e: Exception) {
|
||||
} catch (e: Exception) {
|
||||
println(e)
|
||||
}
|
||||
}
|
||||
@ -210,7 +210,7 @@ class VaultWithCashTest : TestDependencyInjectionBase() {
|
||||
LOCKED: ${lockedStates2.count()} : $lockedStates2
|
||||
""")
|
||||
txn2
|
||||
} catch(e: Exception) {
|
||||
} catch (e: Exception) {
|
||||
println(e)
|
||||
}
|
||||
}
|
||||
@ -254,7 +254,8 @@ class VaultWithCashTest : TestDependencyInjectionBase() {
|
||||
val linearId = UniqueIdentifier()
|
||||
|
||||
val dummyIssue =
|
||||
database.transaction { // Issue a linear state
|
||||
database.transaction {
|
||||
// Issue a linear state
|
||||
val dummyIssueBuilder = TransactionBuilder(notary = DUMMY_NOTARY)
|
||||
.addOutputState(DummyLinearContract.State(linearId = linearId, participants = listOf(freshIdentity)), DUMMY_LINEAR_CONTRACT_PROGRAM_ID)
|
||||
.addCommand(dummyCommand(notaryServices.myInfo.chooseIdentity().owningKey))
|
||||
|
@ -11,12 +11,14 @@ class AffinityExecutorTests {
|
||||
var _executor: AffinityExecutor.ServiceAffinityExecutor? = null
|
||||
val executor: AffinityExecutor.ServiceAffinityExecutor get() = _executor!!
|
||||
|
||||
@After fun shutdown() {
|
||||
@After
|
||||
fun shutdown() {
|
||||
_executor?.shutdown()
|
||||
_executor = null
|
||||
}
|
||||
|
||||
@Test fun `flush handles nested executes`() {
|
||||
@Test
|
||||
fun `flush handles nested executes`() {
|
||||
_executor = AffinityExecutor.ServiceAffinityExecutor("test4", 1)
|
||||
var nestedRan = false
|
||||
val latch = CountDownLatch(1)
|
||||
@ -29,7 +31,8 @@ class AffinityExecutorTests {
|
||||
assertTrue(nestedRan)
|
||||
}
|
||||
|
||||
@Test fun `single threaded affinity executor runs on correct thread`() {
|
||||
@Test
|
||||
fun `single threaded affinity executor runs on correct thread`() {
|
||||
val thisThread = Thread.currentThread()
|
||||
_executor = AffinityExecutor.ServiceAffinityExecutor("test thread", 1)
|
||||
assertTrue(!executor.isOnThread)
|
||||
@ -50,7 +53,8 @@ class AffinityExecutorTests {
|
||||
assertEquals(thread2.get(), thread.get())
|
||||
}
|
||||
|
||||
@Test fun `pooled executor`() {
|
||||
@Test
|
||||
fun `pooled executor`() {
|
||||
_executor = AffinityExecutor.ServiceAffinityExecutor("test2", 3)
|
||||
assertFalse(executor.isOnThread)
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user