Run the IntelliJ reformatter across the Kotlin code. Did not reformat JS/web code.

This commit is contained in:
Mike Hearn
2016-11-30 14:40:34 +00:00
parent 4a9f5cafc1
commit 7b40be8361
149 changed files with 763 additions and 618 deletions

View File

@ -1,7 +1,7 @@
package net.corda.node.utilities
import net.corda.testing.node.makeTestDataSourceProperties
import junit.framework.TestSuite
import net.corda.testing.node.makeTestDataSourceProperties
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.Transaction
@ -136,7 +136,7 @@ class JDBCHashMapTestSuite {
*/
class JDBCHashMapTestGenerator(val loadOnInit: Boolean, val constrained: Boolean) : com.google.common.collect.testing.TestStringMapGenerator() {
override fun create(elements: Array<Map.Entry<String, String>>): Map<String, String> {
val map = if (loadOnInit) loadOnInitTrueMap else if(constrained) memoryConstrainedMap else loadOnInitFalseMap
val map = if (loadOnInit) loadOnInitTrueMap else if (constrained) memoryConstrainedMap else loadOnInitFalseMap
map.clear()
map.putAll(elements.associate { Pair(it.key, it.value) })
return map
@ -178,7 +178,7 @@ class JDBCHashMapTestSuite {
*/
class JDBCHashSetTestGenerator(val loadOnInit: Boolean, val constrained: Boolean) : com.google.common.collect.testing.TestStringSetGenerator() {
override fun create(elements: Array<String>): Set<String> {
val set = if (loadOnInit) loadOnInitTrueSet else if(constrained) memoryConstrainedSet else loadOnInitFalseSet
val set = if (loadOnInit) loadOnInitTrueSet else if (constrained) memoryConstrainedSet else loadOnInitFalseSet
set.clear()
set.addAll(elements)
return set

View File

@ -2,12 +2,9 @@
// must also be in the default package. When using Kotlin there are a whole host of exceptions
// trying to construct this from Capsule, so it is written in Java.
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class CordaCaplet extends Capsule {
@ -23,7 +20,7 @@ public class CordaCaplet extends Capsule {
protected <T> T attribute(Map.Entry<String, T> attr) {
// Equality is used here because Capsule never instantiates these attributes but instead reuses the ones
// defined as public static final fields on the Capsule class, therefore referential equality is safe.
if(ATTR_APP_CLASS_PATH == attr) {
if (ATTR_APP_CLASS_PATH == attr) {
T cp = super.attribute(attr);
List<Path> classpath = augmentClasspath((List<Path>) cp, "plugins");
return (T) augmentClasspath(classpath, "dependencies");
@ -35,7 +32,7 @@ public class CordaCaplet extends Capsule {
// TODO: Add working directory variable to capsules string replacement variables.
private List<Path> augmentClasspath(List<Path> classpath, String dirName) {
File dir = new File(dirName);
if(!dir.exists()) {
if (!dir.exists()) {
dir.mkdir();
}

View File

@ -95,7 +95,8 @@ sealed class PortAllocation {
val portCounter = AtomicInteger(startingPort)
override fun nextPort() = portCounter.andIncrement
}
class RandomFree(): PortAllocation() {
class RandomFree() : PortAllocation() {
override fun nextPort(): Int {
return ServerSocket().use {
it.bind(InetSocketAddress(0))
@ -128,7 +129,7 @@ sealed class PortAllocation {
* @param isDebug Indicates whether the spawned nodes should start in jdwt debug mode.
* @param dsl The dsl itself.
* @return The value returned in the [dsl] closure.
*/
*/
fun <A> driver(
driverDirectory: Path = Paths.get("build", getTimestampAsDirectoryName()),
portAllocation: PortAllocation = PortAllocation.Incremental(10000),
@ -233,6 +234,7 @@ open class DriverDSL(
val clients = LinkedList<NodeMessagingClient>()
var localServer: ArtemisMessagingServer? = null
}
private val state = ThreadBox(State())
//TODO: remove this once we can bundle quasar properly.
@ -394,6 +396,7 @@ open class DriverDSL(
"Bob",
"Bank"
)
fun <A> pickA(array: Array<A>): A = array[Math.abs(Random().nextInt()) % array.size]
private fun startNode(
@ -409,7 +412,7 @@ open class DriverDSL(
val classpath = System.getProperty("java.class.path")
val path = System.getProperty("java.home") + separator + "bin" + separator + "java"
val debugPortArg = if(debugPort != null)
val debugPortArg = if (debugPort != null)
listOf("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$debugPort")
else
emptyList()

View File

@ -41,6 +41,7 @@ class CordaRPCOpsImpl(
Pair(vault.states.toList(), updates)
}
}
override fun verifiedTransactions(): Pair<List<SignedTransaction>, Observable<SignedTransaction>> {
return databaseTransaction(database) {
services.storageService.validatedTransactions.track()
@ -67,7 +68,7 @@ class CordaRPCOpsImpl(
override fun addVaultTransactionNote(txnId: SecureHash, txnNote: String) {
return databaseTransaction(database) {
services.vaultService.addNoteToTransaction(txnId, txnNote)
services.vaultService.addNoteToTransaction(txnId, txnNote)
}
}

View File

@ -25,7 +25,7 @@ interface CheckpointStorage {
* The checkpoints are only valid during the lifetime of a single call to the block, to allow memory management.
* Return false from the block to terminate further iteration.
*/
fun forEach(block: (Checkpoint)->Boolean)
fun forEach(block: (Checkpoint) -> Boolean)
}

View File

@ -118,6 +118,7 @@ fun configureTestSSL(): NodeSSLConfiguration = object : NodeSSLConfiguration {
override val certificatesPath = Files.createTempDirectory("certs")
override val keyStorePassword: String get() = "cordacadevpass"
override val trustStorePassword: String get() = "trustpass"
init {
configureWithDevSSLCertificate()
}

View File

@ -53,14 +53,14 @@ class FullNodeConfiguration(val config: Config) : NodeConfiguration {
val notaryNodeAddress: HostAndPort? by config.getOrElse { null }
val notaryClusterAddresses: List<HostAndPort> = config.getListOrElse<String>("notaryClusterAddresses") { emptyList<String>() }.map { HostAndPort.fromString(it) }
val rpcUsers: List<User> =
config.getListOrElse<Config>("rpcUsers") { emptyList() }
.map {
val username = it.getString("user")
require(username.matches("\\w+".toRegex())) { "Username $username contains invalid characters" }
val password = it.getString("password")
val permissions = it.getListOrElse<String>("permissions") { emptyList() }.toSet()
User(username, password, permissions)
}
config.getListOrElse<Config>("rpcUsers") { emptyList() }
.map {
val username = it.getString("user")
require(username.matches("\\w+".toRegex())) { "Username $username contains invalid characters" }
val password = it.getString("password")
val permissions = it.getListOrElse<String>("permissions") { emptyList() }.toSet()
User(username, password, permissions)
}
fun createNode(): Node {
// This is a sanity feature do not remove.
@ -74,7 +74,7 @@ class FullNodeConfiguration(val config: Config) : NodeConfiguration {
}
if (networkMapAddress == null) advertisedServices.add(ServiceInfo(NetworkMapService.type))
val networkMapMessageAddress: SingleMessageRecipient? = if (networkMapAddress == null) null else NodeMessagingClient.makeNetworkMapAddress(networkMapAddress!!)
return Node(this, networkMapMessageAddress, advertisedServices, if(useTestClock == true) TestClock() else NodeClock())
return Node(this, networkMapMessageAddress, advertisedServices, if (useTestClock == true) TestClock() else NodeClock())
}
}

View File

@ -47,7 +47,7 @@ class NodeSchedulerService(private val database: Database,
private val services: ServiceHubInternal,
private val flowLogicRefFactory: FlowLogicRefFactory,
private val schedulerTimerExecutor: Executor = Executors.newSingleThreadExecutor())
: SchedulerService, SingletonSerializeAsToken() {
: SchedulerService, SingletonSerializeAsToken() {
private val log = loggerFor<NodeSchedulerService>()
@ -170,7 +170,7 @@ class NodeSchedulerService(private val database: Database,
// Ensure we are still scheduled.
val scheduledLogic: FlowLogic<*>? = getScheduledLogic()
if(scheduledLogic != null) {
if (scheduledLogic != null) {
subFlow(scheduledLogic)
}
}

View File

@ -84,7 +84,7 @@ abstract class ArtemisMessagingComponent() : SingletonSerializeAsToken() {
* For instance it may contain onion routing data.
*/
data class NodeAddress(val identity: CompositeKey, override val hostAndPort: HostAndPort) : SingleMessageRecipient, ArtemisAddress {
override val queueName: SimpleString by lazy { SimpleString(PEERS_PREFIX+identity.toBase58String()) }
override val queueName: SimpleString by lazy { SimpleString(PEERS_PREFIX + identity.toBase58String()) }
override fun toString(): String = "${javaClass.simpleName}(identity = $queueName, $hostAndPort)"
}
@ -117,10 +117,10 @@ abstract class ArtemisMessagingComponent() : SingletonSerializeAsToken() {
*/
fun checkStorePasswords() {
config.keyStorePath.read {
KeyStore.getInstance("JKS").load(it, config.keyStorePassword.toCharArray())
KeyStore.getInstance("JKS").load(it, config.keyStorePassword.toCharArray())
}
config.trustStorePath.read {
KeyStore.getInstance("JKS").load(it, config.trustStorePassword.toCharArray())
KeyStore.getInstance("JKS").load(it, config.trustStorePassword.toCharArray())
}
}

View File

@ -104,13 +104,13 @@ class NodeMessagingClient(override val config: NodeConfiguration,
}
private val processedMessages: MutableSet<UUID> = Collections.synchronizedSet(
object : AbstractJDBCHashSet<UUID, Table>(Table, loadOnInit = true) {
override fun elementFromRow(row: ResultRow): UUID = row[table.uuid]
object : AbstractJDBCHashSet<UUID, Table>(Table, loadOnInit = true) {
override fun elementFromRow(row: ResultRow): UUID = row[table.uuid]
override fun addElementToInsert(insert: InsertStatement, entry: UUID, finalizables: MutableList<() -> Unit>) {
insert[table.uuid] = entry
}
})
override fun addElementToInsert(insert: InsertStatement, entry: UUID, finalizables: MutableList<() -> Unit>) {
insert[table.uuid] = entry
}
})
fun start(rpcOps: RPCOps, userService: RPCUserService) {
state.locked {

View File

@ -72,21 +72,25 @@ interface NetworkMapService {
val ifChangedSinceVersion: Int?,
override val replyTo: SingleMessageRecipient,
override val sessionID: Long = random63BitValue()) : ServiceRequestMessage
data class FetchMapResponse(val nodes: Collection<NodeRegistration>?, val version: Int)
class QueryIdentityRequest(val identity: Party,
override val replyTo: SingleMessageRecipient,
override val sessionID: Long) : ServiceRequestMessage
data class QueryIdentityResponse(val node: NodeInfo?)
class RegistrationRequest(val wireReg: WireNodeRegistration,
override val replyTo: SingleMessageRecipient,
override val sessionID: Long = random63BitValue()) : ServiceRequestMessage
data class RegistrationResponse(val success: Boolean)
class SubscribeRequest(val subscribe: Boolean,
override val replyTo: SingleMessageRecipient,
override val sessionID: Long = random63BitValue()) : ServiceRequestMessage
data class SubscribeResponse(val confirmed: Boolean)
data class Update(val wireReg: WireNodeRegistration, val mapVersion: Int, val replyTo: MessageRecipients)
@ -338,7 +342,7 @@ class NodeRegistration(val node: NodeInfo, val serial: Long, val type: AddOrRemo
return WireNodeRegistration(regSerialized, regSig)
}
override fun toString() : String = "$node #$serial ($type)"
override fun toString(): String = "$node #$serial ($type)"
}
/**

View File

@ -3,9 +3,9 @@ package net.corda.node.services.persistence
import net.corda.core.ThreadBox
import net.corda.core.bufferUntilSubscribed
import net.corda.core.crypto.SecureHash
import net.corda.core.flows.StateMachineRunId
import net.corda.core.node.services.StateMachineRecordedTransactionMappingStorage
import net.corda.core.node.services.StateMachineTransactionMapping
import net.corda.core.flows.StateMachineRunId
import rx.Observable
import rx.subjects.PublishSubject
import java.util.*

View File

@ -9,4 +9,4 @@ import net.corda.core.serialization.SingletonSerializeAsToken
open class StorageServiceImpl(override val attachments: AttachmentStorage,
override val validatedTransactions: TransactionStorage,
override val stateMachineRecordedTransactionMapping: StateMachineRecordedTransactionMappingStorage)
: SingletonSerializeAsToken(), TxWritableStorageService
: SingletonSerializeAsToken(), TxWritableStorageService

View File

@ -1,5 +1,6 @@
package net.corda.node.services.schema
import kotlinx.support.jdk7.use
import net.corda.core.contracts.ContractState
import net.corda.core.contracts.StateAndRef
import net.corda.core.contracts.StateRef
@ -9,7 +10,6 @@ import net.corda.core.schemas.QueryableState
import net.corda.core.utilities.debug
import net.corda.core.utilities.loggerFor
import net.corda.node.services.api.ServiceHubInternal
import kotlinx.support.jdk7.use
import org.hibernate.SessionFactory
import org.hibernate.boot.model.naming.Identifier
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

View File

@ -442,7 +442,7 @@ class StateMachineManager(val serviceHub: ServiceHubInternal,
interface SessionMessage
interface ExistingSessionMessage: SessionMessage {
interface ExistingSessionMessage : SessionMessage {
val recipientSessionId: Long
}

View File

@ -74,7 +74,7 @@ class NodeVaultService(private val services: ServiceHub) : SingletonSerializeAsT
}
// TODO: caching (2nd tier db cache) and db results filtering (max records, date, other)
fun select(txnId: SecureHash) : Iterable<String> {
fun select(txnId: SecureHash): Iterable<String> {
return table.select { table.txnId.eq(txnId) }.map { row -> row[table.note] }.toSet().asIterable()
}
}

View File

@ -139,6 +139,7 @@ class StrandLocalTransactionManager(initWithDatabase: Database) : TransactionMan
// Composite columns for use with below Exposed helpers.
data class PartyColumns(val name: Column<String>, val owningKey: Column<CompositeKey>)
data class StateRefColumns(val txId: Column<SecureHash>, val index: Column<Int>)
data class TxnNoteColumns(val txId: Column<SecureHash>, val note: Column<String>)

View File

@ -58,7 +58,7 @@ fun bytesToBlob(value: SerializedBytes<*>, finalizables: MutableList<() -> Unit>
fun serializeToBlob(value: Any, finalizables: MutableList<() -> Unit>): Blob = bytesToBlob(value.serialize(), finalizables)
fun <T: Any> bytesFromBlob(blob: Blob): SerializedBytes<T> {
fun <T : Any> bytesFromBlob(blob: Blob): SerializedBytes<T> {
try {
return SerializedBytes(blob.getBytes(0, blob.length().toInt()))
} finally {
@ -194,10 +194,10 @@ abstract class AbstractJDBCHashSet<K : Any, out T : JDBCHashedTable>(protected v
*/
abstract class AbstractJDBCHashMap<K : Any, V : Any, out T : JDBCHashedTable>(val table: T,
val loadOnInit: Boolean = false,
val maxBuckets: Int = 256) : MutableMap<K, V>, AbstractMap<K,V>() {
val maxBuckets: Int = 256) : MutableMap<K, V>, AbstractMap<K, V>() {
companion object {
protected val log = loggerFor<AbstractJDBCHashMap<*,*,*>>()
protected val log = loggerFor<AbstractJDBCHashMap<*, *, *>>()
private const val INITIAL_CAPACITY: Int = 16
private const val LOAD_FACTOR: Float = 0.75f

View File

@ -164,10 +164,10 @@ object JsonSupport {
}
object PublicKeySerializer : JsonSerializer<EdDSAPublicKey>() {
override fun serialize(obj: EdDSAPublicKey, generator: JsonGenerator, provider: SerializerProvider) {
check(obj.params == ed25519Curve)
generator.writeString(obj.toBase58String())
}
override fun serialize(obj: EdDSAPublicKey, generator: JsonGenerator, provider: SerializerProvider) {
check(obj.params == ed25519Curve)
generator.writeString(obj.toBase58String())
}
}
object PublicKeyDeserializer : JsonDeserializer<EdDSAPublicKey>() {

View File

@ -1,5 +1,6 @@
package net.corda.node.utilities.certsigning
import joptsimple.OptionParser
import net.corda.core.*
import net.corda.core.crypto.X509Utilities
import net.corda.core.crypto.X509Utilities.CORDA_CLIENT_CA
@ -12,7 +13,6 @@ import net.corda.node.services.config.ConfigHelper
import net.corda.node.services.config.FullNodeConfiguration
import net.corda.node.services.config.NodeConfiguration
import net.corda.node.services.config.getValue
import joptsimple.OptionParser
import java.net.URL
import java.nio.file.Paths
import java.security.KeyPair
@ -107,7 +107,7 @@ class CertificateSigner(val config: NodeConfiguration, val certService: Certific
requestIdStore.writeLines(listOf(requestId))
requestId
} else {
requestIdStore.readLines { it.findFirst().get() }
requestIdStore.readLines { it.findFirst().get() }
}
}
}

View File

@ -6,6 +6,7 @@ import java.security.cert.Certificate
interface CertificateSigningService {
/** Submits a CSR to the signing service and returns an opaque request ID. */
fun submitRequest(request: PKCS10CertificationRequest): String
/** Poll Certificate Signing Server for the request and returns a chain of certificates if request has been approved, null otherwise. */
fun retrieveCertificates(requestId: String): Array<Certificate>?
}

View File

@ -58,7 +58,7 @@ class CordaRPCOpsImplTest {
@Test
fun `cash issue accepted`() {
val quantity = 1000L
val ref = OpaqueBytes(ByteArray(1) {1})
val ref = OpaqueBytes(ByteArray(1) { 1 })
// Check the monitoring service wallet is empty
databaseTransaction(aliceNode.database) {

View File

@ -305,9 +305,9 @@ class TwoPartyTradeFlowTests {
// Bob answers with the transactions that are now all verifiable, as Alice bottomed out.
// Bob's transactions are valid, so she commits to the database
expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[0].id]!!)),
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[2].id]!!)),
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Get(bobsFakeCash[0].id)), // Verify
expect(TxRecord.Add(bobsSignedTxns[bobsFakeCash[1].id]!!)),
// Now she verifies the transaction is contract-valid (not signature valid) which means
// looking up the states again.
@ -413,7 +413,7 @@ class TwoPartyTradeFlowTests {
val sellerId: StateMachineRunId
)
private fun runBuyerAndSeller(assetToSell: StateAndRef<OwnableState>) : RunResult {
private fun runBuyerAndSeller(assetToSell: StateAndRef<OwnableState>): RunResult {
val buyerFuture = bobNode.initiateSingleShotFlow(Seller::class) { otherParty ->
Buyer(otherParty, notaryNode.info.notaryIdentity, 1000.DOLLARS, CommercialPaper.State::class.java)
}.map { it.fsm }
@ -488,7 +488,7 @@ class TwoPartyTradeFlowTests {
if (!withError)
command(DUMMY_CASH_ISSUER_KEY.public.composite) { Cash.Commands.Issue() }
else
// Put a broken command on so at least a signature is created
// Put a broken command on so at least a signature is created
command(DUMMY_CASH_ISSUER_KEY.public.composite) { Cash.Commands.Move() }
timestamp(TEST_TX_TIME)
if (withError) {

View File

@ -63,7 +63,7 @@ abstract class AbstractNetworkMapServiceTest {
assertEquals(1, service().nodes.count())
// Confirm that de-registering the node succeeds and drops it from the node lists
val removeChange = NodeRegistration(registerNode.info, instant.toEpochMilli()+1, AddOrRemove.REMOVE, expires)
val removeChange = NodeRegistration(registerNode.info, instant.toEpochMilli() + 1, AddOrRemove.REMOVE, expires)
val removeWireChange = removeChange.toWire(nodeKey.private)
assert(service().processRegistrationChangeRequest(RegistrationRequest(removeWireChange, mapServiceNode.info.address, Long.MIN_VALUE)).success)
swizzle()
@ -92,7 +92,7 @@ abstract class AbstractNetworkMapServiceTest {
val nodeKey = registerNode.services.legalIdentityKey
val instant = Instant.now()
val expires = instant + NetworkMapService.DEFAULT_EXPIRATION_PERIOD
val reg = NodeRegistration(registerNode.info, instant.toEpochMilli()+1, AddOrRemove.REMOVE, expires)
val reg = NodeRegistration(registerNode.info, instant.toEpochMilli() + 1, AddOrRemove.REMOVE, expires)
val registerResult = registerNode.registration(mapServiceNode, reg, nodeKey.private)
network.runNetwork()
assertTrue(registerResult.getOrThrow().success)

View File

@ -11,7 +11,7 @@ import org.graphstream.graph.Node
import org.graphstream.graph.implementations.SingleGraph
import kotlin.reflect.memberProperties
@Suppress("unused") // TODO: Re-evaluate by EOY2016 if this code is still useful and if not, delete.
@Suppress("unused") // TODO: Re-evaluate by EOY2016 if this code is still useful and if not, delete.
class GraphVisualiser(val dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>) {
companion object {
val css = GraphVisualiser::class.java.getResourceAsStream("graph.css").bufferedReader().readText()