Minor: fix various inspector warnings and delete some dead code.

This commit is contained in:
Mike Hearn
2016-08-08 16:19:28 +02:00
parent 2bc77ae095
commit 87047c8996
80 changed files with 210 additions and 288 deletions

View File

@ -8,15 +8,6 @@ interface StatesQuery {
fun select(criteria: Criteria): Selection {
return Selection(criteria)
}
fun selectAllDeals(): Selection {
return select(Criteria.AllDeals)
}
fun selectDeal(ref: String): Selection {
return select(Criteria.Deal(ref))
}
}
// TODO make constructors private

View File

@ -6,13 +6,13 @@ import com.google.common.util.concurrent.SettableFuture
import com.r3corda.core.RunOnCallerThread
import com.r3corda.core.contracts.SignedTransaction
import com.r3corda.core.crypto.Party
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.messaging.runOnNextMessage
import com.r3corda.core.node.CityDatabase
import com.r3corda.core.node.CordaPluginRegistry
import com.r3corda.core.node.NodeInfo
import com.r3corda.core.node.PhysicalLocation
import com.r3corda.core.node.services.*
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.core.protocols.ProtocolLogicRefFactory
import com.r3corda.core.random63BitValue
@ -27,14 +27,15 @@ import com.r3corda.node.services.events.NodeSchedulerService
import com.r3corda.node.services.events.ScheduledActivityObserver
import com.r3corda.node.services.identity.InMemoryIdentityService
import com.r3corda.node.services.keys.E2ETestKeyManagementService
import com.r3corda.core.node.services.NetworkMapCache
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.node.services.network.InMemoryNetworkMapCache
import com.r3corda.node.services.network.InMemoryNetworkMapService
import com.r3corda.node.services.network.NetworkMapService
import com.r3corda.node.services.network.NetworkMapService.Companion.REGISTER_PROTOCOL_TOPIC
import com.r3corda.node.services.network.NodeRegistration
import com.r3corda.node.services.persistence.*
import com.r3corda.node.services.persistence.NodeAttachmentService
import com.r3corda.node.services.persistence.PerFileCheckpointStorage
import com.r3corda.node.services.persistence.PerFileTransactionStorage
import com.r3corda.node.services.persistence.StorageServiceImpl
import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.node.services.transactions.InMemoryUniquenessProvider
import com.r3corda.node.services.transactions.NotaryService
@ -158,7 +159,7 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
storage = storageServices.first
checkpointStorage = storageServices.second
net = makeMessagingService()
netMapCache = InMemoryNetworkMapCache(net)
netMapCache = InMemoryNetworkMapCache()
wallet = NodeWalletService(services)
identity = makeIdentityService()
@ -201,8 +202,8 @@ abstract class AbstractNode(val dir: Path, val configuration: NodeConfiguration,
private fun initialiseProtocolLogicFactory(): ProtocolLogicRefFactory {
val protocolWhitelist = HashMap<String, Set<String>>()
for (plugin in pluginRegistries) {
for (protocol in plugin.requiredProtocols) {
protocolWhitelist.merge(protocol.key, protocol.value, { x, y -> x + y })
for ((className, classWhitelist) in plugin.requiredProtocols) {
protocolWhitelist.merge(className, classWhitelist, { x, y -> x + y })
}
}

View File

@ -4,7 +4,6 @@ import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.google.common.util.concurrent.Futures
import com.r3corda.core.crypto.Party
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.messaging.SingleMessageRecipient
import com.r3corda.core.node.NodeInfo
import com.r3corda.core.node.PhysicalLocation
@ -104,7 +103,8 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
}
// This does not indirect through the NodeInfo object so it can be called before the node is started.
val place: PhysicalLocation get() = findMyLocation()!!
// It is used from the network visualiser tool.
@Suppress("unused") val place: PhysicalLocation get() = findMyLocation()!!
}
/** Returns a node, optionally created by the passed factory method. */
@ -168,6 +168,7 @@ class MockNetwork(private val networkSendManuallyPumped: Boolean = false,
fun createNotaryNode(legalName: String? = null, keyPair: KeyPair? = null) = createNode(null, -1, defaultFactory, true, legalName, keyPair, NetworkMapService.Type, SimpleNotaryService.Type)
fun createPartyNode(networkMapAddr: NodeInfo, legalName: String? = null, keyPair: KeyPair? = null) = createNode(networkMapAddr, -1, defaultFactory, true, legalName, keyPair)
@Suppress("unused") // This is used from the network visualiser tool.
fun addressToNode(address: SingleMessageRecipient): MockNode = nodes.single { it.net.myAddress == address }
fun startNodes() {

View File

@ -31,8 +31,8 @@ import java.util.*
* in a few cities around the world.
*/
abstract class Simulation(val networkSendManuallyPumped: Boolean,
val runAsync: Boolean,
val latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) {
runAsync: Boolean,
latencyInjector: InMemoryMessagingNetwork.LatencyCalculator?) {
init {
if (!runAsync && latencyInjector != null)
throw IllegalArgumentException("The latency injector is only useful when using manual pumping.")
@ -160,10 +160,11 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean,
val clocks = (serviceProviders + regulators + banks).map { it.services.clock as TestClock }
// These are used from the network visualiser tool.
private val _allProtocolSteps = PublishSubject.create<Pair<SimulatedNode, ProgressTracker.Change>>()
private val _doneSteps = PublishSubject.create<Collection<SimulatedNode>>()
val allProtocolSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allProtocolSteps
val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
@Suppress("unused") val allProtocolSteps: Observable<Pair<SimulatedNode, ProgressTracker.Change>> = _allProtocolSteps
@Suppress("unused") val doneSteps: Observable<Collection<SimulatedNode>> = _doneSteps
private var pumpCursor = 0
@ -258,6 +259,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean,
}
}
@Suppress("unused") // Used from the network visualiser tool.
val networkInitialisationFinished: ListenableFuture<*> =
Futures.allAsList(network.nodes.map { it.networkMapRegistrationFuture })

View File

@ -2,7 +2,6 @@ package com.r3corda.node.services.api
import com.r3corda.core.messaging.Message
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.messaging.TopicSession
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.node.services.NetworkMapCache
import com.r3corda.core.serialization.SingletonSerializeAsToken

View File

@ -3,7 +3,6 @@ package com.r3corda.node.services.api
import com.r3corda.core.serialization.SerializedBytes
import com.r3corda.node.services.statemachine.FiberRequest
import com.r3corda.node.services.statemachine.ProtocolStateMachineImpl
import com.r3corda.node.services.statemachine.StateMachineManager
/**
* Thread-safe storage of fiber checkpoints.

View File

@ -3,7 +3,6 @@ package com.r3corda.node.services.clientapi
import com.r3corda.core.node.CordaPluginRegistry
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.serialization.deserialize
import com.r3corda.node.internal.AbstractNode
import com.r3corda.node.services.api.ServiceHubInternal
import com.r3corda.protocols.TwoPartyDealProtocol

View File

@ -197,7 +197,7 @@ object NodeInterestRates {
class UnknownFix(val fix: FixOf) : RetryableException("Unknown fix: $fix")
/** Fix container, for every fix name & date pair stores a tenor to interest rate map - [InterpolatingRateMap] */
class FixContainer(val fixes: List<Fix>, val factory: InterpolatorFactory = CubicSplineInterpolator) {
class FixContainer(fixes: List<Fix>, val factory: InterpolatorFactory = CubicSplineInterpolator) {
private val container = buildContainer(fixes)
val size = fixes.size
@ -227,7 +227,7 @@ object NodeInterestRates {
* Interpolates missing values using the provided interpolation mechanism.
*/
class InterpolatingRateMap(val date: LocalDate,
val inputRates: Map<Tenor, BigDecimal>,
inputRates: Map<Tenor, BigDecimal>,
val calendar: BusinessCalendar,
val factory: InterpolatorFactory) {
@ -274,7 +274,7 @@ object NodeInterestRates {
/** Parses lines containing fixes */
fun parseFile(s: String): FixContainer {
val fixes = s.lines().
map { it.trim() }.
map(String::trim).
// Filter out comment and empty lines.
filterNot { it.startsWith("#") || it.isBlank() }.
map { parseFix(it) }
@ -283,7 +283,7 @@ object NodeInterestRates {
/** Parses a string of the form "LIBOR 16-March-2016 1M = 0.678" into a [Fix] */
fun parseFix(s: String): Fix {
val (key, value) = s.split('=').map { it.trim() }
val (key, value) = s.split('=').map(String::trim)
val of = parseFixOf(key)
val rate = BigDecimal(value)
return Fix(of, rate)

View File

@ -50,6 +50,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
// The corresponding sentMessages stream reflects when a message was pumpSend'd
private val messageSendQueue = LinkedBlockingQueue<MessageTransfer>()
private val _sentMessages = PublishSubject.create<MessageTransfer>()
@Suppress("unused") // Used by the visualiser tool.
/** A stream of (sender, message, recipients) triples */
val sentMessages: Observable<MessageTransfer>
get() = _sentMessages
@ -61,6 +62,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
// The corresponding stream reflects when a message was pumpReceive'd
private val messageReceiveQueues = HashMap<Handle, LinkedBlockingQueue<MessageTransfer>>()
private val _receivedMessages = PublishSubject.create<MessageTransfer>()
@Suppress("unused") // Used by the visualiser tool.
/** A stream of (sender, message, recipients) triples */
val receivedMessages: Observable<MessageTransfer>
get() = _receivedMessages
@ -202,18 +205,18 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
val callback: (Message, MessageHandlerRegistration) -> Unit) : MessageHandlerRegistration
@Volatile
protected var running = true
private var running = true
protected inner class InnerState {
private inner class InnerState {
val handlers: MutableList<Handler> = ArrayList()
val pendingRedelivery = LinkedList<MessageTransfer>()
}
protected val state = ThreadBox(InnerState())
private val state = ThreadBox(InnerState())
override val myAddress: SingleMessageRecipient = handle
protected val backgroundThread = if (manuallyPumped) null else
private val backgroundThread = if (manuallyPumped) null else
thread(isDaemon = true, name = "In-memory message dispatcher") {
while (!Thread.currentThread().isInterrupted) {
try {
@ -235,8 +238,8 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
pendingRedelivery.clear()
Pair(handler, items)
}
for (it in items) {
send(it.message, handle)
for ((sender, message) in items) {
send(message, handle)
}
return handler
}
@ -329,10 +332,7 @@ class InMemoryMessagingNetwork(val sendManuallyPumped: Boolean) : SingletonSeria
private fun pumpReceiveInternal(block: Boolean): MessageTransfer? {
val q = getQueueForHandle(handle)
val next = getNextQueue(q, block)
if (next == null) {
return null
}
val next = getNextQueue(q, block) ?: return null
val (transfer, deliverTo) = next
for (handler in deliverTo) {

View File

@ -13,14 +13,13 @@ import com.r3corda.core.node.NodeInfo
import com.r3corda.core.node.services.DEFAULT_SESSION_ID
import com.r3corda.core.node.services.NetworkCacheError
import com.r3corda.core.node.services.NetworkMapCache
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.core.node.services.NetworkMapCache.MapChange
import com.r3corda.core.node.services.NetworkMapCache.MapChangeType
import com.r3corda.core.node.services.ServiceType
import com.r3corda.core.random63BitValue
import com.r3corda.core.serialization.SingletonSerializeAsToken
import com.r3corda.core.serialization.deserialize
import com.r3corda.core.serialization.serialize
import com.r3corda.node.services.api.MessagingServiceInternal
import com.r3corda.node.services.api.RegulatorService
import com.r3corda.node.services.clientapi.NodeInterestRates
import com.r3corda.node.services.transactions.NotaryService
@ -36,7 +35,7 @@ import javax.annotation.concurrent.ThreadSafe
* Extremely simple in-memory cache of the network map.
*/
@ThreadSafe
open class InMemoryNetworkMapCache(val netInternal: MessagingServiceInternal?) : SingletonSerializeAsToken(), NetworkMapCache {
open class InMemoryNetworkMapCache : SingletonSerializeAsToken(), NetworkMapCache {
override val networkMapNodes: List<NodeInfo>
get() = get(NetworkMapService.Type)
override val regulators: List<NodeInfo>

View File

@ -12,14 +12,14 @@ import rx.subjects.PublishSubject
/**
* Network map cache with no backing map service.
*/
class MockNetworkMapCache() : InMemoryNetworkMapCache(null) {
class MockNetworkMapCache() : InMemoryNetworkMapCache() {
override val changed: Observable<NetworkMapCache.MapChange> = PublishSubject.create<NetworkMapCache.MapChange>()
data class MockAddress(val id: String): SingleMessageRecipient
init {
var mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C")))
var mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D")))
val mockNodeA = NodeInfo(MockAddress("bankC:8080"), Party("Bank C", DummyPublicKey("Bank C")))
val mockNodeB = NodeInfo(MockAddress("bankD:8080"), Party("Bank D", DummyPublicKey("Bank D")))
registeredNodes[mockNodeA.identity] = mockNodeA
registeredNodes[mockNodeB.identity] = mockNodeB
}

View File

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

@ -62,7 +62,7 @@ object DataVending {
if (data.accepted) {
future.set(Unit)
} else {
future.setException(TransactionRejectedError("Transaction ${transaction} rejected by remote party ${recipient.identity}"))
future.setException(TransactionRejectedError("Transaction $transaction rejected by remote party ${recipient.identity}"))
}
}
val msg = NotifyTxRequestMessage(transaction, myIdentity, sessionID)

View File

@ -22,7 +22,7 @@ import javax.annotation.concurrent.ThreadSafe
* Stores attachments in the specified local directory, which must exist. Doesn't allow new attachments to be uploaded.
*/
@ThreadSafe
class NodeAttachmentService(val storePath: Path, val metrics: MetricRegistry) : AttachmentStorage, AcceptsFileUpload {
class NodeAttachmentService(val storePath: Path, metrics: MetricRegistry) : AttachmentStorage, AcceptsFileUpload {
private val log = loggerFor<NodeAttachmentService>()
@VisibleForTesting
@ -122,7 +122,7 @@ class NodeAttachmentService(val storePath: Path, val metrics: MetricRegistry) :
Files.deleteIfExists(tmp)
}
if (automaticallyExtractAttachments) {
val extractTo = storePath.resolve("${id}.jar")
val extractTo = storePath.resolve("$id.jar")
try {
Files.createDirectory(extractTo)
extractZipFile(finalPath, extractTo)

View File

@ -40,7 +40,7 @@ class PerFileCheckpointStorage(val storeDir: Path) : CheckpointStorage {
override fun addCheckpoint(checkpoint: Checkpoint) {
val serialisedCheckpoint = checkpoint.serialize()
val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}${fileExtension}"
val fileName = "${serialisedCheckpoint.hash.toString().toLowerCase()}$fileExtension"
val checkpointFile = storeDir.resolve(fileName)
atomicWrite(checkpointFile, serialisedCheckpoint)
logger.trace { "Stored $checkpoint to $checkpointFile" }

View File

@ -59,15 +59,15 @@ sealed class FiberRequest(val topic: String,
) : FiberRequest(topic, destination, sessionIDForSend, sessionIDForReceive, obj) {
private val responseTypeName: String = type.name
override fun equals(other: Any?): Boolean
= if (other is ExpectingResponse<*>) {
super.equals(other)
&& responseTypeName == other.responseTypeName
} else
false
override fun equals(other: Any?): Boolean {
return if (other is ExpectingResponse<*>) {
super.equals(other) && responseTypeName == other.responseTypeName
} else
false
}
override fun toString(): String {
return "Expecting response via topic ${receiveTopicSession} of type ${responseTypeName}"
return "Expecting response via topic $receiveTopicSession of type $responseTypeName"
}
// We have to do an unchecked cast, but unless the serialized form is damaged, this was

View File

@ -30,13 +30,13 @@ class CashBalanceAsMetricsObserver(val serviceHubInternal: ServiceHubInternal) {
//
// Note: exported as pennies.
val m = serviceHubInternal.monitoringService.metrics
for (balance in wallet.cashBalances) {
val metric = balanceMetrics.getOrPut(balance.key) {
for ((key, value) in wallet.cashBalances) {
val metric = balanceMetrics.getOrPut(key) {
val newMetric = BalanceMetric()
m.register("WalletBalances.${balance.key}Pennies", newMetric)
m.register("WalletBalances.${key}Pennies", newMetric)
newMetric
}
metric.pennies = balance.value.quantity
metric.pennies = value.quantity
}
}
}

View File

@ -4,7 +4,6 @@ import com.r3corda.core.ThreadBox
import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.core.utilities.ProgressTracker
import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.protocols.TwoPartyDealProtocol
import java.util.*
/**

View File

@ -36,7 +36,7 @@ import kotlin.concurrent.withLock
* TODO: We should consider using a [Semaphore] or [CountDownLatch] here to make it a little easier to understand, but it seems
* as though the current version of Qasar does not support suspending on either of their implementations.
*/
class FiberBox<T>(private val content: T, private val lock: Lock = ReentrantLock()) {
class FiberBox<out T>(private val content: T, private val lock: Lock = ReentrantLock()) {
private var mutated: SettableFuture<Boolean>? = null
@Suppress("UNUSED_VALUE") // This is here due to the compiler thinking ourMutated is not used

View File

@ -13,8 +13,6 @@ import com.r3corda.core.contracts.BusinessCalendar
import com.r3corda.core.crypto.*
import com.r3corda.core.node.services.IdentityService
import net.i2p.crypto.eddsa.EdDSAPublicKey
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime

View File

@ -19,6 +19,7 @@ import com.r3corda.node.services.statemachine.StateMachineManager
import com.r3corda.node.services.wallet.NodeWalletService
import java.time.Clock
@Suppress("LeakingThis")
open class MockServiceHubInternal(
customWallet: WalletService? = null,
val keyManagement: KeyManagementService? = null,

View File

@ -22,7 +22,6 @@ import com.r3corda.protocols.RatesFixProtocol
import org.junit.Assert
import org.junit.Test
import java.time.Clock
import java.time.Duration
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
@ -109,7 +108,7 @@ class NodeInterestRatesTest {
val tx = TransactionType.General.Builder()
val fixOf = NodeInterestRates.parseFixOf("LIBOR 2016-03-16 1M")
val protocol = RatesFixProtocol(tx, n2.info.identity, fixOf, "0.675".bd, "0.1".bd, Duration.ofNanos(1))
val protocol = RatesFixProtocol(tx, n2.info.identity, fixOf, "0.675".bd, "0.1".bd)
BriefLogFormatter.initVerbose("rates")
net.runNetwork()
val future = n1.smm.add("rates", protocol)

View File

@ -196,7 +196,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
@Test
fun `test activity due in the future and schedule another for same time then unschedule original`() {
val time = stoppedClock.instant() + 1.days
var scheduledRef1 = scheduleTX(time)
val scheduledRef1 = scheduleTX(time)
val backgroundExecutor = Executors.newSingleThreadExecutor()
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }
@ -214,7 +214,7 @@ class NodeSchedulerServiceTest : SingletonSerializeAsToken() {
@Test
fun `test activity due in the future then unschedule`() {
var scheduledRef1 = scheduleTX(stoppedClock.instant() + 1.days)
val scheduledRef1 = scheduleTX(stoppedClock.instant() + 1.days)
val backgroundExecutor = Executors.newSingleThreadExecutor()
backgroundExecutor.execute { schedulerGatedExecutor.waitAndRun() }

View File

@ -7,7 +7,6 @@ import com.r3corda.core.random63BitValue
import com.r3corda.core.serialization.SerializedBytes
import com.r3corda.node.services.api.Checkpoint
import com.r3corda.node.services.statemachine.FiberRequest
import com.r3corda.node.services.statemachine.StateMachineManager
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.After

View File

@ -2,7 +2,6 @@ package com.r3corda.node.services.statemachine
import co.paralleluniverse.fibers.Fiber
import co.paralleluniverse.fibers.Suspendable
import com.r3corda.core.messaging.MessagingService
import com.r3corda.core.protocols.ProtocolLogic
import com.r3corda.node.services.MockServiceHubInternal
import com.r3corda.node.services.api.Checkpoint

View File

@ -11,6 +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.
class GraphVisualiser(val dsl: LedgerDSL<TestTransactionDSLInterpreter, TestLedgerDSLInterpreter>) {
companion object {
val css = GraphVisualiser::class.java.getResourceAsStream("graph.css").bufferedReader().readText()

View File

@ -37,7 +37,7 @@ public class StateViewer {
frame.setVisible(true);
}
public StateViewer(List<Pair<String, Object>> props) {
private StateViewer(List<Pair<String, Object>> props) {
propsTable.setModel(new AbstractTableModel() {
@Override
public int getRowCount() {