TM-23 Fail build on compiler warnings (#5453)

* java compile respects compilation.allWarningsAsErrors

* suppress or cleanup warnings

* suppress warning

* use non-deprecated kotlin dependency

* rename property

* handle property existence check

* Deal with warnings
This commit is contained in:
Zoltan Kiss 2019-09-11 16:34:51 +01:00 committed by Dominic Fox
parent 4e6edd012a
commit f171de7b69
75 changed files with 223 additions and 143 deletions

View File

@ -14,6 +14,7 @@ buildscript {
//
// TODO: Sort this alphabetically.
ext.kotlin_version = constants.getProperty("kotlinVersion")
ext.warnings_as_errors = project.hasProperty("compilation.warningsAsErrors") ? project.property("compilation.warningsAsErrors").toBoolean() : false
ext.quasar_group = 'co.paralleluniverse'
ext.quasar_version = constants.getProperty("quasarVersion")
@ -214,6 +215,12 @@ allprojects {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" << "-Xlint:-options" << "-parameters"
if (warnings_as_errors) {
// We cannot fail the build on compiler warnings because we have java warnings that you cannot disable:
// Signal is internal proprietary API and may be removed in a future release
// otherwise we should have the following line here:
// options.compilerArgs << "-Werror"
}
options.encoding = 'UTF-8'
}
@ -224,7 +231,7 @@ allprojects {
jvmTarget = "1.8"
javaParameters = true // Useful for reflection.
freeCompilerArgs = ['-Xjvm-default=compatibility']
allWarningsAsErrors = project.hasProperty('compilation.allWarningsAsErrors') ? project.property('compilation.allWarningsAsErrors').toBoolean() : false
allWarningsAsErrors = warnings_as_errors
}
}

View File

@ -195,7 +195,7 @@ open class StringToMethodCallParser<in T : Any> @JvmOverloads constructor(
@Throws(UnparseableCallException::class)
fun validateIsMatchingCtor(methodNameHint: String, parameters: List<Pair<String, Type>>, args: String) {
val tree = createJsonTreeAndValidate(methodNameHint, parameters, args)
val inOrderParams: List<Any?> = parameters.mapIndexed { _, (argName, argType) ->
parameters.mapIndexed { _, (argName, _) ->
tree[argName] ?: throw UnparseableCallException.MissingParameter(methodNameHint, argName, args)
}
}

View File

@ -86,7 +86,7 @@ class NodeMonitorModel : AutoCloseable {
vaultUpdates.startWith(initialVaultUpdate).subscribe(vaultUpdatesSubject::onNext)
// Transactions
val (transactions, newTransactions) = rpc.internalVerifiedTransactionsFeed()
val (transactions, newTransactions) = @Suppress("DEPRECATION") rpc.internalVerifiedTransactionsFeed()
newTransactions.startWith(transactions).subscribe(transactionsSubject::onNext)
// SM -> TX mapping

View File

@ -196,6 +196,7 @@ open class CordaRPCClientConfiguration @JvmOverloads constructor(
if (trackRpcCallSites != other.trackRpcCallSites) return false
if (reapInterval != other.reapInterval) return false
if (observationExecutorPoolSize != other.observationExecutorPoolSize) return false
@Suppress("DEPRECATION")
if (cacheConcurrencyLevel != other.cacheConcurrencyLevel) return false
if (connectionRetryInterval != other.connectionRetryInterval) return false
if (connectionRetryIntervalMultiplier != other.connectionRetryIntervalMultiplier) return false
@ -212,6 +213,7 @@ open class CordaRPCClientConfiguration @JvmOverloads constructor(
result = 31 * result + trackRpcCallSites.hashCode()
result = 31 * result + reapInterval.hashCode()
result = 31 * result + observationExecutorPoolSize
@Suppress("DEPRECATION")
result = 31 * result + cacheConcurrencyLevel
result = 31 * result + connectionRetryInterval.hashCode()
result = 31 * result + connectionRetryIntervalMultiplier.hashCode()

View File

@ -69,7 +69,10 @@ object IdentitySyncFlow {
.filter { serviceHub.networkMapCache.getNodesByLegalIdentityKey(it.owningKey).isEmpty() }
.toList()
return confidentialIdentities
.map { Pair(it, serviceHub.identityService.certificateFromKey(it.owningKey)) }
.map {
@Suppress("DEPRECATION")
Pair(it, serviceHub.identityService.certificateFromKey(it.owningKey))
}
// Filter down to confidential identities of our well known identity
// TODO: Consider if this too restrictive - we perhaps should be checking the name on the signing certificate in the certificate path instead
.filter { it.second?.name == ourIdentity.name }

View File

@ -4,7 +4,10 @@ import co.paralleluniverse.fibers.Suspendable
import net.corda.core.CordaInternal
import net.corda.core.crypto.DigitalSignature
import net.corda.core.crypto.verify
import net.corda.core.flows.*
import net.corda.core.flows.FlowException
import net.corda.core.flows.FlowLogic
import net.corda.core.flows.FlowSession
import net.corda.core.flows.InitiatingFlow
import net.corda.core.identity.AnonymousParty
import net.corda.core.identity.CordaX500Name
import net.corda.core.identity.Party
@ -41,7 +44,7 @@ private constructor(private val otherSideSession: FlowSession?,
@Deprecated("It is unsafe to use this constructor as it requires nodes to automatically vend anonymous identities without first " +
"checking if they should. Instead, use the constructor that takes in an existing FlowSession.")
constructor(otherParty: Party, revocationEnabled: Boolean, progressTracker: ProgressTracker) : this(null, otherParty, progressTracker)
constructor(otherParty: Party, @Suppress("UNUSED_PARAMETER") revocationEnabled: Boolean, progressTracker: ProgressTracker) : this(null, otherParty, progressTracker)
@Deprecated("It is unsafe to use this constructor as it requires nodes to automatically vend anonymous identities without first " +
"checking if they should. Instead, use the constructor that takes in an existing FlowSession.")

View File

@ -91,7 +91,7 @@ class IdentitySyncFlowTests {
val issueFlow = charlieNode.services.startFlow(CashIssueAndPaymentFlow(1000.DOLLARS, ref, charlie, anonymous, notary))
val issueTx = issueFlow.resultFuture.getOrThrow().stx
val confidentialIdentity = issueTx.tx.outputs.map { it.data }.filterIsInstance<Cash.State>().single().owner
val confidentialIdentCert = charlieNode.services.identityService.certificateFromKey(confidentialIdentity.owningKey)!!
val confidentialIdentCert = @Suppress("DEPRECATION") charlieNode.services.identityService.certificateFromKey(confidentialIdentity.owningKey)!!
// Manually inject this identity into Alice's database so the node could leak it, but we prove won't
aliceNode.database.transaction { aliceNode.services.identityService.verifyAndRegisterIdentity(confidentialIdentCert) }

View File

@ -8,5 +8,5 @@ import net.corda.core.contracts.ContractState
@Suppress("unused")
object StateContractValidationEnforcementRule {
fun shouldEnforce(state: ContractState): Boolean = true
fun shouldEnforce(@Suppress("UNUSED_PARAMETER") state: ContractState): Boolean = true
}

View File

@ -3,6 +3,6 @@ package net.corda.core.internal
/**
* Stubbing out non-deterministic method.
*/
fun <T: Any> createInstancesOfClassesImplementing(classloader: ClassLoader, clazz: Class<T>): Set<T> {
fun <T: Any> createInstancesOfClassesImplementing(@Suppress("UNUSED_PARAMETER") classloader: ClassLoader, @Suppress("UNUSED_PARAMETER") clazz: Class<T>): Set<T> {
return emptySet()
}

View File

@ -315,7 +315,7 @@ class ConstraintsPropagationTests {
whenever(attachmentSigned.allContracts).thenReturn(setOf(propagatingContractClassName))
// network parameters
val netParams = testNetworkParameters(minimumPlatformVersion = 4,
testNetworkParameters(minimumPlatformVersion = 4,
packageOwnership = mapOf("net.corda.core.contracts" to ALICE_PARTY.owningKey))
ledgerServices.attachments.importContractAttachment(attachmentIdSigned, attachmentSigned)

View File

@ -12,7 +12,7 @@ import rx.Observer
// TODO Delete this file once the Future stuff is out of here
fun <A> CordaFuture<out A>.toObservable(): Observable<A> {
return Observable.create { subscriber ->
return Observable.unsafeCreate { subscriber ->
thenMatch({
subscriber.onNext(it)
subscriber.onCompleted()

View File

@ -42,8 +42,14 @@ fun <C : CommandData> Collection<CommandWithParties<CommandData>>.select(klass:
party: AbstractParty? = null) =
mapNotNull { if (klass.isInstance(it.value)) uncheckedCast<CommandWithParties<CommandData>, CommandWithParties<C>>(it) else null }.
filter { if (signer == null) true else signer in it.signers }.
filter { if (party == null) true else party in it.signingParties }.
map { CommandWithParties(it.signers, it.signingParties, it.value) }
filter {
@Suppress("DEPRECATION")
if (party == null) true else party in it.signingParties
}.
map {
@Suppress("DEPRECATION")
CommandWithParties(it.signers, it.signingParties, it.value)
}
/** Filters the command list by type, parties and public keys all at once. */
inline fun <reified T : CommandData> Collection<CommandWithParties<CommandData>>.select(signers: Collection<PublicKey>?,
@ -56,8 +62,14 @@ fun <C : CommandData> Collection<CommandWithParties<CommandData>>.select(klass:
parties: Collection<Party>?) =
mapNotNull { if (klass.isInstance(it.value)) uncheckedCast<CommandWithParties<CommandData>, CommandWithParties<C>>(it) else null }.
filter { if (signers == null) true else it.signers.containsAll(signers) }.
filter { if (parties == null) true else it.signingParties.containsAll(parties) }.
map { CommandWithParties(it.signers, it.signingParties, it.value) }
filter {
@Suppress("DEPRECATION")
if (parties == null) true else it.signingParties.containsAll(parties)
}.
map {
@Suppress("DEPRECATION")
CommandWithParties(it.signers, it.signingParties, it.value)
}
/** Ensures that a transaction has only one command that is of the given type, otherwise throws an exception. */
inline fun <reified T : CommandData> Collection<CommandWithParties<CommandData>>.requireSingleCommand() = requireSingleCommand(T::class.java)

View File

@ -48,10 +48,15 @@ val ContractState.requiredContractClassName: String? get() {
*/
fun AttachmentConstraint.canBeTransitionedFrom(input: AttachmentConstraint, attachment: ContractAttachment): Boolean {
val output = this
@Suppress("DEPRECATION")
fun AttachmentConstraint.isAutomaticHashConstraint() =
this is AutomaticHashConstraint
return when {
// These branches should not happen, as this has been already checked.
input is AutomaticPlaceholderConstraint || output is AutomaticPlaceholderConstraint -> throw IllegalArgumentException("Illegal constraint: AutomaticPlaceholderConstraint.")
input is AutomaticHashConstraint || output is AutomaticHashConstraint -> throw IllegalArgumentException("Illegal constraint: AutomaticHashConstraint.")
input.isAutomaticHashConstraint() || output.isAutomaticHashConstraint() -> throw IllegalArgumentException("Illegal constraint: AutomaticHashConstraint.")
// Transition to the same constraint.
input == output -> true

View File

@ -97,10 +97,12 @@ class TransactionDeserialisationException(groupEnum: ComponentGroupEnum, index:
*
* This method used the [deserialiseComponentGroup] method.
*/
fun deserialiseCommands(componentGroups: List<ComponentGroup>,
forceDeserialize: Boolean = false,
factory: SerializationFactory = SerializationFactory.defaultFactory,
context: SerializationContext = factory.defaultContext): List<Command<*>> {
fun deserialiseCommands(
componentGroups: List<ComponentGroup>,
forceDeserialize: Boolean = false,
factory: SerializationFactory = SerializationFactory.defaultFactory,
@Suppress("UNUSED_PARAMETER") context: SerializationContext = factory.defaultContext
): List<Command<*>> {
// TODO: we could avoid deserialising unrelated signers.
// However, current approach ensures the transaction is not malformed
// and it will throw if any of the signers objects is not List of public keys).

View File

@ -48,6 +48,7 @@ interface IdentityService {
*/
@Throws(UnknownAnonymousPartyException::class)
fun assertOwnership(party: Party, anonymousParty: AnonymousParty) {
@Suppress("DEPRECATION")
val anonymousIdentity = certificateFromKey(anonymousParty.owningKey)
?: throw UnknownAnonymousPartyException("Unknown $anonymousParty")
val issuingCert = anonymousIdentity.certPath.certificates[1]
@ -79,7 +80,9 @@ interface IdentityService {
* @param key The owning [PublicKey] of the [Party].
* @return Returns a [Party] with a matching owningKey if known, else returns null.
*/
fun partyFromKey(key: PublicKey): Party? = certificateFromKey(key)?.party
fun partyFromKey(key: PublicKey): Party? =
@Suppress("DEPRECATION")
certificateFromKey(key)?.party
/**
* Resolves a party name to the well known identity [Party] instance for this name. Where possible well known identity

View File

@ -390,5 +390,7 @@ private constructor(
privacySalt: PrivacySalt = this.privacySalt,
sigs: List<TransactionSignature> = this.sigs,
networkParameters: NetworkParameters = this.networkParameters
) = ContractUpgradeLedgerTransaction(inputs, notary, legacyContractAttachment, upgradedContractClassName, upgradedContractAttachment, id, privacySalt, sigs, networkParameters)
) =
@Suppress("DEPRECATION")
ContractUpgradeLedgerTransaction(inputs, notary, legacyContractAttachment, upgradedContractClassName, upgradedContractAttachment, id, privacySalt, sigs, networkParameters)
}

View File

@ -98,7 +98,11 @@ data class NotaryChangeWireTransaction(
* TODO - currently this uses the main classloader.
*/
@CordaInternal
internal fun resolveOutputComponent(services: ServicesForResolution, stateRef: StateRef, params: NetworkParameters): SerializedBytes<TransactionState<ContractState>> {
internal fun resolveOutputComponent(
services: ServicesForResolution,
stateRef: StateRef,
@Suppress("UNUSED_PARAMETER") params: NetworkParameters
): SerializedBytes<TransactionState<ContractState>> {
return services.loadState(stateRef).serialize()
}

View File

@ -246,7 +246,9 @@ open class TransactionBuilder(
* TODO also on the versions of the attachments of the transactions generating the input states. ( after we add versioning)
*/
private fun selectContractAttachmentsAndOutputStateConstraints(
services: ServicesForResolution, serializationContext: SerializationContext?): Pair<Collection<SecureHash>, List<TransactionState<ContractState>>> {
services: ServicesForResolution,
@Suppress("UNUSED_PARAMETER") serializationContext: SerializationContext?
): Pair<Collection<SecureHash>, List<TransactionState<ContractState>>> {
// Determine the explicitly set contract attachments.
val explicitAttachmentContracts: List<Pair<ContractClassName, SecureHash>> = this.attachments
@ -297,7 +299,10 @@ open class TransactionBuilder(
return Pair(attachments, resolvedOutputStatesInTheOriginalOrder)
}
private val automaticConstraints = setOf(AutomaticPlaceholderConstraint, AutomaticHashConstraint)
private val automaticConstraints = setOf(
AutomaticPlaceholderConstraint,
@Suppress("DEPRECATION") AutomaticHashConstraint
)
/**
* Selects an attachment and resolves the constraints for the output states with [AutomaticPlaceholderConstraint].

View File

@ -107,7 +107,6 @@ class WireTransaction(componentGroups: List<ComponentGroup>, val privacySalt: Pr
val hashToResolve = it ?: services.networkParametersService.defaultHash
services.networkParametersService.lookup(hashToResolve)
},
resolveContractAttachment = { services.loadContractAttachment(it) },
// `as?` is used due to [MockServices] not implementing [ServiceHubCoreInternal]
isAttachmentTrusted = { (services as? ServiceHubCoreInternal)?.attachmentTrustCalculator?.calculate(it) ?: true }
)
@ -115,6 +114,7 @@ class WireTransaction(componentGroups: List<ComponentGroup>, val privacySalt: Pr
// Helper for deprecated toLedgerTransaction
// TODO: revisit once Deterministic JVM code updated
@Suppress("UNUSED") // not sure if this field can be removed safely??
private val missingAttachment: Attachment by lazy {
object : AbstractAttachment({ byteArrayOf() }, DEPLOYED_CORDAPP_UPLOADER ) {
override val id: SecureHash get() = throw UnsupportedOperationException()
@ -143,8 +143,6 @@ class WireTransaction(componentGroups: List<ComponentGroup>, val privacySalt: Pr
resolveAttachment,
{ stateRef -> resolveStateRef(stateRef)?.serialize() },
{ null },
// Returning a dummy `missingAttachment` Attachment allows this deprecated method to work and it disables "contract version no downgrade rule" as a dummy Attachment returns version 1
{ resolveAttachment(it.txhash) ?: missingAttachment },
{ it.isUploaderTrusted() }
)
}
@ -161,7 +159,6 @@ class WireTransaction(componentGroups: List<ComponentGroup>, val privacySalt: Pr
resolveAttachment,
{ stateRef -> resolveStateRef(stateRef)?.serialize() },
resolveParameters,
{ resolveAttachment(it.txhash) ?: missingAttachment },
{ true } // Any attachment loaded through the DJVM should be trusted
)
}
@ -171,7 +168,6 @@ class WireTransaction(componentGroups: List<ComponentGroup>, val privacySalt: Pr
resolveAttachment: (SecureHash) -> Attachment?,
resolveStateRefAsSerialized: (StateRef) -> SerializedBytes<TransactionState<ContractState>>?,
resolveParameters: (SecureHash?) -> NetworkParameters?,
resolveContractAttachment: (StateRef) -> Attachment,
isAttachmentTrusted: (Attachment) -> Boolean
): LedgerTransaction {
// Look up public keys to authenticated identities.

View File

@ -4,8 +4,6 @@ import com.nhaarman.mockito_kotlin.mock
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test
import java.lang.IllegalArgumentException
import java.lang.RuntimeException
class ClassLoadingUtilsTest {
@ -33,7 +31,7 @@ class ClassLoadingUtilsTest {
@Test(expected = IllegalArgumentException::class)
fun throwsExceptionWhenClassDoesNotContainProperConstructors() {
val classes = createInstancesOfClassesImplementing(BaseInterface::class.java.classLoader, BaseInterface2::class.java)
createInstancesOfClassesImplementing(BaseInterface::class.java.classLoader, BaseInterface2::class.java)
}
@Test

View File

@ -2,9 +2,10 @@ package net.corda.nodeinfo
import net.corda.cliutils.CordaCliWrapper
import net.corda.cliutils.start
import net.corda.core.crypto.*
import net.corda.core.crypto.sign
import net.corda.core.identity.PartyAndCertificate
import net.corda.core.internal.*
import net.corda.core.internal.div
import net.corda.core.internal.readAll
import net.corda.core.node.NodeInfo
import net.corda.core.serialization.SerializationContext
import net.corda.core.serialization.SerializedBytes
@ -15,9 +16,13 @@ import net.corda.core.serialization.serialize
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.internal.SignedNodeInfo
import net.corda.nodeapi.internal.crypto.X509KeyStore
import net.corda.serialization.internal.*
import net.corda.serialization.internal.amqp.*
import picocli.CommandLine.*
import net.corda.serialization.internal.AMQP_P2P_CONTEXT
import net.corda.serialization.internal.CordaSerializationMagic
import net.corda.serialization.internal.SerializationFactoryImpl
import net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme
import net.corda.serialization.internal.amqp.amqpMagic
import picocli.CommandLine.ITypeConverter
import picocli.CommandLine.Option
import java.io.File
import java.nio.file.Path
import java.security.cert.CertificateFactory
@ -164,7 +169,7 @@ class NodeInfoSigner : CordaCliWrapper("nodeinfo-signer", "Display and generate
println(outputFile)
outputFile!!.toFile().writeBytes(nodeInfoSigned.signedInfoNode.serialize().bytes)
outputFile.toFile().writeBytes(nodeInfoSigned.signedInfoNode.serialize().bytes)
return 0
}

View File

@ -134,6 +134,7 @@ public class JavaCommercialPaper implements Contract {
}
@NotNull
@SuppressWarnings("deprecation")
private List<CommandWithParties<Commands>> extractCommands(@NotNull LedgerTransaction tx) {
return tx.getCommands()
.stream()

View File

@ -221,19 +221,19 @@ internal inline fun <reified T : MoveCommand> verifyFlattenedMoveCommand(inputs:
// see a signature from each of those keys. The actual signatures have been verified against the transaction
// data by the platform before execution.
val owningPubKeys = inputs.map { it.owner.owningKey }.toSet()
val commands = commands.groupCommands<T>()
val groupedCommands = commands.groupCommands<T>()
// Does not use requireThat to maintain message compatibility with verifyMoveCommand.
if (commands.isEmpty()) {
if (groupedCommands.isEmpty()) {
throw IllegalStateException("Required ${T::class.qualifiedName} command")
}
requireThat {
"move commands can only differ by signing keys" using (commands.size == 1)
"move commands can only differ by signing keys" using (groupedCommands.size == 1)
}
val keysThatSigned = commands.values.first()
val keysThatSigned = groupedCommands.values.first()
requireThat {
"the owning keys are a subset of the signing keys" using keysThatSigned.containsAll(owningPubKeys)
}
return commands.keys.single()
return groupedCommands.keys.single()
}
/** Group commands by instances of the given type. */

View File

@ -1,22 +1,27 @@
package net.corda.nodeapi.exceptions
import net.corda.core.ClientRelevantError
import net.corda.core.CordaRuntimeException
import net.corda.core.crypto.SecureHash
import net.corda.core.flows.IdentifiableException
import net.corda.core.serialization.CordaSerializable
/**
* Thrown to indicate that an attachment was already uploaded to a Corda node.
*/
class DuplicateAttachmentException(attachmentHash: String) : java.nio.file.FileAlreadyExistsException(attachmentHash), ClientRelevantError
class DuplicateAttachmentException(attachmentHash: String) :
java.nio.file.FileAlreadyExistsException(attachmentHash),
@Suppress("DEPRECATION") net.corda.core.ClientRelevantError
/**
* Thrown to indicate that a flow was not designed for RPC and should be started from an RPC client.
*/
class NonRpcFlowException(logicType: Class<*>) : IllegalArgumentException("${logicType.name} was not designed for RPC"), ClientRelevantError
class NonRpcFlowException(logicType: Class<*>) :
IllegalArgumentException("${logicType.name} was not designed for RPC"),
@Suppress("DEPRECATION") net.corda.core.ClientRelevantError
class OutdatedNetworkParameterHashException(old: SecureHash, new: SecureHash) : CordaRuntimeException(TEMPLATE.format(old, new)), ClientRelevantError {
class OutdatedNetworkParameterHashException(old: SecureHash, new: SecureHash) :
CordaRuntimeException(TEMPLATE.format(old, new)),
@Suppress("DEPRECATION") net.corda.core.ClientRelevantError
{
private companion object {
private const val TEMPLATE = "Refused to accept parameters with hash %s because network map advertises update with hash %s. Please check newest version"
@ -26,7 +31,9 @@ class OutdatedNetworkParameterHashException(old: SecureHash, new: SecureHash) :
/**
* Thrown to indicate that the command was rejected by the node, typically due to a special temporary mode.
*/
class RejectedCommandException(message: String) : CordaRuntimeException(message), ClientRelevantError
class RejectedCommandException(message: String) :
CordaRuntimeException(message),
@Suppress("DEPRECATION") net.corda.core.ClientRelevantError
/**
* Allows an implementing [Throwable] to be propagated to RPC clients.

View File

@ -54,7 +54,6 @@ class BCCryptoService(private val legalName: X500Principal, private val certific
}
}
@JvmOverloads
override fun sign(alias: String, data: ByteArray, signAlgorithm: String?): ByteArray {
try {
return when(signAlgorithm) {

View File

@ -55,15 +55,15 @@ class AttachmentVersionNumberMigration : CustomTaskChange {
}
availableAttachments.forEach { attachmentId ->
val versions = networkParameters?.whitelistedContractImplementations?.values.mapNotNull { it.indexOfFirst { it.toString() == attachmentId } }.filter { it >= 0 }
val versions = networkParameters.whitelistedContractImplementations.values.map { it.indexOfFirst { aid -> aid.toString() == attachmentId } }.filter { it >= 0 }
val maxPosition = versions.max() ?: 0
if (maxPosition > 0) {
val version = maxPosition + 1
val msg = "Updating version of attachment $attachmentId to '$version'."
val updateVersionMsg = "Updating version of attachment $attachmentId to '$version'."
if (versions.toSet().size > 1)
logger.warn("Several versions based on whitelistedContractImplementations position are available: ${versions.toSet()}. $msg")
logger.warn("Several versions based on whitelistedContractImplementations position are available: ${versions.toSet()}. $updateVersionMsg")
else
logger.info(msg)
logger.info(updateVersionMsg)
updateVersion(connection, attachmentId, version)
}
}
@ -88,8 +88,8 @@ class AttachmentVersionNumberMigration : CustomTaskChange {
private fun getNetworkParametersFromFile(path: Path): NetworkParameters? {
return try {
val networkParametersBytes = path?.readObject<SignedNetworkParameters>()
networkParametersBytes?.raw?.deserialize()
val networkParametersBytes = path.readObject<SignedNetworkParameters>()
networkParametersBytes.raw.deserialize()
} catch (e: Exception) {
// This condition is logged in the calling function, so no need to do that here.
null

View File

@ -269,6 +269,7 @@ class CordaPersistence(
(_dataSource as? AutoCloseable)?.close()
}
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
val hikariPoolThreadLocal: ThreadLocal<List<Object>>? by lazy(LazyThreadSafetyMode.PUBLICATION) {
val hikariDataSource = dataSource as? HikariDataSource
if (hikariDataSource == null) {
@ -279,9 +280,11 @@ class CordaPersistence(
val pool: HikariPool = poolField.get(hikariDataSource) as HikariPool
val connectionBagField: Field = HikariPool::class.java.getDeclaredField("connectionBag")
connectionBagField.isAccessible = true
@Suppress("UNCHECKED_CAST")
val connectionBag: ConcurrentBag<ConcurrentBag.IConcurrentBagEntry> = connectionBagField.get(pool) as ConcurrentBag<ConcurrentBag.IConcurrentBagEntry>
val threadListField: Field = ConcurrentBag::class.java.getDeclaredField("threadList")
threadListField.isAccessible = true
@Suppress("UNCHECKED_CAST")
val threadList: ThreadLocal<List<Object>> = threadListField.get(connectionBag) as ThreadLocal<List<Object>>
threadList
}

View File

@ -132,6 +132,7 @@ class HibernateConfiguration(
ClassLoaderServiceImpl(customClassLoader))
}
@Suppress("DEPRECATION")
val metadataBuilder = metadataSources.getMetadataBuilder(config.standardServiceRegistryBuilder.build())
val metadata = buildHibernateMetadata(metadataBuilder, jdbcUrl, attributeConverters)
return metadata.sessionFactoryBuilder.run {

View File

@ -118,6 +118,7 @@ class DelegatingStatisticsService(private val delegate: Statistics) : Statistics
return delegate.naturalIdCachePutCount
}
@Suppress("DEPRECATION")
override fun getNaturalIdCacheStatistics(arg0: String): NaturalIdCacheStatistics {
return delegate.getNaturalIdCacheStatistics(arg0)
}
@ -190,6 +191,7 @@ class DelegatingStatisticsService(private val delegate: Statistics) : Statistics
return delegate.secondLevelCacheRegionNames
}
@Suppress("DEPRECATION")
override fun getSecondLevelCacheStatistics(arg0: String): SecondLevelCacheStatistics {
return delegate.getSecondLevelCacheStatistics(arg0)
}

View File

@ -1,6 +1,5 @@
package net.corda.contracts
import junit.framework.Assert.assertNotNull
import net.corda.client.rpc.CordaRPCClient
import net.corda.core.contracts.HashAttachmentConstraint
import net.corda.core.contracts.SignatureAttachmentConstraint
@ -17,6 +16,7 @@ import net.corda.testing.node.internal.internalDriver
import org.junit.Assume.assumeFalse
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
open class SignatureConstraintMigrationFromHashConstraintsTests : SignatureConstraintVersioningTests() {

View File

@ -297,7 +297,6 @@ class RetryFlow() : FlowLogic<String>(), IdempotentFlow {
override fun call(): String {
progressTracker.currentStep = FIRST_STEP
throw ExceptionToCauseFiniteRetry()
return "Result"
}
}

View File

@ -44,7 +44,7 @@ abstract class MutableClock(private var _delegateClock: Clock) : CordaClock() {
}
private val _version = AtomicLong(0L)
override val mutations: Observable<Long> by lazy {
Observable.create { subscriber: Subscriber<in Long> ->
Observable.unsafeCreate { subscriber: Subscriber<in Long> ->
if (!subscriber.isUnsubscribed) {
mutationObservers.add(subscriber)
// This is not very intuitive, but subscribing to a subscriber observes unsubscribes.

View File

@ -96,6 +96,7 @@ class InitialRegistrationCmdLineOptions : SharedNodeCmdLineOptions() {
require(!config.devMode || config.devModeOptions?.allowCompatibilityZone == true) {
"Cannot perform initial registration when 'devMode' is true, unless 'devModeOptions.allowCompatibilityZone' is also true."
}
@Suppress("DEPRECATION")
require(config.compatibilityZoneURL != null || config.networkServices != null) {
"compatibilityZoneURL or networkServices must be present in the node configuration file in registration mode."
}
@ -167,6 +168,7 @@ open class NodeCmdLineOptions : SharedNodeCmdLineOptions() {
override fun parseConfiguration(configuration: Config): Valid<NodeConfiguration> {
return super.parseConfiguration(configuration).doIfValid { config ->
if (isRegistration) {
@Suppress("DEPRECATION")
require(config.compatibilityZoneURL != null || config.networkServices != null) {
"compatibilityZoneURL or networkServices must be present in the node configuration file in registration mode."
}

View File

@ -88,7 +88,6 @@ import net.corda.nodeapi.internal.cryptoservice.bouncycastle.BCCryptoService
import net.corda.nodeapi.internal.persistence.*
import net.corda.tools.shell.InteractiveShell
import org.apache.activemq.artemis.utils.ReusableLatch
import org.hibernate.type.descriptor.java.JavaTypeDescriptorRegistry
import org.slf4j.Logger
import rx.Observable
import rx.Scheduler
@ -1140,7 +1139,8 @@ fun createCordaPersistence(databaseConfig: DatabaseConfig,
// Hibernate warns about not being able to find a descriptor if we don't provide one, but won't use it by default
// so we end up providing both descriptor and converter. We should re-examine this in later versions to see if
// either Hibernate can be convinced to stop warning, use the descriptor by default, or something else.
JavaTypeDescriptorRegistry.INSTANCE.addDescriptor(AbstractPartyDescriptor(wellKnownPartyFromX500Name, wellKnownPartyFromAnonymous))
@Suppress("DEPRECATION")
org.hibernate.type.descriptor.java.JavaTypeDescriptorRegistry.INSTANCE.addDescriptor(AbstractPartyDescriptor(wellKnownPartyFromX500Name, wellKnownPartyFromAnonymous))
val attributeConverters = listOf(PublicKeyToTextConverter(), AbstractPartyToX500NameAsStringConverter(wellKnownPartyFromX500Name, wellKnownPartyFromAnonymous))
val jdbcUrl = hikariProperties.getProperty("dataSource.url", "")
return CordaPersistence(databaseConfig, schemaService.schemaOptions.keys, jdbcUrl, cacheFactory, attributeConverters, customClassLoader)

View File

@ -339,7 +339,7 @@ internal class CordaRPCOpsImpl(
if (drainPendingFlows) {
logger.info("Waiting for pending flows to complete before shutting down.")
setFlowsDrainingModeEnabled(true)
val subscription = pendingFlowsCount()
val subscription = @Suppress("DEPRECATION") pendingFlowsCount()
.updates
.doOnNext { (completed, total) -> logger.info("Pending flows progress before shutdown: $completed / $total.") }
.doOnCompleted { setPersistentDrainingModeProperty(enabled = false, propagateChange = false) }

View File

@ -556,7 +556,7 @@ open class Node(configuration: NodeConfiguration,
log.info("Shutdown complete")
}
fun <T : FlowLogic<*>> registerInitiatedFlow(smm: StateMachineManager, initiatedFlowClass: Class<T>) {
fun <T : FlowLogic<*>> registerInitiatedFlow(@Suppress("UNUSED_PARAMETER") smm: StateMachineManager, initiatedFlowClass: Class<T>) {
this.flowManager.registerInitiatedFlow(initiatedFlowClass)
}
}

View File

@ -484,7 +484,7 @@ fun CliWrapperBase.initLogging(baseDirectory: Path): Boolean {
//Test for access to the logging path and shutdown if we are unable to reach it.
val logPath = baseDirectory / NodeCliCommand.LOGS_DIRECTORY_NAME
try {
logPath.safeSymbolicRead()?.createDirectories()
logPath.safeSymbolicRead().createDirectories()
} catch (e: IOException) {
printError("Unable to create logging directory ${logPath.toString()}. Node will now shutdown.")
return false

View File

@ -158,6 +158,7 @@ data class NodeConfigurationImpl(
}
// Support the deprecated method of configuring network services with a single compatibilityZoneURL option
@Suppress("DEPRECATION")
if (compatibilityZoneURL != null && networkServices == null) {
networkServices = NetworkServicesConfig(compatibilityZoneURL, compatibilityZoneURL, inferred = true)
}
@ -244,6 +245,7 @@ data class NodeConfigurationImpl(
private fun validateDevModeOptions(): List<String> {
if (devMode) {
@Suppress("DEPRECATION")
compatibilityZoneURL?.let {
if (devModeOptions?.allowCompatibilityZone != true) {
return listOf("cannot specify 'compatibilityZoneURL' when 'devMode' is true, unless 'devModeOptions.allowCompatibilityZone' is also true")
@ -264,6 +266,7 @@ data class NodeConfigurationImpl(
private fun validateNetworkServices(): List<String> {
val errors = mutableListOf<String>()
@Suppress("DEPRECATION")
if (compatibilityZoneURL != null && networkServices != null && !(networkServices!!.inferred)) {
errors += "cannot specify both 'compatibilityZoneUrl' and 'networkServices'"
}

View File

@ -2,7 +2,10 @@ package net.corda.node.services.identity
import net.corda.core.crypto.toStringShort
import net.corda.core.identity.*
import net.corda.core.internal.*
import net.corda.core.internal.CertRole
import net.corda.core.internal.NamedCacheFactory
import net.corda.core.internal.hash
import net.corda.core.internal.toSet
import net.corda.core.node.services.IdentityService
import net.corda.core.node.services.UnknownAnonymousPartyException
import net.corda.core.serialization.SingletonSerializeAsToken
@ -286,7 +289,7 @@ class PersistentIdentityService(cacheFactory: NamedCacheFactory) : SingletonSeri
// Allows us to eliminate keys we know belong to others by using the cache contents that might have been seen during other identity activity.
// Concentrating activity on the identity cache works better than spreading checking across identity and key management, because we cache misses too.
fun stripNotOurKeys(keys: Iterable<PublicKey>): Iterable<PublicKey> {
return keys.filter { certificateFromKey(it)?.name in ourNames }
return keys.filter { (@Suppress("DEPRECATION") certificateFromKey(it))?.name in ourNames }
}
override fun registerKeyToParty(key: PublicKey, party: Party) {

View File

@ -12,10 +12,10 @@ private fun <V> Fiber<V>.swappedOutThreadLocals(): Any = fiberThreadLocalsField.
private val threadLocalInitialValueMethod: Method = ThreadLocal::class.java.getDeclaredMethod("initialValue")
.apply { this.isAccessible = true }
private fun <T> ThreadLocal<T>.initialValue(): T? = threadLocalInitialValueMethod.invoke(this) as T?
private fun <T> ThreadLocal<T>.initialValue(): T? = @Suppress("UNCHECKED_CAST") (threadLocalInitialValueMethod.invoke(this) as T?)
// TODO: This method uses a built-in Quasar function to make a map of all ThreadLocals. This is probably inefficient, but the only API readily available.
fun <V, T> Fiber<V>.swappedOutThreadLocalValue(threadLocal: ThreadLocal<T>): T? {
val threadLocals = swappedOutThreadLocals()
return (ThreadAccess.toMap(threadLocals)[threadLocal] as T?) ?: threadLocal.initialValue()
return (@Suppress("UNCHECKED_CAST") (ThreadAccess.toMap(threadLocals)[threadLocal] as T?)) ?: threadLocal.initialValue()
}

View File

@ -10,7 +10,7 @@ import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.transactions.LedgerTransaction
import net.corda.nodeapi.internal.persistence.withoutDatabaseAccess
class InMemoryTransactionVerifierService(numberOfWorkers: Int) : SingletonSerializeAsToken(), TransactionVerifierService, TransactionVerifierServiceInternal, AutoCloseable {
class InMemoryTransactionVerifierService(@Suppress("UNUSED_PARAMETER") numberOfWorkers: Int) : SingletonSerializeAsToken(), TransactionVerifierService, TransactionVerifierServiceInternal, AutoCloseable {
override fun verify(transaction: LedgerTransaction): CordaFuture<Unit> = this.verify(transaction, emptyList())
override fun verify(transaction: LedgerTransaction, extraAttachments: List<Attachment>): CordaFuture<Unit> {

View File

@ -164,7 +164,7 @@ class NodeVaultService(
}
}
private fun recordUpdate(update: Vault.Update<ContractState>, previouslySeen: Boolean): Vault.Update<ContractState> {
private fun recordUpdate(update: Vault.Update<ContractState>): Vault.Update<ContractState> {
if (!update.isEmpty()) {
val producedStateRefs = update.produced.map { it.ref }
val producedStateRefsMap = update.produced.associateBy { it.ref }
@ -220,7 +220,7 @@ class NodeVaultService(
fun flushBatch(previouslySeen: Boolean) {
val updates = makeUpdates(batch, statesToRecord, previouslySeen)
processAndNotify(updates, previouslySeen)
processAndNotify(updates)
batch.clear()
}
@ -369,11 +369,11 @@ class NodeVaultService(
return states
}
private fun processAndNotify(updates: List<Vault.Update<ContractState>>, previouslySeen: Boolean) {
private fun processAndNotify(updates: List<Vault.Update<ContractState>>) {
if (updates.isEmpty()) return
val netUpdate = updates.reduce { update1, update2 -> update1 + update2 }
if (!netUpdate.isEmpty()) {
recordUpdate(netUpdate, previouslySeen)
recordUpdate(netUpdate)
mutex.locked {
// flowId was required by SoftLockManager to perform auto-registration of soft locks for new states
val uuid = (Strand.currentStrand() as? FlowStateMachineImpl<*>)?.id?.uuid

View File

@ -38,7 +38,7 @@ class InfrequentlyMutatedCache<K : Any, V : Any>(name: String, cacheFactory: Nam
* @param key The key to retrieve.
*/
fun getIfPresent(key: K): V? {
val wrapper = backingCache.get(key) { k: K ->
val wrapper = backingCache.get(key) {
null
}
return when (wrapper) {
@ -89,9 +89,9 @@ class InfrequentlyMutatedCache<K : Any, V : Any>(name: String, cacheFactory: Nam
private fun decrementInvalidators(key: K, value: Wrapper.Invalidated<V>) {
if(value.invalidators.decrementAndGet() == 0) {
// Maybe we can replace the invalidated value with nothing, so it gets loaded next time.
backingCache.asMap().compute(key) { key: K, currentValue: Wrapper<V>? ->
backingCache.asMap().compute(key) { computeKey: K, currentValue: Wrapper<V>? ->
if(currentValue === value && value.invalidators.get() == 0) {
currentlyInvalid.remove(key)
currentlyInvalid.remove(computeKey)
null
} else currentValue
}

View File

@ -62,7 +62,10 @@ class BFTSmartNotaryService(
private val cluster: BFTSmart.Cluster = makeBFTCluster(notaryIdentityKey, bftSMaRtConfig)
protected open fun makeBFTCluster(notaryKey: PublicKey, bftSMaRtConfig: BFTSmartConfig): BFTSmart.Cluster {
private fun makeBFTCluster(
@Suppress("UNUSED_PARAMETER") notaryKey: PublicKey,
@Suppress("UNUSED_PARAMETER") bftSMaRtConfig: BFTSmartConfig
): BFTSmart.Cluster {
return object : BFTSmart.Cluster {
override fun waitUntilAllReplicasHaveInitialized() {
log.warn("A BFT replica may still be initializing, in which case the upcoming consensus change may cause it to spin.")
@ -180,6 +183,7 @@ class BFTSmartNotaryService(
val references = transaction.references
val notary = transaction.notary
val timeWindow = (transaction as? FilteredTransaction)?.timeWindow
@Suppress("DEPRECATION")
if (notary !in services.myInfo.legalIdentities) throw NotaryInternalException(NotaryError.WrongNotary)
commitInputStates(inputs, id, callerIdentity.name, requestSignature, timeWindow, references)
log.debug { "Inputs committed successfully, signing $id" }

View File

@ -567,7 +567,7 @@ public class VaultQueryJavaTests {
private Pair<Path, SecureHash> makeTestJar(Path path) throws IOException {
Path file = Paths.get(path.toAbsolutePath().toString(), "$counter.jar");
ContractJarTestUtils.INSTANCE.makeTestJar(Files.newOutputStream(file));
return new Pair(file, SecureHash.sha256(Files.readAllBytes(file)));
return new Pair<>(file, SecureHash.sha256(Files.readAllBytes(file)));
}
@Test

View File

@ -25,7 +25,7 @@ class ThreadContextAdjustingRpcOpsProxyTest {
true
}
val result = proxy.killFlow(StateMachineRunId.createRandom())
proxy.killFlow(StateMachineRunId.createRandom())
assertThat(Thread.currentThread().contextClassLoader).isNotEqualTo(mockClassloader)
}
}

View File

@ -84,7 +84,7 @@ class RoundTripObservableSerializerTests {
// What we're actually going to serialize then deserialize
val obs = Observable.create<Int> { Math.random() }
val obs = Observable.unsafeCreate<Int> { Math.random() }
val serverSerializationContext = RpcServerObservableSerializer.createContext(
serializationContext, serverObservableContext)

View File

@ -71,7 +71,7 @@ class RpcServerObservableSerializerTests {
register(RpcServerObservableSerializer())
}
val obs = Observable.create<Int> { Math.random() }
val obs = Observable.unsafeCreate<Int> { Math.random() }
val newContext = RpcServerObservableSerializer.createContext(serializationContext, observable)
try {

View File

@ -125,12 +125,12 @@ class InMemoryIdentityServiceTests {
val service = createService(alice)
service.verifyAndRegisterIdentity(aliceTxIdentity)
var actual = service.certificateFromKey(aliceTxIdentity.party.owningKey)
var actual = @Suppress("DEPRECATION") service.certificateFromKey(aliceTxIdentity.party.owningKey)
assertEquals(aliceTxIdentity, actual!!)
assertNull(service.certificateFromKey(bobTxIdentity.party.owningKey))
assertNull(@Suppress("DEPRECATION") service.certificateFromKey(bobTxIdentity.party.owningKey))
service.verifyAndRegisterIdentity(bobTxIdentity)
actual = service.certificateFromKey(bobTxIdentity.party.owningKey)
actual = @Suppress("DEPRECATION") service.certificateFromKey(bobTxIdentity.party.owningKey)
assertEquals(bobTxIdentity, actual!!)
}

View File

@ -169,12 +169,12 @@ class PersistentIdentityServiceTests {
identityService.verifyAndRegisterIdentity(alice)
identityService.verifyAndRegisterIdentity(aliceTxIdentity)
var actual = identityService.certificateFromKey(aliceTxIdentity.party.owningKey)
var actual = @Suppress("DEPRECATION") identityService.certificateFromKey(aliceTxIdentity.party.owningKey)
assertEquals(aliceTxIdentity, actual!!)
assertNull(identityService.certificateFromKey(bobTxIdentity.party.owningKey))
assertNull(@Suppress("DEPRECATION") identityService.certificateFromKey(bobTxIdentity.party.owningKey))
identityService.verifyAndRegisterIdentity(bobTxIdentity)
actual = identityService.certificateFromKey(bobTxIdentity.party.owningKey)
actual = @Suppress("DEPRECATION") identityService.certificateFromKey(bobTxIdentity.party.owningKey)
assertEquals(bobTxIdentity, actual!!)
}
@ -233,13 +233,13 @@ class PersistentIdentityServiceTests {
assertEquals(alice.party, aliceParent!!)
val bobReload = newPersistentIdentityService.certificateFromKey(anonymousBob.party.owningKey)
val bobReload = @Suppress("DEPRECATION") newPersistentIdentityService.certificateFromKey(anonymousBob.party.owningKey)
assertEquals(anonymousBob, bobReload!!)
}
@Test
fun `ensure no exception when looking up an unregistered confidential identity`() {
val (alice, anonymousAlice) = createConfidentialIdentity(ALICE.name)
val (_, anonymousAlice) = createConfidentialIdentity(ALICE.name)
// Ensure no exceptions are thrown if we attempt to look up an unregistered CI
assertNull(identityService.wellKnownPartyFromAnonymous(AnonymousParty(anonymousAlice.owningKey)))

View File

@ -110,10 +110,10 @@ class NetworkMapUpdaterTest {
@Test
fun `process add node updates from network map, with additional node infos from dir`() {
setUpdater()
val (nodeInfo1, signedNodeInfo1) = createNodeInfoAndSigned("Info 1")
val (nodeInfo2, signedNodeInfo2) = createNodeInfoAndSigned("Info 2")
val (nodeInfo3, signedNodeInfo3) = createNodeInfoAndSigned("Info 3")
val (nodeInfo4, signedNodeInfo4) = createNodeInfoAndSigned("Info 4")
val (_, signedNodeInfo1) = createNodeInfoAndSigned("Info 1")
val (_, signedNodeInfo2) = createNodeInfoAndSigned("Info 2")
val (_, signedNodeInfo3) = createNodeInfoAndSigned("Info 3")
val (_, signedNodeInfo4) = createNodeInfoAndSigned("Info 4")
val fileNodeInfoAndSigned = createNodeInfoAndSigned("Info from file")
//Test adding new node.
@ -468,6 +468,7 @@ class NetworkMapUpdaterTest {
}
on { addNodes(any<List<NodeInfo>>()) }.then {
@Suppress("UNCHECKED_CAST")
val nodeInfos = it.arguments[0] as List<NodeInfo>
nodeInfos.forEach { nodeInfo ->
addNodeToMockCache(nodeInfo, data)

View File

@ -15,11 +15,7 @@ import net.corda.finance.contracts.FixOf
import net.corda.finance.contracts.asset.CASH
import net.corda.finance.contracts.asset.Cash
import net.corda.irs.flows.RatesFixFlow
import net.corda.testing.core.ALICE_NAME
import net.corda.testing.core.BOB_NAME
import net.corda.testing.core.DUMMY_NOTARY_NAME
import net.corda.testing.core.TestIdentity
import net.corda.testing.core.singleIdentity
import net.corda.testing.core.*
import net.corda.testing.internal.LogHelper
import net.corda.testing.node.MockNetwork
import net.corda.testing.node.MockNodeParameters
@ -53,7 +49,7 @@ class OracleNodeTearOffTests {
@Before
// DOCSTART 1
fun setUp() {
mockNet = MockNetwork(cordappPackages = listOf("net.corda.finance.contracts", "net.corda.irs"))
mockNet = @Suppress("DEPRECATION") MockNetwork(cordappPackages = listOf("net.corda.finance.contracts", "net.corda.irs"))
aliceNode = mockNet.createPartyNode(ALICE_NAME)
oracleNode = mockNet.createNode(MockNodeParameters(legalName = BOB_NAME)).apply {
transaction {

View File

@ -78,7 +78,7 @@ class CorDappCustomSerializer(
data.withDescribed(descriptor) {
data.withList {
(proxySerializer as ObjectSerializer).propertySerializers.forEach { (_, serializer) ->
proxySerializer.propertySerializers.forEach { (_, serializer) ->
serializer.writeProperty(proxy, this, output, context, debugIndent)
}
}

View File

@ -123,7 +123,13 @@ class ComposableObjectWriter(
}
}
fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput, context: SerializationContext, debugIndent: Int) {
fun writeObject(
obj: Any, data: Data,
@Suppress("UNUSED_PARAMETER") type: Type,
output: SerializationOutput,
context: SerializationContext,
debugIndent: Int
) {
data.withDescribed(typeNotation.descriptor) {
withList {
propertySerializers.values.forEach { propertySerializer ->

View File

@ -48,8 +48,8 @@ class CarpentryDependencyGraph private constructor(private val typesRequiringCar
private fun RemoteTypeInformation.dependsOn(dependees: Collection<RemoteTypeInformation>) {
val dependeesInTypesRequiringCarpentry = dependees.filter { it in typesRequiringCarpentry }
if (dependeesInTypesRequiringCarpentry.isEmpty()) return // we don't want to put empty sets into the map.
dependencies.compute(this) { _, dependees ->
dependees?.apply { addAll(dependeesInTypesRequiringCarpentry) } ?:
dependencies.compute(this) { _, dependeesInner ->
dependeesInner?.apply { addAll(dependeesInTypesRequiringCarpentry) } ?:
dependeesInTypesRequiringCarpentry.toMutableSet()
}
}

View File

@ -51,7 +51,7 @@ internal data class LocalTypeInformationBuilder(val lookup: LocalTypeLookup,
val previous = validateProperties
return try {
validateProperties = false
block()
this.block()
} finally {
validateProperties = previous
}
@ -183,7 +183,7 @@ internal data class LocalTypeInformationBuilder(val lookup: LocalTypeLookup,
val previous = resolutionContext
return try {
resolutionContext = newContext
block()
this.block()
} finally {
resolutionContext = previous
}
@ -253,9 +253,9 @@ internal data class LocalTypeInformationBuilder(val lookup: LocalTypeLookup,
}
val evolutionConstructors = evolutionConstructors(type).map { ctor ->
val constructorInformation = buildConstructorInformation(type, ctor)
val evolutionProperties = buildObjectProperties(rawType, constructorInformation)
EvolutionConstructorInformation(constructorInformation, evolutionProperties)
val evolutionConstructorInformation = buildConstructorInformation(type, ctor)
val evolutionProperties = buildObjectProperties(rawType, evolutionConstructorInformation)
EvolutionConstructorInformation(evolutionConstructorInformation, evolutionProperties)
}
return LocalTypeInformation.Composable(type, typeIdentifier, constructorInformation, evolutionConstructors, properties,
@ -514,7 +514,7 @@ private fun evolutionConstructors(type: Type): List<KFunction<Any>> {
val version = it.findAnnotation<DeprecatedConstructorForDeserialization>()?.version
if (version == null) null else version to it
}
.sortedBy { (version, ctor) -> version }
.map { (version, ctor) -> ctor.apply { isAccessible = true} }
.sortedBy { (version, _) -> version }
.map { (_, ctor) -> ctor.apply { isAccessible = true} }
.toList()
}

View File

@ -3,10 +3,7 @@ package net.corda.serialization.internal.amqp
import net.corda.core.serialization.CordaSerializable
import net.corda.serialization.internal.amqp.testutils.*
import org.junit.Test
import java.io.NotSerializableException
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFailsWith
import kotlin.test.fail
// Prior to certain fixes being made within the [PropertySerializaer] classes these simple
@ -533,7 +530,7 @@ class DeserializeSimpleTypesTests {
}
@CordaSerializable
class Garbo private constructor(value: Int) {
class Garbo private constructor(@Suppress("UNUSED_PARAMETER", "unused") value: Int) {
companion object {
fun make(value: Int) = Garbo(value)
}
@ -600,6 +597,7 @@ No custom serializers registered.
// See CORDA-2782
@Test
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun comparableNotWhitelistedOk() {
@CordaSerializable
class Ok(val value: String) : java.lang.Comparable<Ok> {

View File

@ -1,14 +1,12 @@
package net.corda.serialization.internal.amqp
import net.corda.serialization.internal.AllWhitelist
import net.corda.serialization.internal.NotSerializable
import net.corda.serialization.internal.model.ConfigurableLocalTypeModel
import net.corda.serialization.internal.model.LocalTypeInformation
import net.corda.serialization.internal.model.TypeModellingFingerPrinter
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
class TypeModellingFingerPrinterTests {
@ -26,7 +24,7 @@ class TypeModellingFingerPrinterTests {
}
// Not serializable, because there is no readable property corresponding to the constructor parameter
class NonSerializable(a: String)
class NonSerializable(@Suppress("UNUSED_PARAMETER") a: String)
class HasTypeParameter<T>
data class SuppliesTypeParameter(val value: HasTypeParameter<NonSerializable>)

View File

@ -37,12 +37,12 @@ class LocalTypeModelTests {
class Nested(
val collectionHolder: StringKeyedCollectionHolder<out Int>?,
private val intArray: IntArray,
optionalParam: Short?)
@Suppress("UNUSED_PARAMETER") optionalParam: Short?)
// This can't be treated as a composable type, because the [intArray] parameter is mandatory but we have no readable
// field or property to populate it from.
@Suppress("unused")
class NonComposableNested(val collectionHolder: StringKeyedCollectionHolder<out Int>?, intArray: IntArray)
class NonComposableNested(val collectionHolder: StringKeyedCollectionHolder<out Int>?, @Suppress("UNUSED_PARAMETER") intArray: IntArray)
@Test
fun `Primitives and collections`() {
@ -149,7 +149,7 @@ class LocalTypeModelTests {
class AnotherTransitivelyNonComposable(val e: String, val f: Exception, val g: OneMoreTransitivelyNonComposable)
class OneMoreTransitivelyNonComposable(val h: String, val i: Exception)
class MissingConstructorParameter(val a: String, b: Exception)
class MissingConstructorParameter(val a: String, @Suppress("UNUSED_PARAMETER") b: Exception)
@Test
fun `no unique deserialization constructor creates non-composable type`() {

View File

@ -193,7 +193,7 @@ fun <A> driver(defaultParameters: DriverParameters = DriverParameters(), dsl: Dr
isDebug = defaultParameters.isDebug,
startNodesInProcess = defaultParameters.startNodesInProcess,
waitForAllNodesToFinish = defaultParameters.waitForAllNodesToFinish,
extraCordappPackagesToScan = defaultParameters.extraCordappPackagesToScan,
extraCordappPackagesToScan = @Suppress("DEPRECATION") defaultParameters.extraCordappPackagesToScan,
notarySpecs = defaultParameters.notarySpecs,
jmxPolicy = defaultParameters.jmxPolicy,
compatibilityZone = null,

View File

@ -303,7 +303,7 @@ open class MockNetwork(
constructor(parameters: MockNetworkParameters) : this(emptyList(), defaultParameters = parameters)
private val internalMockNetwork = InternalMockNetwork(
cordappPackages,
@Suppress("DEPRECATION") cordappPackages,
defaultParameters,
networkSendManuallyPumped,
threadPerNode,

View File

@ -1009,7 +1009,7 @@ fun <DI : DriverDSL, D : InternalDriverDSL, A> genericDriver(
isDebug = defaultParameters.isDebug,
startNodesInProcess = defaultParameters.startNodesInProcess,
waitForAllNodesToFinish = defaultParameters.waitForAllNodesToFinish,
extraCordappPackagesToScan = defaultParameters.extraCordappPackagesToScan,
extraCordappPackagesToScan = @Suppress("DEPRECATION") defaultParameters.extraCordappPackagesToScan,
jmxPolicy = defaultParameters.jmxPolicy,
notarySpecs = defaultParameters.notarySpecs,
compatibilityZone = null,
@ -1101,7 +1101,7 @@ fun <A> internalDriver(
systemProperties: Map<String, String> = DriverParameters().systemProperties,
useTestClock: Boolean = DriverParameters().useTestClock,
startNodesInProcess: Boolean = DriverParameters().startNodesInProcess,
extraCordappPackagesToScan: List<String> = DriverParameters().extraCordappPackagesToScan,
extraCordappPackagesToScan: List<String> = @Suppress("DEPRECATION") DriverParameters().extraCordappPackagesToScan,
waitForAllNodesToFinish: Boolean = DriverParameters().waitForAllNodesToFinish,
notarySpecs: List<NotarySpec> = DriverParameters().notarySpecs,
jmxPolicy: JmxPolicy = DriverParameters().jmxPolicy,

View File

@ -607,6 +607,7 @@ private fun mockNodeConfiguration(certificatesDirectory: Path): NodeConfiguratio
doReturn(null).whenever(it).jmxMonitoringHttpPort
doReturn(true).whenever(it).devMode
doReturn(emptyList<String>()).whenever(it).blacklistedAttachmentSigningKeys
@Suppress("DEPRECATION")
doReturn(null).whenever(it).compatibilityZoneURL
doReturn(null).whenever(it).networkServices
doReturn(VerifierType.InMemory).whenever(it).verifierType

View File

@ -11,8 +11,10 @@ import net.corda.core.node.services.CordaService
import net.corda.core.serialization.SingletonSerializeAsToken
import net.corda.core.utilities.getOrThrow
import net.corda.core.utilities.unwrap
import net.corda.testing.core.*
import org.assertj.core.api.Assertions.*
import net.corda.testing.core.DUMMY_BANK_A_NAME
import net.corda.testing.core.DUMMY_BANK_B_NAME
import net.corda.testing.core.singleIdentity
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
@ -68,7 +70,7 @@ class MockNetworkTest {
}
@CordaService
class TestService(services: AppServiceHub) : SingletonSerializeAsToken()
class TestService(@Suppress("UNUSED_PARAMETER") services: AppServiceHub) : SingletonSerializeAsToken()
@InitiatingFlow
class TestInitiator(private val party: Party) : FlowLogic<String>() {

View File

@ -38,7 +38,7 @@ class CheckpointSerializationEnvironmentRule(private val inheritable: Boolean =
}
/** Do not call, instead use [SerializationEnvironmentRule] as a [org.junit.Rule]. */
fun <T> run(taskLabel: String, task: (SerializationEnvironment) -> T): T {
fun <T> run(@Suppress("UNUSED_PARAMETER") taskLabel: String, task: (SerializationEnvironment) -> T): T {
return CheckpointSerializationEnvironmentRule().apply { init() }.runTask(task)
}
}

View File

@ -77,10 +77,10 @@ object JarSignatureTestUtils {
fun Path.getJarSigners(fileName: String) =
JarInputStream(FileInputStream((this / fileName).toFile())).use(JarSignatureCollector::collectSigners)
fun Path.addManifest(fileName: String, vararg entry: Pair<Attributes.Name, String>) {
fun Path.addManifest(fileName: String, vararg entries: Pair<Attributes.Name, String>) {
JarInputStream(FileInputStream((this / fileName).toFile())).use { input ->
val manifest = input.manifest ?: Manifest()
entry.forEach { (attributeName, value) ->
entries.forEach { (attributeName, value) ->
manifest.mainAttributes[attributeName] = value
}
val output = JarOutputStream(FileOutputStream((this / fileName).toFile()), manifest)

View File

@ -5,8 +5,8 @@ import net.corda.nodeapi.internal.DEV_CA_KEY_STORE_PASS
import net.corda.nodeapi.internal.DEV_CA_TRUST_STORE_PASS
import net.corda.nodeapi.internal.DEV_CA_TRUST_STORE_PRIVATE_KEY_PASS
import net.corda.nodeapi.internal.config.FileBasedCertificateStoreSupplier
import net.corda.nodeapi.internal.config.SslConfiguration
import net.corda.nodeapi.internal.config.MutualSslConfiguration
import net.corda.nodeapi.internal.config.SslConfiguration
import java.nio.file.Path
class CertificateStoreStubs {
@ -47,7 +47,7 @@ class CertificateStoreStubs {
fun withCertificatesDirectory(certificatesDirectory: Path, keyStoreFileName: String = KeyStore.DEFAULT_STORE_FILE_NAME,
keyStorePassword: String = KeyStore.DEFAULT_STORE_PASSWORD, keyPassword: String = keyStorePassword,
trustStoreFileName: String = TrustStore.DEFAULT_STORE_FILE_NAME, trustStorePassword: String = TrustStore.DEFAULT_STORE_PASSWORD, trustStoreKeyPassword: String = TrustStore.DEFAULT_KEY_PASSWORD,
useOpenSsl: Boolean = false): MutualSslConfiguration {
@Suppress("UNUSED_PARAMETER") useOpenSsl: Boolean = false): MutualSslConfiguration {
val keyStore = FileBasedCertificateStoreSupplier(certificatesDirectory / keyStoreFileName, keyStorePassword, keyPassword)
val trustStore = FileBasedCertificateStoreSupplier(certificatesDirectory / trustStoreFileName, trustStorePassword, trustStoreKeyPassword)

View File

@ -244,7 +244,7 @@ class NetworkBootstrapperRunnerTests {
@Test
fun `test when packages overlap that the bootstrapper fails with a sensible message`() {
val (runner, mockBootstrapper) = getRunner()
val (runner, _) = getRunner()
val conf = packageOverlapConfigFile.copyToTestDir()
runner.networkParametersFile = conf
val exitCode = runner.runProgram()
@ -255,7 +255,7 @@ class NetworkBootstrapperRunnerTests {
@Test
fun `test when keyfile does not exist then bootstrapper fails with a sensible message`() {
val (runner, mockBootstrapper) = getRunner()
val (runner, _) = getRunner()
runner.networkParametersFile = dirAlice / "filename-that-doesnt-exist"
val exception = assertFailsWith<FileNotFoundException> { runner.runProgram() }
assert(exception.message!!.startsWith("Unable to find specified network parameters config file at"))

View File

@ -29,7 +29,7 @@ apply plugin: 'idea'
description 'A javaagent to allow hooking into Kryo checkpoints'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "javassist:javassist:$javaassist_version"
compile "com.esotericsoftware:kryo:4.0.0"

View File

@ -214,16 +214,19 @@ object CheckpointHook : ClassFileTransformer {
if (clazz.isArray) {
log.debug { "readFieldExit array type: $clazz, value: $value]" }
if (Array<Number>::class.java.isAssignableFrom(clazz)) {
@Suppress("UNCHECKED_CAST")
val numberValue = value as Array<Number>
log.debug { "readFieldExit array of number: $clazz = ${numberValue.joinToString(",")}" }
return numberValue.joinToString(",")
} else if (clazz == Array<Boolean>::class.java) {
@Suppress("UNCHECKED_CAST")
val arrayValue = value as Array<Boolean>
log.debug { "readFieldExit array of boolean: $clazz = ${arrayValue.joinToString(",")}" }
return arrayValue.joinToString(",")
}
// N dimensional arrays
else if (arrayOf<Array<*>>()::class.java.isAssignableFrom(clazz)) {
@Suppress("UNCHECKED_CAST")
val arrayValue = value as Array<Array<*>>
return arrayValue.map { arrayEntry ->
log.debug { "N Dimensional: $clazz, $arrayEntry, ${arrayEntry::class.java}" }
@ -264,6 +267,7 @@ object CheckpointHook : ClassFileTransformer {
log.debug { "readFieldExit boolean array: $clazz = ${arrayValue.joinToString(",")}" }
return arrayValue.joinToString(",")
}
@Suppress("UNCHECKED_CAST")
log.debug { "ARRAY OF TYPE: $clazz (size: ${(value as Array<Any?>).size})" }
}
return null
@ -347,6 +351,7 @@ object CheckpointHook : ClassFileTransformer {
builder.append(CharArray(indent) { ' ' })
builder.append(" ${statsInfo.fieldName} ")
if (statsInfo.fieldType != null && statsInfo.fieldType.isArray) {
@Suppress("UNCHECKED_CAST")
val arrayValue = (statsTree.value as Array<Any?>)
builder.append("${statsInfo.fieldType} (array length:${arrayValue.size})")
} else if (statsInfo.fieldType != null && statsTree.value is Collection<*>) {
@ -454,7 +459,6 @@ fun readTrees(events: List<StatsEvent>, index: Int, idMap: IdentityHashMap<Any,
inField = true
}
is StatsEvent.Exit -> {
arrayIdx = 0
if (idMap.containsKey(event.value)) {
val identityInfo = idMap[event.value]!!
idMap[event.value] = IdentityInfo(identityInfo.tree, identityInfo.refCount + 1)
@ -472,7 +476,7 @@ fun readTrees(events: List<StatsEvent>, index: Int, idMap: IdentityHashMap<Any,
if (idMap.containsKey(event.value)) {
val identityInfo = idMap[event.value]!!
idMap[event.value] = IdentityInfo(identityInfo.tree, identityInfo.refCount + 1)
log.debug { "Skipping repeated StatsEvent.ObjectField: ${event.value} (hashcode:${event.value!!.hashCode()}) (count:${idMap[event.value]?.refCount})" }
log.debug { "Skipping repeated StatsEvent.ObjectField: ${event.value} (hashcode:${event.value.hashCode()}) (count:${idMap[event.value]?.refCount})" }
identityInfo
} else {
IdentityInfo(StatsTree.Loop(0), 1)

View File

@ -307,7 +307,7 @@ class InteractiveShellIntegrationTest {
Thread.sleep(5000)
val (output) = mockRenderPrintWriter()
mockRenderPrintWriter()
InteractiveShell.runDumpCheckpoints(aliceNode.rpc as InternalCordaRPCOps)
val zipFile = (aliceNode.baseDirectory / NodeStartup.LOGS_DIRECTORY_NAME).list().first { "checkpoints_dump-" in it.toString() }

View File

@ -568,6 +568,7 @@ object InteractiveShell {
cordaRPCOps.terminate(true)
val latch = CountDownLatch(1)
@Suppress("DEPRECATION")
cordaRPCOps.pendingFlowsCount().updates.doOnError { error ->
log.error(error.message)
throw error

View File

@ -295,6 +295,7 @@ object StdoutANSIProgressRenderer : ANSIProgressRenderer() {
// This line looks weird as hell because the magic code to decide if we really have a TTY or not isn't
// actually exposed anywhere as a function (weak sauce). So we have to rely on our knowledge of jansi
// implementation details.
@Suppress("DEPRECATION")
usingANSI = AnsiConsole.wrapOutputStream(System.out) !is AnsiOutputStream
if (usingANSI) {
@ -307,6 +308,7 @@ object StdoutANSIProgressRenderer : ANSIProgressRenderer() {
loggerFor<StdoutANSIProgressRenderer>().warn("Cannot find console appender - progress tracking may not work as expected")
return
}
@Suppress("DEPRECATION")
val scrollingAppender = object : AbstractOutputStreamAppender<OutputStreamManager>(
consoleAppender.name, consoleAppender.layout, consoleAppender.filter,
consoleAppender.ignoreExceptions(), true, consoleAppender.manager) {

View File

@ -6,13 +6,15 @@ import org.crsh.text.RenderPrintWriter;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class OutputFormatCommandTest {
private InvocationContext mockInvocationContext;
private InvocationContext<Map> mockInvocationContext;
private RenderPrintWriter printWriter;
private OutputFormatCommand outputFormatCommand;

View File

@ -3,8 +3,6 @@ package net.corda.webserver.internal
import com.google.common.html.HtmlEscapers.htmlEscaper
import io.netty.channel.unix.Errors
import net.corda.client.jackson.JacksonSupport
import net.corda.client.rpc.CordaRPCClient
import net.corda.client.rpc.RPCException
import net.corda.client.rpc.internal.ReconnectingCordaRPCOps
import net.corda.core.internal.errors.AddressBindingException
import net.corda.core.messaging.CordaRPCOps
@ -28,7 +26,6 @@ import java.io.IOException
import java.io.Writer
import java.lang.reflect.InvocationTargetException
import java.net.BindException
import java.nio.file.NoSuchFileException
import java.util.*
import javax.servlet.http.HttpServletRequest
@ -66,6 +63,7 @@ class NodeWebServer(val config: WebServerConfig) {
val httpsConfiguration = HttpConfiguration()
httpsConfiguration.outputBufferSize = 32768
httpsConfiguration.addCustomizer(SecureRequestCustomizer())
@Suppress("DEPRECATION")
val sslContextFactory = SslContextFactory()
sslContextFactory.keyStorePath = config.keyStorePath
sslContextFactory.setKeyStorePassword(config.keyStorePassword)