Reformat files in node

This commit is contained in:
Tommy Lillehagen 2017-10-06 15:24:53 +01:00
parent 7a372bed59
commit cb9e27a84a
69 changed files with 448 additions and 393 deletions

View File

@ -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

View File

@ -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,

View File

@ -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() {

View File

@ -115,8 +115,8 @@ open class NodeStartup(val args: Array<String>) {
}
}
},
{
th -> logger.error("Unexpected exception during registration", th)
{ th ->
logger.error("Unexpected exception during registration", th)
})
startedNode.internals.run()
}

View File

@ -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.

View File

@ -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

View File

@ -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>()
}
@ -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()}")

View File

@ -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()

View File

@ -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"

View File

@ -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,
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
@ -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)
}
}

View File

@ -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() {
}
}

View File

@ -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 {

View File

@ -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()
}

View File

@ -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) {

View File

@ -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()

View File

@ -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())
})
}
}

View File

@ -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) {
@ -558,7 +559,8 @@ val Class<out FlowLogic<*>>.flowVersionAndInitiatingClass: Pair<Int, Class<out F
}
}
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")

View File

@ -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> {

View File

@ -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))
}
}

View File

@ -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())

View File

@ -51,7 +51,8 @@ class AppendOnlyPersistentMap<K, V, E, out EK> (
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))

View File

@ -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()
}
}

View File

@ -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)

View File

@ -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)

View File

@ -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 -> {
}
}
}
}
@ -65,7 +66,8 @@ class PersistentMap<K, V, E, out EK> (
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.
@ -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>> {

View File

@ -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

View File

@ -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 {

View File

@ -80,6 +80,7 @@ class TwoPartyTradeFlowTests(val anonymous: Boolean) {
return listOf(true, false)
}
}
private lateinit var mockNet: MockNetwork
@Before

View File

@ -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()

View File

@ -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

View File

@ -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)
}

View File

@ -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)

View File

@ -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()

View File

@ -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))

View File

@ -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)