From d027b5b8f2bb00ef7f39d6760b658ccc4c165b43 Mon Sep 17 00:00:00 2001 From: Michele Sollecito Date: Mon, 14 May 2018 21:15:52 +0700 Subject: [PATCH] [CORDA-1472]: Crackdown on warnings. (#3136) --- .idea/compiler.xml | 119 ------------------ .../corda/client/jackson/JacksonSupport.kt | 16 +-- .../jackson/StringToMethodCallParser.kt | 2 +- .../jackson/StringToMethodCallParserTest.kt | 1 - .../corda/client/jfx/NodeMonitorModelTest.kt | 6 +- .../client/jfx/model/ContractStateModel.kt | 11 +- .../net/corda/client/jfx/model/Models.kt | 11 +- .../net/corda/client/jfx/model/ModelsUtils.kt | 1 - .../client/jfx/model/NetworkIdentityModel.kt | 2 +- .../client/jfx/model/TransactionDataModel.kt | 4 +- .../corda/client/jfx/utils/AggregatedList.kt | 32 ++--- .../corda/client/jfx/utils/AmountBindings.kt | 3 +- .../corda/client/jfx/utils/AssociatedList.kt | 52 ++++---- .../net/corda/client/jfx/utils/ChosenList.kt | 6 +- .../client/jfx/utils/ConcatenatedList.kt | 38 +++--- .../corda/client/jfx/utils/FlattenedList.kt | 4 +- .../client/jfx/utils/LeftOuterJoinedMap.kt | 12 +- .../net/corda/client/jfx/utils/MappedList.kt | 1 - .../corda/client/jfx/utils/ObservableFold.kt | 2 +- .../client/jfx/utils/ObservableUtilities.kt | 24 ++-- .../utils/ReadOnlyBackedObservableMapBase.kt | 2 +- .../corda/client/jfx/utils/ReplayedList.kt | 6 +- .../client/jfx/model/ExchangeRateModelTest.kt | 3 +- .../client/jfx/utils/AggregatedListTest.kt | 6 +- .../client/jfx/utils/ConcatenatedListTest.kt | 17 +-- .../corda/client/jfx/utils/MappedListTest.kt | 1 - .../net/corda/client/jfx/utils/ReplayedMap.kt | 4 +- .../rpc/internal/CordaRPCClientUtils.kt | 2 +- .../rpc/internal/RPCClientProxyHandler.kt | 25 ++-- .../kryo/KryoClientSerializationScheme.kt | 1 - .../kryo/RpcClientObservableSerializer.kt | 2 +- .../kotlin/rpc/StandaloneCordaRPClientTest.kt | 2 +- .../corda/client/rpc/RPCConcurrencyTests.kt | 2 +- .../net/corda/client/rpc/RPCFailureTests.kt | 2 +- .../client/rpc/RepeatingBytesInputStream.kt | 6 +- .../corda/confidential/SwapIdentitiesFlow.kt | 2 +- .../confidential/IdentitySyncFlowTests.kt | 4 +- .../java/net/corda/core/crypto/Base58.java | 2 +- .../core/flows/IdentifiableException.java | 3 +- .../main/kotlin/net/corda/core/CordaOID.kt | 4 +- .../corda/core/concurrent/ConcurrencyUtils.kt | 12 +- .../corda/core/context/InvocationContext.kt | 1 - .../kotlin/net/corda/core/context/Trace.kt | 4 +- .../kotlin/net/corda/core/contracts/Amount.kt | 2 +- .../core/contracts/ContractAttachment.kt | 4 +- .../net/corda/core/contracts/ContractsDSL.kt | 2 +- .../net/corda/core/contracts/Structures.kt | 2 +- .../TransactionVerificationException.kt | 8 +- .../kotlin/net/corda/core/cordapp/Cordapp.kt | 2 +- .../net/corda/core/crypto/CompositeKey.kt | 24 ++-- .../net/corda/core/crypto/MerkleTree.kt | 6 +- .../kotlin/net/corda/core/crypto/NullKeys.kt | 1 - .../net/corda/core/crypto/SignedData.kt | 2 +- .../flows/AbstractStateReplacementFlow.kt | 6 +- .../corda/core/flows/CollectSignaturesFlow.kt | 16 ++- .../net/corda/core/flows/FlowException.kt | 2 + .../net/corda/core/flows/FlowInitiator.kt | 29 ++--- .../net/corda/core/identity/CordaX500Name.kt | 7 +- .../kotlin/net/corda/core/internal/Emoji.kt | 1 - .../net/corda/core/internal/FetchDataFlow.kt | 1 - .../net/corda/core/internal/FlowIORequest.kt | 3 +- .../corda/core/internal/FlowStateMachine.kt | 8 +- .../net/corda/core/internal/LazyPool.kt | 6 +- .../net/corda/core/internal/LazyStickyPool.kt | 2 +- .../corda/core/internal/ProgressTracker.kt | 2 +- .../corda/core/internal/X509EdDSAEngine.kt | 6 +- .../internal/concurrent/CordaFutureImpl.kt | 2 +- .../core/internal/cordapp/CordappImpl.kt | 2 +- .../net/corda/core/messaging/FlowHandle.kt | 1 - .../net/corda/core/node/AppServiceHub.kt | 1 - .../kotlin/net/corda/core/node/NodeInfo.kt | 3 +- .../node/services/vault/QueryCriteriaUtils.kt | 10 +- .../net/corda/core/schemas/CommonSchema.kt | 4 +- .../net/corda/core/schemas/PersistentTypes.kt | 3 +- .../SerializationCustomSerializer.kt | 4 +- .../ContractUpgradeTransactions.kt | 8 +- .../core/transactions/WireTransaction.kt | 2 +- .../net/corda/core/utilities/EncodingUtils.kt | 2 - .../net/corda/core/utilities/KotlinUtils.kt | 6 +- .../corda/core/utilities/ProgressTracker.kt | 4 +- .../corda/core/utilities/UntrustworthyData.kt | 5 +- .../net/corda/core/utilities/UuidGenerator.kt | 2 +- .../net/corda/core/flows/FlowsInJavaTest.java | 4 +- .../corda/core/contracts/StructuresTests.kt | 2 - .../net/corda/core/crypto/EdDSATests.kt | 6 +- .../core/crypto/X509NameConstraintsTest.kt | 1 - .../net/corda/core/flows/AttachmentTests.kt | 3 +- .../core/flows/CollectSignaturesFlowTests.kt | 13 +- .../core/identity/PartyAndCertificateTest.kt | 2 +- .../net/corda/core/identity/PartyTest.kt | 2 +- .../core/internal/AbstractAttachmentTest.kt | 1 - .../core/internal/LegalNameValidatorTest.kt | 4 +- .../net/corda/core/node/VaultUpdateTests.kt | 10 +- .../AttachmentSerializationTest.kt | 1 + .../TransactionSerializationTests.kt | 2 +- .../CompatibleTransactionTests.kt | 29 ++--- .../TransactionEncumbranceTests.kt | 2 +- .../java/net/corda/docs/FlowCookbookJava.java | 2 +- .../tutorial/contract/CommercialPaper.java | 2 +- .../kotlin/net/corda/docs/CustomVaultQuery.kt | 3 +- .../docs/WorkflowTransactionBuildTutorial.kt | 2 +- .../tutorial/helloworld/templateContract.kt | 2 +- .../mocknetwork/TutorialMockNetwork.kt | 24 ++-- .../corda/docs/tutorial/twoparty/contract.kt | 2 +- .../net/corda/docs/tutorial/twoparty/flow.kt | 16 +-- .../net/corda/docs/CustomVaultQueryTest.kt | 5 +- .../docs/FxTransactionBuildTutorialTest.kt | 11 +- .../docs/tutorial/testdsl/TutorialTestDSL.kt | 8 +- .../database/DatabaseConfigurationTemplate.kt | 1 - .../behave/database/DatabaseConnection.kt | 4 +- .../corda/behave/database/DatabaseSettings.kt | 1 - .../net/corda/behave/database/DatabaseType.kt | 2 - .../configuration/H2ConfigurationTemplate.kt | 1 - .../kotlin/net/corda/behave/file/LogSource.kt | 3 +- .../behave/monitoring/ConjunctiveWatch.kt | 3 +- .../behave/monitoring/DisjunctiveWatch.kt | 4 +- .../net/corda/behave/monitoring/Watch.kt | 1 + .../net/corda/behave/network/Network.kt | 4 +- .../net/corda/behave/node/Distribution.kt | 2 +- .../node/configuration/Configuration.kt | 1 - .../configuration/ConfigurationTemplate.kt | 1 - .../configuration/CordappConfiguration.kt | 1 - .../configuration/CurrencyConfiguration.kt | 1 - .../configuration/DatabaseConfiguration.kt | 1 - .../node/configuration/NetworkInterface.kt | 3 - .../node/configuration/NotaryConfiguration.kt | 1 - .../behave/node/configuration/NotaryType.kt | 1 - .../node/configuration/UserConfiguration.kt | 1 - .../net/corda/behave/process/Command.kt | 8 +- .../net/corda/behave/process/JarCommand.kt | 12 +- .../behave/process/output/OutputListener.kt | 1 - .../net/corda/behave/service/Service.kt | 3 +- .../behave/service/database/H2Service.kt | 8 +- .../service/database/PostgreSQLService.kt | 11 +- .../corda/behave/ssh/MonitoringSSHClient.kt | 5 +- .../behave/src/scenario/kotlin/Scenarios.kt | 4 +- .../corda/behave/scenarios/ScenarioRunner.kt | 29 ++--- .../corda/behave/scenarios/ScenarioState.kt | 5 +- .../corda/behave/scenarios/StepsContainer.kt | 2 +- .../corda/behave/scenarios/helpers/Cash.kt | 7 +- .../behave/scenarios/helpers/Database.kt | 1 - .../net/corda/behave/scenarios/helpers/Ssh.kt | 1 - .../scenarios/steps/ConfigurationSteps.kt | 1 - .../behave/monitoring/MonitoringTests.kt | 1 - .../net/corda/behave/network/NetworkTests.kt | 1 - .../behave/service/PostreSQLServiceTests.kt | 1 - .../net/corda/blobinspector/BlobInspector.kt | 28 +++-- .../net/corda/blobinspector/BlobLoader.kt | 6 +- .../blobinspector/IndentingStringBuilder.kt | 7 +- .../kotlin/net/corda/blobinspector/Main.kt | 10 +- .../net/corda/blobinspector/FileParseTests.kt | 23 ++-- .../net/corda/blobinspector/ModeParse.kt | 32 +++-- .../corda/blobinspector/SimplifyClassTests.kt | 4 +- .../kotlin/net/corda/kryohook/KryoHook.kt | 12 +- .../quasarhook/QuasarInstrumentationHook.kt | 16 +-- .../net/corda/sandbox/CandidacyStatus.java | 8 +- .../sandbox/SandboxAwareClassWriter.java | 3 +- .../main/java/net/corda/sandbox/Utils.java | 6 +- .../corda/sandbox/WhitelistClassLoader.java | 6 +- .../sandbox/costing/RuntimeCostAccounter.java | 28 +---- .../corda/sandbox/tools/SandboxCreator.java | 2 +- .../corda/sandbox/CandidateMethodTest.java | 4 +- .../java/net/corda/sandbox/Constants.java | 14 +-- .../java/net/corda/sandbox/TestUtils.java | 21 ++-- .../sandbox/WhitelistClassLoaderTest.java | 2 - .../costing/SandboxedRewritingTest.java | 2 +- .../finance/contracts/universal/Literal.kt | 2 +- .../contracts/universal/Perceivable.kt | 4 +- .../contracts/universal/PrettyPrint.kt | 2 +- .../contracts/universal/UniversalContract.kt | 16 +-- .../corda/finance/contracts/universal/Util.kt | 6 +- .../finance/contracts/universal/Caplet.kt | 4 +- .../contracts/universal/ContractDefinition.kt | 7 -- .../finance/contracts/universal/FXSwap.kt | 2 +- .../contracts/universal/RollOutTests.kt | 4 +- .../finance/contracts/universal/Swaption.kt | 7 +- .../contracts/universal/ZeroCouponBond.kt | 10 +- .../contracts/JavaCommercialPaper.java | 2 +- .../finance/contracts/CommercialPaper.kt | 2 +- .../corda/finance/contracts/FinanceTypes.kt | 3 +- .../corda/finance/contracts/GetBalances.kt | 2 +- .../net/corda/finance/contracts/asset/Cash.kt | 4 +- .../contracts/asset/CommodityContract.kt | 2 +- .../finance/contracts/asset/Obligation.kt | 58 ++++++--- .../finance/contracts/asset/OnLedgerAsset.kt | 36 +++--- .../cash/selection/AbstractCashSelection.kt | 10 +- .../selection/CashSelectionPostgreSQLImpl.kt | 2 +- .../finance/contracts/math/Interpolators.kt | 2 +- .../corda/finance/flows/CashConfigDataFlow.kt | 3 +- .../net/corda/finance/flows/CashExitFlow.kt | 7 +- .../finance/flows/CashIssueAndPaymentFlow.kt | 2 +- .../net/corda/finance/flows/CashIssueFlow.kt | 3 - .../corda/finance/flows/CashPaymentFlow.kt | 4 - .../finance/plugin/FinanceJSONSupport.kt | 2 +- .../finance/utils/StateSummingUtilities.kt | 9 +- .../contracts/asset/DummyFungibleContract.kt | 4 +- .../contracts/asset/ObligationTests.kt | 8 +- .../contracts/math/InterpolatorsTest.kt | 6 +- .../corda/finance/flows/CashIssueFlowTests.kt | 2 +- .../finance/schemas/SampleCashSchemaV2.kt | 2 +- .../net/corda/nodeapi/ArtemisTcpTransport.kt | 2 +- .../main/kotlin/net/corda/nodeapi/RPCApi.kt | 32 ++--- .../internal/ArtemisMessagingComponent.kt | 2 - .../corda/nodeapi/internal/SignedNodeInfo.kt | 1 + .../internal/bridging/AMQPBridgeManager.kt | 2 +- .../net/corda/nodeapi/internal/config/User.kt | 2 +- .../nodeapi/internal/network/NetworkMap.kt | 2 +- .../internal/persistence/CordaPersistence.kt | 11 +- .../persistence/HibernateConfiguration.kt | 2 +- .../engine/ConnectionStateMachine.kt | 1 + .../protonwrapper/netty/AMQPServer.kt | 3 +- .../serialization/ByteBufferStreams.kt | 7 +- .../SerializeAsTokenContextImpl.kt | 2 +- .../amqp/AMQPPrimitiveSerializer.kt | 2 +- .../amqp/AMQPSerializationScheme.kt | 1 + .../amqp/AMQPSerializerFactories.kt | 1 + .../serialization/amqp/AMQPStreams.kt | 1 + .../serialization/amqp/ArraySerializer.kt | 4 +- .../amqp/CollectionSerializer.kt | 6 +- .../amqp/CorDappCustomSerializer.kt | 2 +- .../serialization/amqp/CustomSerializer.kt | 4 +- .../amqp/DeserializationInput.kt | 30 +---- .../amqp/DeserializedParameterizedType.kt | 10 +- .../serialization/amqp/EvolutionSerializer.kt | 2 +- .../serialization/amqp/FingerPrinter.kt | 2 +- .../serialization/amqp/ObjectSerializer.kt | 6 +- .../serialization/amqp/PropertySerializers.kt | 2 +- .../serialization/amqp/SerializationOutput.kt | 6 +- .../serialization/amqp/SerializerFactory.kt | 3 +- .../serialization/amqp/SingletonSerializer.kt | 2 +- .../serialization/amqp/TransformsSchema.kt | 12 +- .../amqp/custom/ZonedDateTimeSerializer.kt | 3 +- .../carpenter/AMQPSchemaExtensions.kt | 4 +- .../kryo/CordaClosureSerializer.kt | 4 +- .../kryo/DefaultKryoCustomizer.kt | 2 + .../serialization/kryo/KryoStreams.kt | 1 + .../ForbiddenLambdaSerializationTests.java | 4 +- .../LambdaCheckpointSerializationTest.java | 2 +- .../serialization/amqp/ErrorMessageTests.java | 1 - .../amqp/JavaNestedClassesTests.java | 1 - .../amqp/JavaSerializationOutputTests.java | 5 - .../testutils/TestSerializationContext.java | 2 +- ...tachmentsClassLoaderStaticContractTests.kt | 2 +- .../internal/AttachmentsClassLoaderTests.kt | 21 +++- .../nodeapi/internal/SignedNodeInfoTest.kt | 1 - .../internal/config/ConfigParsingTest.kt | 26 ++-- .../network/NodeInfoFilesCopierTest.kt | 3 +- .../serialization/MapsSerializationTest.kt | 2 +- .../PrivateKeySerializationTest.kt | 3 +- .../amqp/EnumEvolvabilityTests.kt | 1 + .../serialization/amqp/ErrorMessagesTests.kt | 2 +- .../amqp/FingerPrinterTesting.kt | 18 +-- .../amqp/OverridePKSerializerTest.kt | 2 +- .../serialization/amqp/RoundTripTests.kt | 25 ++-- .../amqp/SerializationOutputTests.kt | 63 ++++++++-- .../amqp/SerializationSchemaTests.kt | 17 +-- ...ticInitialisationOfSerializedObjectTest.kt | 4 +- .../carpenter/CarpenterExceptionTests.kt | 14 +-- .../carpenter/ClassCarpenterTestUtils.kt | 2 +- .../carpenter/ClassCarpenterWhitelistTest.kt | 3 +- ...berCompositeSchemaToClassCarpenterTests.kt | 1 - .../kotlin/net/corda/node/AuthDBTests.kt | 19 ++- .../kotlin/net/corda/node/BootTests.kt | 3 +- .../net/corda/node/NodeUnloadHandlerTests.kt | 4 +- .../net/corda/node/amqp/AMQPBridgeTest.kt | 2 - .../events/ScheduledFlowIntegrationTests.kt | 1 - .../net/corda/node/services/rpc/RpcSslTest.kt | 1 - .../statemachine/FlowVersioningTest.kt | 1 - .../statemachine/LargeTransactionsTest.kt | 15 ++- .../services/messaging/P2PMessagingTest.kt | 1 - .../net/corda/node/internal/AbstractNode.kt | 33 ++--- .../corda/node/internal/CordaRPCOpsImpl.kt | 4 +- .../kotlin/net/corda/node/internal/Node.kt | 4 +- .../net/corda/node/internal/NodeStartup.kt | 18 +-- .../node/internal/RpcAuthorisationProxy.kt | 2 + .../internal/RpcExceptionHandlingProxy.kt | 2 + .../artemis/ReactiveArtemisConsumer.kt | 4 +- .../node/internal/cordapp/CordappLoader.kt | 2 +- .../internal/cordapp/CordappProviderImpl.kt | 2 +- .../node/internal/schemas/NodeInfoSchema.kt | 17 ++- .../internal/security/AuthorizingSubject.kt | 5 +- .../internal/security/RPCSecurityManager.kt | 1 - .../security/RPCSecurityManagerImpl.kt | 16 +-- .../corda/node/services/CoreFlowHandlers.kt | 3 +- .../node/services/api/MonitoringService.kt | 1 - .../node/services/config/ConfigUtilities.kt | 5 +- .../node/services/config/NodeConfiguration.kt | 2 +- .../node/services/config/shell/ShellConfig.kt | 1 - .../PersistentScheduledFlowRepository.kt | 8 +- .../net/corda/node/services/keys/KMSUtils.kt | 1 - .../messaging/ArtemisMessagingServer.kt | 4 +- .../node/services/messaging/Messaging.kt | 3 +- .../services/messaging/MessagingExecutor.kt | 9 +- .../services/messaging/P2PMessagingClient.kt | 19 ++- .../node/services/messaging/RPCServer.kt | 4 +- .../services/network/NetworkMapUpdater.kt | 8 +- .../network/PersistentNetworkMapCache.kt | 2 +- .../persistence/AbstractPartyDescriptor.kt | 5 +- ...bstractPartyToX500NameAsStringConverter.kt | 2 +- .../persistence/DBCheckpointStorage.kt | 3 +- .../DBTransactionMappingStorage.kt | 5 +- .../persistence/NodeAttachmentService.kt | 15 +-- .../node/services/rpc/NodeLoginModule.kt | 4 +- .../services/rpc/RpcBrokerConfiguration.kt | 4 +- .../node/services/schema/HibernateObserver.kt | 6 +- .../node/services/schema/NodeSchemaService.kt | 4 +- .../node/services/statemachine/Action.kt | 16 ++- .../statemachine/ActionExecutorImpl.kt | 3 +- .../services/statemachine/CountUpDownLatch.kt | 6 +- .../corda/node/services/statemachine/Event.kt | 16 ++- .../statemachine/FlowLogicRefFactoryImpl.kt | 10 +- .../services/statemachine/FlowMessaging.kt | 2 +- .../services/statemachine/SessionMessage.kt | 2 - .../SingleThreadedStateMachineManager.kt | 6 +- .../statemachine/StateMachineManager.kt | 2 + .../DumpHistoryOnErrorInterceptor.kt | 1 - .../interceptors/MetricInterceptor.kt | 4 +- .../DeliverSessionMessageTransition.kt | 2 +- .../transitions/StartedFlowTransition.kt | 6 +- .../statemachine/transitions/Transition.kt | 1 + .../transitions/TransitionBuilder.kt | 2 - .../transitions/TransitionResult.kt | 8 +- .../services/transactions/BFTSMaRtConfig.kt | 6 +- .../OutOfProcessTransactionVerifierService.kt | 3 +- .../PersistentUniquenessProvider.kt | 2 +- .../transactions/RaftUniquenessProvider.kt | 6 +- .../upgrade/ContractUpgradeServiceImpl.kt | 2 +- .../vault/HibernateQueryCriteriaParser.kt | 38 +++--- .../node/services/vault/NodeVaultService.kt | 2 +- .../corda/node/services/vault/VaultSchema.kt | 8 +- .../net/corda/node/utilities/AddOrRemove.kt | 12 -- .../net/corda/node/utilities/AddressUtils.kt | 2 +- .../corda/node/utilities/AffinityExecutor.kt | 6 +- .../node/utilities/AppendOnlyPersistentMap.kt | 10 +- .../corda/node/utilities/JVMAgentRegistry.kt | 6 +- .../node/utilities/NamedThreadFactory.kt | 3 +- .../node/utilities/NonInvalidatingCache.kt | 2 - .../utilities/NonInvalidatingUnboundCache.kt | 2 +- .../net/corda/node/utilities/ObjectDiffer.kt | 34 ++--- .../HTTPNetworkRegistrationService.kt | 7 +- .../net/corda/node/CordaRPCOpsImplTest.kt | 9 +- .../events/NodeSchedulerServiceTest.kt | 2 +- .../services/network/NetworkMapCacheTest.kt | 4 +- .../services/network/NetworkMapClientTest.kt | 5 +- .../network/NetworkParametersReaderTest.kt | 3 +- .../statemachine/FlowFrameworkTests.kt | 2 +- .../FlowLogicRefFactoryImplTest.kt | 1 - .../vault/VaultQueryExceptionsTests.kt | 3 +- .../node/services/vault/VaultQueryTests.kt | 2 +- .../node/utilities/AffinityExecutorTests.kt | 4 +- .../node/utilities/PersistentMapTests.kt | 8 +- .../attachmentdemo/AttachmentDemoTest.kt | 3 +- .../corda/attachmentdemo/AttachmentDemo.kt | 2 +- .../corda/bank/api/BankOfCordaClientApi.kt | 3 +- .../net/corda/irs/api/NodeInterestRates.kt | 2 +- .../main/kotlin/net/corda/irs/contract/IRS.kt | 41 ++++-- .../net/corda/irs/contract/IRSExport.kt | 4 +- .../kotlin/net/corda/irs/contract/IRSUtils.kt | 1 - .../net/corda/irs/flows/AutoOfferFlow.kt | 1 - .../kotlin/net/corda/irs/flows/FixingFlow.kt | 8 +- .../corda/irs/api/OracleNodeTearOffTests.kt | 7 +- .../kotlin/net/corda/irs/contract/IRSTests.kt | 3 +- .../corda/irs/flows/UpdateBusinessDayFlow.kt | 2 +- .../{ => net/corda/irs}/IRSDemoDockerTest.kt | 17 +-- .../corda/irs/web/IrsDemoWebApplication.kt | 11 +- .../corda/irs/web/api/InterestSwapRestAPI.kt | 4 +- .../irs/web/IrsDemoWebApplicationTests.kt | 12 +- .../corda/irs/web/demo/IrsDemoClientApi.kt | 2 +- .../net/corda/netmap/simulation/Simulation.kt | 3 +- .../net/corda/notarydemo/BFTNotaryCordform.kt | 2 +- .../corda/notarydemo/RaftNotaryCordform.kt | 2 +- .../notarydemo/flows/DummyIssueAndMove.kt | 2 +- .../corda/vega/contracts/PortfolioState.kt | 2 +- .../net/corda/vega/contracts/PortfolioSwap.kt | 1 - .../marketdata/ExampleMarketDataBuilder.java | 8 +- .../MarkitIndexCreditCurveDataParser.java | 18 ++- .../markit/MarkitYieldCurveDataParser.java | 16 +-- .../kotlin/net/corda/vega/analytics/OGStub.kt | 2 +- .../example/OGSwapPricingCcpExample.kt | 1 - .../net/corda/vega/flows/IRSTradeFlow.kt | 1 - .../corda/vega/flows/OpenGammaCordaUtils.kt | 1 - .../net/corda/vega/SimmValuationTest.kt | 2 +- .../net/corda/vega/api/PortfolioApiUtils.kt | 4 +- ...urrencyParameterSensitivitiesSerializer.kt | 2 +- .../CurrencyParameterSensitivitySerialiser.kt | 5 +- .../customserializers/CurrencySerializer.kt | 2 +- .../DoubleArraySerializer.kt | 21 +++- .../MultiCurrencyAmountSerializer.kt | 4 +- .../TenorDateParameterMetadataSerializer.kt | 2 +- .../customserializers/TenorSerializer.kt | 2 +- .../java/net/corda/vega/SwapExampleX.java | 2 - .../net/corda/traderdemo/TraderDemoTest.kt | 1 - .../kotlin/net/corda/traderdemo/TraderDemo.kt | 4 +- .../traderdemo/TransactionGraphSearch.kt | 2 +- .../flow/CommercialPaperIssueFlow.kt | 5 +- .../testing/node/FlowStackSnapshotTest.kt | 18 ++- .../node/MockNetworkIntegrationTests.kt | 1 - .../kotlin/net/corda/testing/driver/Driver.kt | 4 +- .../net/corda/testing/driver/DriverDSL.kt | 2 + .../net/corda/testing/node/NodeTestUtils.kt | 13 +- .../testing/node/internal/DriverDSLImpl.kt | 28 +++-- .../node/internal/InternalMockNetwork.kt | 2 +- .../node/internal/InternalTestUtils.kt | 2 - .../testing/node/internal/ProcessUtilities.kt | 2 +- .../corda/testing/node/internal/RPCDriver.kt | 2 +- .../node/internal/performance/Reporter.kt | 23 ++-- .../node/MockNodeFactoryInJavaTest.java | 2 - .../net/corda/smoketesting/NodeConfig.kt | 3 +- .../testing/contracts/DummyContractV2.kt | 9 +- .../kotlin/net/corda/testing/core/Expect.kt | 12 +- .../net/corda/testing/core/TestConstants.kt | 2 - .../kotlin/net/corda/testing/dsl/TestDSL.kt | 3 +- .../testing/internal/FlowStackSnapshot.kt | 2 +- .../testing/internal/InternalTestConstants.kt | 2 +- .../net/corda/testing/internal/LogHelper.kt | 1 - .../internal/MockCordappConfigProvider.kt | 6 +- .../internal/vault/DummyDealContract.kt | 2 +- .../internal/vault/DummyDealStateSchemaV1.kt | 4 +- .../vault/DummyLinearStateSchemaV2.kt | 4 +- .../testing/services/MockAttachmentStorage.kt | 16 +-- .../model/DemoBenchNodeInfoFilesCopier.kt | 8 +- .../net/corda/demobench/model/NodeConfig.kt | 2 +- .../demobench/plugin/CordappController.kt | 11 +- .../demobench/pty/PtyProcessTtyConnector.kt | 1 - .../kotlin/net/corda/demobench/pty/R3Pty.kt | 1 - .../net/corda/demobench/pty/ZeroFilter.kt | 2 - .../kotlin/net/corda/demobench/rpc/NodeRPC.kt | 1 - .../net/corda/demobench/ui/CloseableTab.kt | 1 - .../net/corda/demobench/ui/PropertyLabel.kt | 1 - .../net/corda/demobench/web/DBViewer.kt | 1 - .../org/h2/server/web/LocalWebServer.kt | 3 +- .../net/corda/demobench/LoggingTestSuite.kt | 1 - .../main/kotlin/net/corda/explorer/Main.kt | 6 +- .../corda/explorer/formatters/Formatter.kt | 1 - .../explorer/identicon/IdenticonRenderer.kt | 10 +- .../explorer/model/ReportingCurrencyModel.kt | 7 +- .../corda/explorer/ui/TableViewUtilities.kt | 3 +- .../explorer/ui/TreeTableViewUtilities.kt | 1 - .../net/corda/explorer/views/Dashboard.kt | 1 - .../net/corda/explorer/views/GuiUtilities.kt | 3 +- .../net/corda/explorer/views/Network.kt | 2 +- .../net/corda/explorer/views/SearchField.kt | 2 +- .../net/corda/explorer/views/Settings.kt | 1 - .../net/corda/loadtest/ConnectionManager.kt | 6 +- .../kotlin/net/corda/loadtest/Disruption.kt | 3 +- .../kotlin/net/corda/loadtest/LoadTest.kt | 6 +- .../net/corda/loadtest/tests/CrossCashTest.kt | 48 +++---- .../net/corda/loadtest/tests/SelfIssueTest.kt | 4 +- .../corda/tools/shell/RunShellCommand.java | 7 +- .../tools/shell/CordaAuthenticationPlugin.kt | 2 +- .../net/corda/tools/shell/InteractiveShell.kt | 10 +- .../corda/tools/shell/SSHDConfiguration.kt | 2 +- .../net/corda/tools/shell/StandaloneShell.kt | 4 +- .../corda/tools/shell/InteractiveShellTest.kt | 3 +- .../corda/webserver/WebserverDriverTests.kt | 4 +- .../net/corda/webserver/WebServerConfig.kt | 2 +- .../net/corda/webserver/api/APIServer.kt | 1 - .../corda/webserver/internal/NodeWebServer.kt | 16 ++- .../WebServerPluginRegistry.kt | 3 +- .../webserver/servlets/CorDappInfoServlet.kt | 2 +- .../webserver/servlets/ResponseFilter.kt | 2 - 461 files changed, 1413 insertions(+), 1578 deletions(-) delete mode 100644 node/src/main/kotlin/net/corda/node/utilities/AddOrRemove.kt rename samples/irs-demo/src/system-test/kotlin/{ => net/corda/irs}/IRSDemoDockerTest.kt (85%) rename webserver/src/main/kotlin/net/corda/webserver/{service => services}/WebServerPluginRegistry.kt (95%) diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 505f1ef7a7..e409e551c9 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -4,82 +4,28 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -87,68 +33,15 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -158,23 +51,11 @@ - - - - - - - - - - - - diff --git a/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt b/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt index 04294c4043..23dd98f274 100644 --- a/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt +++ b/client/jackson/src/main/kotlin/net/corda/client/jackson/JacksonSupport.kt @@ -330,14 +330,14 @@ object JacksonSupport { mapper.wellKnownPartyFromX500Name(principal) ?: throw JsonParseException(parser, "Could not find a Party with name $principal") } else { val nameMatches = mapper.partiesFromName(parser.text) - if (nameMatches.isEmpty()) { - val publicKey = parser.readValueAs() - mapper.partyFromKey(publicKey) - ?: throw JsonParseException(parser, "Could not find a Party with key ${publicKey.toStringShort()}") - } else if (nameMatches.size == 1) { - nameMatches.first() - } else { - throw JsonParseException(parser, "Ambiguous name match '${parser.text}': could be any of " + + when { + nameMatches.isEmpty() -> { + val publicKey = parser.readValueAs() + mapper.partyFromKey(publicKey) + ?: throw JsonParseException(parser, "Could not find a Party with key ${publicKey.toStringShort()}") + } + nameMatches.size == 1 -> nameMatches.first() + else -> throw JsonParseException(parser, "Ambiguous name match '${parser.text}': could be any of " + nameMatches.map { it.name }.joinToString(" ... or ... ")) } } diff --git a/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt b/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt index 5ff3c3b08e..80c0ff9ac9 100644 --- a/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt +++ b/client/jackson/src/main/kotlin/net/corda/client/jackson/StringToMethodCallParser.kt @@ -220,7 +220,7 @@ open class StringToMethodCallParser @JvmOverloads constructor( val paramNames = methodParamNames[name]!! val typeNames = args.parameters.map { it.type.simpleName } val paramTypes = paramNames.zip(typeNames) - paramTypes.map { "${it.first}: ${it.second}" }.joinToString(", ") + paramTypes.joinToString(", ") { "${it.first}: ${it.second}" } } Pair(name, argStr) }.toMap() diff --git a/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt b/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt index a93052a48e..3eb9ef1042 100644 --- a/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt +++ b/client/jackson/src/test/kotlin/net/corda/client/jackson/StringToMethodCallParserTest.kt @@ -3,7 +3,6 @@ package net.corda.client.jackson import net.corda.core.crypto.SecureHash import org.junit.Assert.assertArrayEquals import org.junit.Test -import kotlin.reflect.full.primaryConstructor import kotlin.test.assertEquals class StringToMethodCallParserTest { diff --git a/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt b/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt index 5da68b3af4..ab405af19b 100644 --- a/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt +++ b/client/jfx/src/integration-test/kotlin/net/corda/client/jfx/NodeMonitorModelTest.kt @@ -100,13 +100,13 @@ class NodeMonitorModelTest { sequence( // TODO : Add test for remove when driver DSL support individual node shutdown. expect { output: NetworkMapCache.MapChange -> - require(output.node.legalIdentities.any { it.name == ALICE_NAME }) { "Expecting : ${ALICE_NAME}, Actual : ${output.node.legalIdentities.map(Party::name)}" } + require(output.node.legalIdentities.any { it.name == ALICE_NAME }) { "Expecting : $ALICE_NAME, Actual : ${output.node.legalIdentities.map(Party::name)}" } }, expect { output: NetworkMapCache.MapChange -> - require(output.node.legalIdentities.any { it.name == BOB_NAME }) { "Expecting : ${BOB_NAME}, Actual : ${output.node.legalIdentities.map(Party::name)}" } + require(output.node.legalIdentities.any { it.name == BOB_NAME }) { "Expecting : $BOB_NAME, Actual : ${output.node.legalIdentities.map(Party::name)}" } }, expect { output: NetworkMapCache.MapChange -> - require(output.node.legalIdentities.any { it.name == CHARLIE_NAME }) { "Expecting : ${CHARLIE_NAME}, Actual : ${output.node.legalIdentities.map(Party::name)}" } + require(output.node.legalIdentities.any { it.name == CHARLIE_NAME }) { "Expecting : $CHARLIE_NAME, Actual : ${output.node.legalIdentities.map(Party::name)}" } } ) } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt index a8a0d04109..e31a37c862 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ContractStateModel.kt @@ -29,24 +29,23 @@ class ContractStateModel { private val cashStatesDiff: Observable> = contractStatesDiff.map { Diff(it.added.filterCashStateAndRefs(), it.removed.filterCashStateAndRefs()) } - val cashStates: ObservableList> = cashStatesDiff.fold(FXCollections.observableArrayList()) { list: MutableList>, statesDiff -> - list.removeIf { it in statesDiff.removed } - list.addAll(statesDiff.added) + val cashStates: ObservableList> = cashStatesDiff.fold(FXCollections.observableArrayList()) { list: MutableList>, (added, removed) -> + list.removeIf { it in removed } + list.addAll(added) }.distinctBy { it.ref } val cash = cashStates.map { it.state.data.amount } companion object { private fun Collection>.filterCashStateAndRefs(): List> { - return this.map { stateAndRef -> + return this.mapNotNull { stateAndRef -> if (stateAndRef.state.data is Cash.State) { // Kotlin doesn't unify here for some reason uncheckedCast, StateAndRef>(stateAndRef) } else { null } - }.filterNotNull() + } } } - } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt index feb3548ed2..420e53fa6a 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/Models.kt @@ -1,15 +1,6 @@ package net.corda.client.jfx.model -import javafx.beans.property.ObjectProperty -import javafx.beans.value.ObservableValue -import javafx.beans.value.WritableValue -import javafx.collections.ObservableList import net.corda.core.internal.uncheckedCast -import org.reactfx.EventSink -import org.reactfx.EventStream -import rx.Observable -import rx.Observer -import rx.subjects.Subject import java.util.* import kotlin.reflect.KClass @@ -74,7 +65,7 @@ object Models { fun initModel(klass: KClass) = modelStore.getOrPut(klass) { klass.java.newInstance() } fun get(klass: KClass, origin: KClass<*>): M { - dependencyGraph.getOrPut(origin) { mutableSetOf>() }.add(klass) + dependencyGraph.getOrPut(origin) { mutableSetOf() }.add(klass) val model = initModel(klass) if (model.javaClass != klass.java) { throw IllegalStateException("Model stored as ${klass.qualifiedName} has type ${model.javaClass}") diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt index 868849d56b..9655f8b083 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/ModelsUtils.kt @@ -11,7 +11,6 @@ import org.reactfx.EventStream import rx.Observable import rx.Observer import rx.subjects.Subject -import kotlin.reflect.KClass inline fun observable(noinline observableProperty: (M) -> Observable) = TrackedDelegate.ObservableDelegate(M::class, observableProperty) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt index a4b8e334ed..610e5129f8 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/NetworkIdentityModel.kt @@ -22,7 +22,7 @@ class NetworkIdentityModel { else -> false } } - if(update is MapChange.Modified || update is MapChange.Added){ + if (update is MapChange.Modified || update is MapChange.Added) { list.addAll(update.node) } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt index f6c8f5f479..e5aeaa30cf 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/model/TransactionDataModel.kt @@ -85,8 +85,8 @@ class TransactionDataModel { private val transactions by observable(NodeMonitorModel::transactions) private val collectedTransactions = transactions.recordInSequence().distinctBy { it.id } private val vaultUpdates by observable(NodeMonitorModel::vaultUpdates) - private val stateMap = vaultUpdates.fold(FXCollections.observableHashMap>()) { map, update -> - val states = update.consumed + update.produced + private val stateMap = vaultUpdates.fold(FXCollections.observableHashMap>()) { map, (consumed, produced) -> + val states = consumed + produced states.forEach { map[it.ref] = it } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt index 820d9102b7..e468fb3950 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AggregatedList.kt @@ -70,21 +70,25 @@ class AggregatedList( override fun sourceChanged(c: ListChangeListener.Change) { beginChange() while (c.next()) { - if (c.wasPermutated()) { - // Permutation should not change aggregation - } else if (c.wasUpdated()) { - // Update should not change aggregation - } else { - for (removedSourceItem in c.removed) { - val removedPair = removeItem(removedSourceItem) - if (removedPair != null) { - nextRemove(removedPair.first, removedPair.second.value) - } + when { + c.wasPermutated() -> { + // Permutation should not change aggregation } - for (addedItem in c.addedSubList) { - val insertIndex = addItem(addedItem) - if (insertIndex != null) { - nextAdd(insertIndex, insertIndex + 1) + c.wasUpdated() -> { + // Update should not change aggregation + } + else -> { + for (removedSourceItem in c.removed) { + val removedPair = removeItem(removedSourceItem) + if (removedPair != null) { + nextRemove(removedPair.first, removedPair.second.value) + } + } + for (addedItem in c.addedSubList) { + val insertIndex = addItem(addedItem) + if (insertIndex != null) { + nextAdd(insertIndex, insertIndex + 1) + } } } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt index 49e76e227a..4d3ef8fa5f 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AmountBindings.kt @@ -6,6 +6,7 @@ import javafx.collections.ObservableList import net.corda.client.jfx.model.ExchangeRate import net.corda.core.contracts.Amount import org.fxmisc.easybind.EasyBind +import org.fxmisc.easybind.monadic.MonadicBinding import java.util.* import java.util.stream.Collectors @@ -13,7 +14,7 @@ import java.util.stream.Collectors * Utility bindings for the [Amount] type, similar in spirit to [Bindings] */ object AmountBindings { - fun sum(amounts: ObservableList>, token: T) = EasyBind.map( + fun sum(amounts: ObservableList>, token: T): MonadicBinding> = EasyBind.map( Bindings.createLongBinding({ amounts.stream().collect(Collectors.summingLong { require(it.token == token) diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt index 6bac0fcb47..0c4c05e1cf 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/AssociatedList.kt @@ -21,35 +21,39 @@ class AssociatedList( init { sourceList.forEach { val key = toKey(it) - backingMap.set(key, Pair(assemble(key, it), Unit)) + backingMap[key] = Pair(assemble(key, it), Unit) } sourceList.addListener { change: ListChangeListener.Change -> while (change.next()) { - if (change.wasPermutated()) { - } else if (change.wasUpdated()) { - } else { - val removedSourceMap = change.removed.associateBy(toKey) - val addedSourceMap = change.addedSubList.associateBy(toKey) - val removedMap = HashMap() - val addedMap = HashMap() - removedSourceMap.forEach { - val removed = backingMap.remove(it.key)?.first - removed ?: throw IllegalStateException("Removed list does not associate") - removedMap.put(it.key, removed) + when { + change.wasPermutated() -> { } - addedSourceMap.forEach { - val oldValue = backingMap.get(it.key) - val newValue = if (oldValue == null) { - assemble(it.key, it.value) - } else { - throw IllegalStateException("Several elements associated with same key") + change.wasUpdated() -> { + } + else -> { + val removedSourceMap = change.removed.associateBy(toKey) + val addedSourceMap = change.addedSubList.associateBy(toKey) + val removedMap = HashMap() + val addedMap = HashMap() + removedSourceMap.forEach { + val removed = backingMap.remove(it.key)?.first + removed ?: throw IllegalStateException("Removed list does not associate") + removedMap.put(it.key, removed) + } + addedSourceMap.forEach { + val oldValue = backingMap.get(it.key) + val newValue = if (oldValue == null) { + assemble(it.key, it.value) + } else { + throw IllegalStateException("Several elements associated with same key") + } + backingMap.put(it.key, Pair(newValue, Unit)) + addedMap.put(it.key, newValue) + } + val keys = removedMap.keys + addedMap.keys + keys.forEach { key -> + fireChange(createMapChange(key, removedMap.get(key), addedMap.get(key))) } - backingMap.put(it.key, Pair(newValue, Unit)) - addedMap.put(it.key, newValue) - } - val keys = removedMap.keys + addedMap.keys - keys.forEach { key -> - fireChange(createMapChange(key, removedMap.get(key), addedMap.get(key))) } } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt index 321f751c3e..e3a3b58726 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ChosenList.kt @@ -27,9 +27,7 @@ class ChosenList( private var currentList = chosenListObservable.value - private val listener = object : ListChangeListener { - override fun onChanged(change: ListChangeListener.Change) = fireChange(change) - } + private val listener = ListChangeListener { change -> fireChange(change) } init { chosenListObservable.addListener { _: Observable -> rechoose() } @@ -39,7 +37,7 @@ class ChosenList( endChange() } - override fun get(index: Int) = currentList.get(index) + override fun get(index: Int): E = currentList[index] override val size: Int get() = currentList.size private fun rechoose() { diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt index 58b602b834..d36e96583f 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ConcatenatedList.kt @@ -52,10 +52,10 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans } private fun startingOffsetOf(listIndex: Int): Int { - if (listIndex == 0) { - return 0 + return if (listIndex == 0) { + 0 } else { - return nestedIndexOffsets[listIndex - 1] + nestedIndexOffsets[listIndex - 1] } } @@ -74,11 +74,11 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans // firstTouched is the result list index of the beginning of the permutation. val firstTouched = startingOffset + change.from // We first set the non-permuted indices. - for (i in 0..firstTouched - 1) { + for (i in 0 until firstTouched) { permutation[i] = i } // Then the permuted ones. - for (i in firstTouched..startingOffset + change.to - 1) { + for (i in firstTouched until startingOffset + change.to) { permutation[startingOffset + i] = change.getPermutation(i) } nextPermutation(firstTouched, startingOffset + change.to, permutation) @@ -87,7 +87,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans // by the startingOffsetOf the nested list. val listIndex = indexMap[wrapped]!!.first val startingOffset = startingOffsetOf(listIndex) - for (i in change.from..change.to - 1) { + for (i in change.from until change.to) { nextUpdate(startingOffset + i) } } else { @@ -144,7 +144,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans val newSubNestedIndexOffsets = IntArray(change.to - change.from) val firstTouched = if (change.from == 0) 0 else nestedIndexOffsets[change.from - 1] var currentOffset = firstTouched - for (i in 0..change.to - change.from - 1) { + for (i in 0 until change.to - change.from) { currentOffset += source[change.from + i].size newSubNestedIndexOffsets[i] = currentOffset } @@ -152,24 +152,24 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans val concatenatedPermutation = IntArray(newSubNestedIndexOffsets.last()) // Set the non-permuted part var offset = 0 - for (i in 0..change.from - 1) { + for (i in 0 until change.from) { val nestedList = source[i] - for (j in offset..offset + nestedList.size - 1) { + for (j in offset until offset + nestedList.size) { concatenatedPermutation[j] = j } offset += nestedList.size } // Now the permuted part - for (i in 0..newSubNestedIndexOffsets.size - 1) { + for (i in 0 until newSubNestedIndexOffsets.size) { val startingOffset = startingOffsetOf(change.from + i) val permutedListIndex = change.getPermutation(change.from + i) val permutedOffset = (if (permutedListIndex == 0) 0 else newSubNestedIndexOffsets[permutedListIndex - 1]) - for (j in 0..source[permutedListIndex].size - 1) { + for (j in 0 until source[permutedListIndex].size) { concatenatedPermutation[startingOffset + j] = permutedOffset + j } } // Record permuted offsets - for (i in 0..newSubNestedIndexOffsets.size - 1) { + for (i in 0 until newSubNestedIndexOffsets.size) { nestedIndexOffsets[change.from + i] = newSubNestedIndexOffsets[i] } nextPermutation(firstTouched, newSubNestedIndexOffsets.last(), concatenatedPermutation) @@ -238,7 +238,7 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans if (firstInvalidatedPosition < source.size) { val firstInvalid = firstInvalidatedPosition var offset = if (firstInvalid == 0) 0 else nestedIndexOffsets[firstInvalid - 1] - for (i in firstInvalid..source.size - 1) { + for (i in firstInvalid until source.size) { offset += source[i].size if (i < nestedIndexOffsets.size) { nestedIndexOffsets[i] = offset @@ -256,10 +256,10 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans override val size: Int get() { recalculateOffsets() - if (nestedIndexOffsets.size > 0) { - return nestedIndexOffsets.last() + return if (nestedIndexOffsets.size > 0) { + nestedIndexOffsets.last() } else { - return 0 + 0 } } @@ -273,17 +273,17 @@ class ConcatenatedList(sourceList: ObservableList>) : Trans comparison = { offset -> compareValues(offset, index) } ) - if (listIndex >= 0) { + return if (listIndex >= 0) { var nonEmptyListIndex = listIndex + 1 while (source[nonEmptyListIndex].isEmpty()) { nonEmptyListIndex++ } - return source[nonEmptyListIndex][0] + source[nonEmptyListIndex][0] } else { // The element is in the range of this list val rangeListIndex = -listIndex - 1 val subListOffset = index - startingOffsetOf(rangeListIndex) - return source[rangeListIndex][subListOffset] + source[rangeListIndex][subListOffset] } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt index 3b349ce67d..21e8b2a5c3 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/FlattenedList.kt @@ -55,7 +55,7 @@ class FlattenedList(val sourceList: ObservableList val from = c.from val to = c.to val permutation = IntArray(to, { c.getPermutation(it) }) - indexMap.replaceAll { _, pair -> Pair(permutation[pair.first], pair.second) } + indexMap.replaceAll { _, (first, second) -> Pair(permutation[first], second) } nextPermutation(from, to, permutation) } else if (c.wasUpdated()) { throw UnsupportedOperationException("FlattenedList doesn't support Update changes") @@ -109,7 +109,7 @@ class FlattenedList(val sourceList: ObservableList assert(sourceList.size == indexMap.size) } - override fun get(index: Int) = sourceList.get(index).value + override fun get(index: Int): A = sourceList[index].value override fun getSourceIndex(index: Int) = index diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt index 3a2be71518..fbddd44024 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/LeftOuterJoinedMap.kt @@ -16,8 +16,8 @@ class LeftOuterJoinedMap( ) : ReadOnlyBackedObservableMapBase>() { init { leftTable.forEach { entry -> - val rightValueProperty = SimpleObjectProperty(rightTable.get(entry.key)) - backingMap.set(entry.key, Pair(assemble(entry.key, entry.value, rightValueProperty), rightValueProperty)) + val rightValueProperty = SimpleObjectProperty(rightTable[entry.key]) + backingMap[entry.key] = Pair(assemble(entry.key, entry.value, rightValueProperty), rightValueProperty) } leftTable.addListener { change: MapChangeListener.Change -> @@ -29,10 +29,10 @@ class LeftOuterJoinedMap( } if (change.wasAdded()) { - val rightValue = rightTable.get(change.key) + val rightValue = rightTable[change.key] val rightValueProperty = SimpleObjectProperty(rightValue) val newValue = assemble(change.key, change.valueAdded, rightValueProperty) - backingMap.set(change.key, Pair(newValue, rightValueProperty)) + backingMap[change.key] = Pair(newValue, rightValueProperty) addedValue = newValue } @@ -40,11 +40,11 @@ class LeftOuterJoinedMap( } rightTable.addListener { change: MapChangeListener.Change -> if (change.wasRemoved() && !change.wasAdded()) { - backingMap.get(change.key)?.second?.set(null) + backingMap[change.key]?.second?.set(null) } if (change.wasAdded()) { - backingMap.get(change.key)?.second?.set(change.valueAdded) + backingMap[change.key]?.second?.set(change.valueAdded) } } } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt index 3578646ccc..d3ad2399b1 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/MappedList.kt @@ -5,7 +5,6 @@ import javafx.collections.ObservableList import javafx.collections.transformation.TransformationList import java.util.* - /** * This is a variant of [EasyBind.map] where the mapped list is backed, therefore the mapping function will only be run * when an element is inserted or updated. diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt index 455d2b5ee7..dc79117122 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableFold.kt @@ -30,7 +30,7 @@ private fun onError(th: Throwable) { */ fun Observable.foldToObservableValue(initial: B, folderFun: (A, B) -> B): ObservableValue { val result = SimpleObjectProperty(initial) - subscribe ({ + subscribe({ Platform.runLater { result.set(folderFun(it, result.get())) } diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt index 599d825aa2..975d32c7da 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ObservableUtilities.kt @@ -42,10 +42,10 @@ fun ObservableValue.map(function: (A) -> B): ObservableValue = * re-run the function. */ fun ObservableList.map(cached: Boolean = true, function: (A) -> B): ObservableList { - if (cached) { - return MappedList(this, function) + return if (cached) { + MappedList(this, function) } else { - return EasyBind.map(this, function) + EasyBind.map(this, function) } } @@ -120,11 +120,7 @@ fun ObservableList.filter(predicate: ObservableValue<(A) -> Boolean>) */ fun ObservableList.filterNotNull(): ObservableList { //TODO This is a tactical work round for an issue with SAM conversion (https://youtrack.jetbrains.com/issue/ALL-1552) so that the M10 explorer works. - return uncheckedCast(uncheckedCast>(this).filtered(object : Predicate { - override fun test(t: A?): Boolean { - return t != null - } - })) + return uncheckedCast(uncheckedCast>(this).filtered { t -> t != null }) } /** @@ -247,8 +243,8 @@ fun ObservableList.leftOuterJoin( assemble: (A, ObservableList) -> C ): ObservableList { val joinedMap = leftOuterJoin(rightTable, leftToJoinKey, rightToJoinKey) - return joinedMap.getObservableValues().map { pair -> - pair.first.map { assemble(it, pair.second) } + return joinedMap.getObservableValues().map { (first, second) -> + first.map { assemble(it, second) } }.concatenate() } @@ -271,11 +267,9 @@ fun ObservableList.leftOuterJoin( ): ObservableMap, ObservableList>> { val leftTableMap = associateByAggregation(leftToJoinKey) val rightTableMap = rightTable.associateByAggregation(rightToJoinKey) - val joinedMap: ObservableMap, ObservableList>> = - LeftOuterJoinedMap(leftTableMap, rightTableMap) { _, left, rightValue -> - Pair(left, ChosenList(rightValue.map { it ?: FXCollections.emptyObservableList() }, "ChosenList from leftOuterJoin")) - } - return joinedMap + return LeftOuterJoinedMap(leftTableMap, rightTableMap) { _, left, rightValue -> + Pair(left, ChosenList(rightValue.map { it ?: FXCollections.emptyObservableList() }, "ChosenList from leftOuterJoin")) + } } fun ObservableList.getValueAt(index: Int): ObservableValue { diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt index 4ee03afc56..3ab224c0a4 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReadOnlyBackedObservableMapBase.kt @@ -46,7 +46,7 @@ open class ReadOnlyBackedObservableMapBase : ObservableMap { override fun containsValue(value: A) = backingMap.any { it.value.first == value } - override fun get(key: K) = backingMap.get(key)?.first + override fun get(key: K) = backingMap[key]?.first override fun isEmpty() = backingMap.isEmpty() diff --git a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt index 61ca306485..14e17eb979 100644 --- a/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt +++ b/client/jfx/src/main/kotlin/net/corda/client/jfx/utils/ReplayedList.kt @@ -33,14 +33,14 @@ class ReplayedList(sourceList: ObservableList) : TransformationList( } nextPermutation(from, to, permutation) } else if (c.wasUpdated()) { - for (i in c.from..c.to - 1) { + for (i in c.from until c.to) { replayedList[i] = c.list[i] nextUpdate(i) } } else { if (c.wasRemoved()) { val removePosition = c.from - for (i in 0..c.removedSize - 1) { + for (i in 0 until c.removedSize) { replayedList.removeAt(removePosition) } nextRemove(c.from, c.removed) @@ -48,7 +48,7 @@ class ReplayedList(sourceList: ObservableList) : TransformationList( if (c.wasAdded()) { val addStart = c.from val addEnd = c.to - for (i in addStart..addEnd - 1) { + for (i in addStart until addEnd) { replayedList.add(i, c.list[i]) } nextAdd(addStart, addEnd) diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt index 6b1a1a9ae2..9a31851248 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/model/ExchangeRateModelTest.kt @@ -19,9 +19,10 @@ class ExchangeRateModelTest { private fun assertEquals(one: Amount, another: Amount) { assertEquals(one.token, another.token) - assertTrue("$one != $another", {(one.toDecimal() - another.toDecimal()).abs() < BigDecimal(0.01) }) + assertTrue("$one != $another", { (one.toDecimal() - another.toDecimal()).abs() < BigDecimal(0.01) }) } } + @Test fun `perform fx testing`() { val tenSwissies = Amount(10, BigDecimal.ONE, CHF) diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt index b04817f62d..ec7ab0e7a8 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/AggregatedListTest.kt @@ -9,9 +9,9 @@ import kotlin.test.fail class AggregatedListTest { - lateinit var sourceList: ObservableList - lateinit var aggregatedList: ObservableList>> - lateinit var replayedList: ObservableList>> + private lateinit var sourceList: ObservableList + private lateinit var aggregatedList: ObservableList>> + private lateinit var replayedList: ObservableList>> @Before fun setup() { diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt index effbed01a7..3b69bea90d 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ConcatenatedListTest.kt @@ -24,14 +24,13 @@ class ConcatenatedListTest { fun ConcatenatedList.checkInvariants() { assertEquals(nestedIndexOffsets.size, source.size) var currentOffset = 0 - for (i in 0..source.size - 1) { + for (i in 0 until source.size) { currentOffset += source[i].size assertEquals(nestedIndexOffsets[i], currentOffset) } assertEquals(indexMap.size, source.size) - for (entry in indexMap) { - val (wrapped, pair) = entry + for ((wrapped, pair) in indexMap) { val index = pair.first val foundListIndices = ArrayList() source.forEachIndexed { i, list -> @@ -124,11 +123,7 @@ class ConcatenatedListTest { assertEquals(replayedList[2], "b") assertEquals(replayedList[3], "c") - sourceList.sortWith(object : Comparator> { - override fun compare(p0: ObservableList, p1: ObservableList): Int { - return p0.size - p1.size - } - }) + sourceList.sortWith(Comparator> { p0, p1 -> p0.size - p1.size }) concatenatedList.checkInvariants() assertEquals(replayedList.size, 4) assertEquals(replayedList[0], "hello") @@ -137,11 +132,7 @@ class ConcatenatedListTest { assertEquals(replayedList[3], "b") sourceList.add(0, FXCollections.observableArrayList("d", "e", "f")) - sourceList.sortWith(object : Comparator> { - override fun compare(p0: ObservableList, p1: ObservableList): Int { - return p0.size - p1.size - } - }) + sourceList.sortWith(Comparator> { p0, p1 -> p0.size - p1.size }) concatenatedList.checkInvariants() assertEquals(replayedList.size, 7) assertEquals(replayedList[0], "hello") diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt index be8783ef97..88eedf1cd9 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/MappedListTest.kt @@ -34,7 +34,6 @@ class MappedListTest { assertEquals(replayedList[0], 7) assertEquals(replayedList[1], 5) assertEquals(replayedList[2], 3) - } @Test diff --git a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt index 1b1e69daaa..295362a069 100644 --- a/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt +++ b/client/jfx/src/test/kotlin/net/corda/client/jfx/utils/ReplayedMap.kt @@ -10,14 +10,14 @@ import kotlin.test.assertEquals class ReplayedMap(sourceMap: ObservableMap) : ReadOnlyBackedObservableMapBase() { init { sourceMap.forEach { - backingMap.set(it.key, Pair(it.value, Unit)) + backingMap[it.key] = Pair(it.value, Unit) } sourceMap.addListener { change: MapChangeListener.Change -> if (change.wasRemoved()) { assertEquals(backingMap.remove(change.key)!!.first, change.valueRemoved) } if (change.wasAdded()) { - backingMap.set(change.key, Pair(change.valueAdded, Unit)) + backingMap[change.key] = Pair(change.valueAdded, Unit) } fireChange(change) } diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt index ab74cb9a4a..635bcb9181 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/CordaRPCClientUtils.kt @@ -29,5 +29,5 @@ fun CordaRPCOps.drainAndShutdown(): Observable { .doOnError { error -> throw error } - .doOnCompleted { shutdown() }.map { } + .doOnCompleted { shutdown() }.map { } } \ No newline at end of file diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt index f26c6a0951..d13116daed 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/RPCClientProxyHandler.kt @@ -1,10 +1,6 @@ package net.corda.client.rpc.internal import co.paralleluniverse.common.util.SameThreadExecutor -import com.esotericsoftware.kryo.Kryo -import com.esotericsoftware.kryo.Serializer -import com.esotericsoftware.kryo.io.Input -import com.esotericsoftware.kryo.io.Output import com.github.benmanes.caffeine.cache.Cache import com.github.benmanes.caffeine.cache.Caffeine import com.github.benmanes.caffeine.cache.RemovalCause @@ -34,18 +30,27 @@ import net.corda.nodeapi.internal.DeduplicationChecker import org.apache.activemq.artemis.api.core.ActiveMQException import org.apache.activemq.artemis.api.core.RoutingType import org.apache.activemq.artemis.api.core.SimpleString -import org.apache.activemq.artemis.api.core.client.* import org.apache.activemq.artemis.api.core.client.ActiveMQClient.DEFAULT_ACK_BATCH_SIZE +import org.apache.activemq.artemis.api.core.client.ClientConsumer +import org.apache.activemq.artemis.api.core.client.ClientMessage +import org.apache.activemq.artemis.api.core.client.ClientProducer +import org.apache.activemq.artemis.api.core.client.ClientSession +import org.apache.activemq.artemis.api.core.client.ClientSessionFactory +import org.apache.activemq.artemis.api.core.client.FailoverEventType +import org.apache.activemq.artemis.api.core.client.ServerLocator import rx.Notification import rx.Observable import rx.subjects.UnicastSubject import java.lang.reflect.InvocationHandler import java.lang.reflect.Method -import java.time.Instant import java.util.* -import java.util.concurrent.* +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.ScheduledExecutorService +import java.util.concurrent.ScheduledFuture +import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import kotlin.reflect.jvm.javaMethod @@ -152,7 +157,7 @@ class RPCClientProxyHandler( private val serializationContextWithObservableContext = RpcClientObservableSerializer.createContext(serializationContext, observableContext) private fun createRpcObservableMap(): RpcObservableMap { - val onObservableRemove = RemovalListener>> { key, value, cause -> + val onObservableRemove = RemovalListener>> { key, _, cause -> val observableId = key!! val rpcCallSite = callSiteMap?.remove(observableId) if (cause == RemovalCause.COLLECTED) { @@ -444,7 +449,7 @@ class RPCClientProxyHandler( log.debug("Trying to connect using ${transport.params}") try { - if (serverLocator != null && !serverLocator.isClosed) { + if (!serverLocator.isClosed) { sessionFactory = serverLocator.createSessionFactory(transport) } else { log.warn("Stopping reconnect attempts.") diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt index 0fa4878018..06ec72e244 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/KryoClientSerializationScheme.kt @@ -45,7 +45,6 @@ class KryoClientSerializationScheme : AbstractKryoSerializationScheme() { }, if (classLoader != null) AMQP_P2P_CONTEXT.withClassLoader(classLoader) else AMQP_P2P_CONTEXT, rpcClientContext = if (classLoader != null) KRYO_RPC_CLIENT_CONTEXT.withClassLoader(classLoader) else KRYO_RPC_CLIENT_CONTEXT) - } } } \ No newline at end of file diff --git a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt index 2a8f6f5283..99749093e2 100644 --- a/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt +++ b/client/rpc/src/main/kotlin/net/corda/client/rpc/internal/serialization/kryo/RpcClientObservableSerializer.kt @@ -57,7 +57,7 @@ object RpcClientObservableSerializer : Serializer>() { }.dematerialize() } - private fun Input.readInvocationId() : Trace.InvocationId? { + private fun Input.readInvocationId(): Trace.InvocationId? { val value = readString() ?: return null val timestamp = readLong() diff --git a/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt b/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt index 6e2adf483e..e898c7b610 100644 --- a/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt +++ b/client/rpc/src/smoke-test/kotlin/net/corda/kotlin/rpc/StandaloneCordaRPClientTest.kt @@ -218,7 +218,7 @@ class StandaloneCordaRPClientTest { flowHandle.returnValue.get() val balance = rpcProxy.getCashBalance(USD) - println("Balance: " + balance) + println("Balance: $balance") assertEquals(629.DOLLARS, balance) } diff --git a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt index 66dd7ae816..cc130604be 100644 --- a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt +++ b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCConcurrencyTests.kt @@ -49,7 +49,7 @@ class RPCConcurrencyTests : AbstractRPCTest() { override fun newLatch(numberOfDowns: Int): Long { val id = random63BitValue() val latch = CountDownLatch(numberOfDowns) - latches.put(id, latch) + latches[id] = latch return id } diff --git a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt index 398e2dc261..fec7adae5d 100644 --- a/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt +++ b/client/rpc/src/test/kotlin/net/corda/client/rpc/RPCFailureTests.kt @@ -58,7 +58,7 @@ class RPCFailureTests { } @Test - fun `unserializable`() = rpc { + fun unserializable() = rpc { assertThatThrownBy { it.getUnserializable() }.isInstanceOf(KryoException::class.java) } diff --git a/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt b/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt index b22ed8b506..72888c27c5 100644 --- a/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt +++ b/client/rpc/src/test/kotlin/net/corda/client/rpc/RepeatingBytesInputStream.kt @@ -6,11 +6,11 @@ class RepeatingBytesInputStream(val bytesToRepeat: ByteArray, val numberOfBytes: private var bytesLeft = numberOfBytes override fun available() = bytesLeft override fun read(): Int { - if (bytesLeft == 0) { - return -1 + return if (bytesLeft == 0) { + -1 } else { bytesLeft-- - return bytesToRepeat[(numberOfBytes - bytesLeft) % bytesToRepeat.size].toInt() + bytesToRepeat[(numberOfBytes - bytesLeft) % bytesToRepeat.size].toInt() } } diff --git a/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt b/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt index 1771c2846f..bac9a523e2 100644 --- a/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt +++ b/confidential-identities/src/main/kotlin/net/corda/confidential/SwapIdentitiesFlow.kt @@ -80,7 +80,7 @@ class SwapIdentitiesFlow(private val otherParty: Party, // TODO: for increased privacy, we should create one anonymous key per output state. val identities = LinkedHashMap() if (serviceHub.myInfo.isLegalIdentity(otherParty)) { - identities.put(otherParty, legalIdentityAnonymous.party.anonymise()) + identities[otherParty] = legalIdentityAnonymous.party.anonymise() } else { val otherSession = initiateFlow(otherParty) val data = buildDataToSign(legalIdentityAnonymous) diff --git a/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt b/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt index bb57ede626..4550d91539 100644 --- a/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt +++ b/confidential-identities/src/test/kotlin/net/corda/confidential/IdentitySyncFlowTests.kt @@ -109,7 +109,7 @@ class IdentitySyncFlowTests { * Very lightweight wrapping flow to trigger the counterparty flow that receives the identities. */ @InitiatingFlow - class Initiator(private val otherSide: Party, private val tx: WireTransaction): FlowLogic() { + class Initiator(private val otherSide: Party, private val tx: WireTransaction) : FlowLogic() { @Suspendable override fun call(): Boolean { val session = initiateFlow(otherSide) @@ -120,7 +120,7 @@ class IdentitySyncFlowTests { } @InitiatedBy(IdentitySyncFlowTests.Initiator::class) - class Receive(private val otherSideSession: FlowSession): FlowLogic() { + class Receive(private val otherSideSession: FlowSession) : FlowLogic() { @Suspendable override fun call() { subFlow(IdentitySyncFlow.Receive(otherSideSession)) diff --git a/core/src/main/java/net/corda/core/crypto/Base58.java b/core/src/main/java/net/corda/core/crypto/Base58.java index b831886e87..9037505bb2 100644 --- a/core/src/main/java/net/corda/core/crypto/Base58.java +++ b/core/src/main/java/net/corda/core/crypto/Base58.java @@ -83,7 +83,7 @@ public class Base58 { * @throws AddressFormatException if the given string is not a valid base58 string */ public static byte[] decode(String input) throws AddressFormatException { - if (input.length() == 0) { + if (input.isEmpty()) { return new byte[0]; } // Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits). diff --git a/core/src/main/java/net/corda/core/flows/IdentifiableException.java b/core/src/main/java/net/corda/core/flows/IdentifiableException.java index d1d32a97f3..93c9549685 100644 --- a/core/src/main/java/net/corda/core/flows/IdentifiableException.java +++ b/core/src/main/java/net/corda/core/flows/IdentifiableException.java @@ -10,7 +10,8 @@ public interface IdentifiableException { /** * @return the ID of the error, or null if the error doesn't have it set (yet). */ - default @Nullable Long getErrorId() { + @Nullable + default Long getErrorId() { return null; } } diff --git a/core/src/main/kotlin/net/corda/core/CordaOID.kt b/core/src/main/kotlin/net/corda/core/CordaOID.kt index c86a7f5269..0292c940b6 100644 --- a/core/src/main/kotlin/net/corda/core/CordaOID.kt +++ b/core/src/main/kotlin/net/corda/core/CordaOID.kt @@ -8,10 +8,10 @@ object CordaOID { /** Assigned to R3, see http://www.oid-info.com/cgi-bin/display?oid=1.3.6.1.4.1.50530&action=display */ const val R3_ROOT = "1.3.6.1.4.1.50530" /** OIDs issued for the Corda platform */ - const val CORDA_PLATFORM = R3_ROOT + ".1" + const val CORDA_PLATFORM = "$R3_ROOT.1" /** * Identifier for the X.509 certificate extension specifying the Corda role. See * https://r3-cev.atlassian.net/wiki/spaces/AWG/pages/156860572/Certificate+identity+type+extension for details. */ - const val X509_EXTENSION_CORDA_ROLE = CORDA_PLATFORM + ".1" + const val X509_EXTENSION_CORDA_ROLE = "$CORDA_PLATFORM.1" } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt b/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt index f86ca21fce..93aca8e49a 100644 --- a/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt +++ b/core/src/main/kotlin/net/corda/core/concurrent/ConcurrencyUtils.kt @@ -36,12 +36,12 @@ internal fun firstOf(futures: Array>, log: Logger, val winnerChosen = AtomicBoolean() futures.forEach { it.then { - if (winnerChosen.compareAndSet(false, true)) { - resultFuture.capture { handler(it) } - } else if (it.isCancelled) { - // Do nothing. - } else { - it.match({}, { log.error(shortCircuitedTaskFailedMessage, it) }) + when { + winnerChosen.compareAndSet(false, true) -> resultFuture.capture { handler(it) } + it.isCancelled -> { + // Do nothing. + } + else -> it.match({}, { log.error(shortCircuitedTaskFailedMessage, it) }) } } } diff --git a/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt b/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt index 58c1544c21..6a86741c6f 100644 --- a/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt +++ b/core/src/main/kotlin/net/corda/core/context/InvocationContext.kt @@ -77,7 +77,6 @@ data class Actor(val id: Id, val serviceId: AuthServiceId, val owningLegalIdenti */ @CordaSerializable data class Id(val value: String) - } /** diff --git a/core/src/main/kotlin/net/corda/core/context/Trace.kt b/core/src/main/kotlin/net/corda/core/context/Trace.kt index 6b9703c545..d06e1c59c8 100644 --- a/core/src/main/kotlin/net/corda/core/context/Trace.kt +++ b/core/src/main/kotlin/net/corda/core/context/Trace.kt @@ -27,7 +27,7 @@ data class Trace(val invocationId: InvocationId, val sessionId: SessionId) { class InvocationId(value: String, timestamp: Instant) : Id(value, TYPE, timestamp) { companion object { - private val TYPE = "Invocation" + private const val TYPE = "Invocation" /** * Creates an invocation id using a [java.util.UUID] as value and [Instant.now] as timestamp. @@ -44,7 +44,7 @@ data class Trace(val invocationId: InvocationId, val sessionId: SessionId) { class SessionId(value: String, timestamp: Instant) : Id(value, TYPE, timestamp) { companion object { - private val TYPE = "Session" + private const val TYPE = "Session" /** * Creates a session id using a [java.util.UUID] as value and [Instant.now] as timestamp. diff --git a/core/src/main/kotlin/net/corda/core/contracts/Amount.kt b/core/src/main/kotlin/net/corda/core/contracts/Amount.kt index 629461a3d7..3355954ca8 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/Amount.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/Amount.kt @@ -250,7 +250,7 @@ data class Amount(val quantity: Long, val displayTokenSize: BigDecimal, val residualTokens = quantity - (commonTokensPerPartition * partitions) val splitAmount = Amount(commonTokensPerPartition, displayTokenSize, token) val splitAmountPlusOne = Amount(commonTokensPerPartition + 1L, displayTokenSize, token) - return (0..partitions - 1).map { if (it < residualTokens) splitAmountPlusOne else splitAmount }.toList() + return (0 until partitions).map { if (it < residualTokens) splitAmountPlusOne else splitAmount }.toList() } /** diff --git a/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt b/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt index e5ab36de93..9899bf27dd 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/ContractAttachment.kt @@ -10,11 +10,11 @@ import net.corda.core.serialization.CordaSerializable * @property additionalContracts Additional contract names contained within the JAR. */ @CordaSerializable -class ContractAttachment @JvmOverloads constructor (val attachment: Attachment, val contract: ContractClassName, val additionalContracts: Set = emptySet(), val uploader: String? = null) : Attachment by attachment { +class ContractAttachment @JvmOverloads constructor(val attachment: Attachment, val contract: ContractClassName, val additionalContracts: Set = emptySet(), val uploader: String? = null) : Attachment by attachment { val allContracts: Set get() = additionalContracts + contract override fun toString(): String { - return "ContractAttachment(attachment=${attachment.id}, contracts='${allContracts}', uploader='${uploader}')" + return "ContractAttachment(attachment=${attachment.id}, contracts='$allContracts', uploader='$uploader')" } } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt index c22b1dadd3..44ac7008ff 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/ContractsDSL.kt @@ -20,7 +20,7 @@ import java.util.* object Requirements { /** Throws [IllegalArgumentException] if the given expression evaluates to false. */ @Suppress("NOTHING_TO_INLINE") // Inlining this takes it out of our committed ABI. - infix inline fun String.using(expr: Boolean) { + inline infix fun String.using(expr: Boolean) { if (!expr) throw IllegalArgumentException("Failed requirement: $this") } } diff --git a/core/src/main/kotlin/net/corda/core/contracts/Structures.kt b/core/src/main/kotlin/net/corda/core/contracts/Structures.kt index 2b363fb140..1f2c907069 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/Structures.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/Structures.kt @@ -196,7 +196,7 @@ data class Command(val value: T, val signers: List) constructor(data: T, key: PublicKey) : this(data, listOf(key)) private fun commandDataToString() = value.toString().let { if (it.contains("@")) it.replace('$', '.').split("@")[0] else it } - override fun toString() = "${commandDataToString()} with pubkeys ${signers.map { it.toStringShort() }.joinToString()}" + override fun toString() = "${commandDataToString()} with pubkeys ${signers.joinToString { it.toStringShort() }}" } /** A common move command for contract states which can change owner. */ diff --git a/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt b/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt index 71926f9e0a..5942d5f0e6 100644 --- a/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt +++ b/core/src/main/kotlin/net/corda/core/contracts/TransactionVerificationException.kt @@ -42,7 +42,7 @@ sealed class TransactionVerificationException(val txId: SecureHash, message: Str * @property contractClass The fully qualified class name of the failing contract. */ class ContractRejection(txId: SecureHash, val contractClass: String, cause: Throwable) : TransactionVerificationException(txId, "Contract verification failed: ${cause.message}, contract: $contractClass", cause) { - constructor(txId: SecureHash, contract: Contract, cause: Throwable) : this(txId, contract.javaClass.name, cause) + constructor(txId: SecureHash, contract: Contract, cause: Throwable) : this(txId, contract.javaClass.name, cause) } /** @@ -108,8 +108,10 @@ sealed class TransactionVerificationException(val txId: SecureHash, message: Str /** Whether the inputs or outputs list contains an encumbrance issue, see [TransactionMissingEncumbranceException]. */ @CordaSerializable enum class Direction { - /** Issue in the inputs list */ INPUT, - /** Issue in the outputs list */ OUTPUT + /** Issue in the inputs list */ + INPUT, + /** Issue in the outputs list */ + OUTPUT } // We could revisit and throw this more appropriate type in a future release that uses targetVersion to diff --git a/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt b/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt index 2ce4c24ce1..73c9f38fc4 100644 --- a/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt +++ b/core/src/main/kotlin/net/corda/core/cordapp/Cordapp.kt @@ -33,7 +33,7 @@ interface Cordapp { val contractClassNames: List val initiatedFlows: List>> val rpcFlows: List>> - val serviceFlows: List>> + val serviceFlows: List>> val schedulableFlows: List>> val services: List> val serializationWhitelists: List diff --git a/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt b/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt index 98bac0dae0..59ae9c7766 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/CompositeKey.kt @@ -100,7 +100,7 @@ class CompositeKey private constructor(val threshold: Int, children: List() - visitedMap.put(this, true) + visitedMap[this] = true cycleDetection(visitedMap) // Graph cycle testing on the root node. checkConstraints() for ((node, _) in children) { @@ -271,15 +271,17 @@ class CompositeKey private constructor(val threshold: Int, children: List 0) val n = children.size - return if (n > 1) - CompositeKey(threshold ?: children.map { (_, weight) -> weight }.sum(), children) - else if (n == 1) { - require(threshold == null || threshold == children.first().weight) - { "Trying to build invalid CompositeKey, threshold value different than weight of single child node." } - // Returning the only child node which is [PublicKey] itself. We need to avoid single-key [CompositeKey] instances, - // as there are scenarios where developers expected the underlying key and its composite versions to be equivalent. - children.first().node - } else throw IllegalStateException("Trying to build CompositeKey without child nodes.") + return when { + n > 1 -> CompositeKey(threshold ?: children.map { (_, weight) -> weight }.sum(), children) + n == 1 -> { + require(threshold == null || threshold == children.first().weight) + { "Trying to build invalid CompositeKey, threshold value different than weight of single child node." } + // Returning the only child node which is [PublicKey] itself. We need to avoid single-key [CompositeKey] instances, + // as there are scenarios where developers expected the underlying key and its composite versions to be equivalent. + children.first().node + } + else -> throw IllegalStateException("Trying to build CompositeKey without child nodes.") + } } } } diff --git a/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt b/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt index 1555ed70fc..73359726a8 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/MerkleTree.kt @@ -48,8 +48,8 @@ sealed class MerkleTree { * @return Tree root. */ private tailrec fun buildMerkleTree(lastNodesList: List): MerkleTree { - if (lastNodesList.size == 1) { - return lastNodesList[0] // Root reached. + return if (lastNodesList.size == 1) { + lastNodesList[0] // Root reached. } else { val newLevelHashes: MutableList = ArrayList() val n = lastNodesList.size @@ -61,7 +61,7 @@ sealed class MerkleTree { val combined = Node(newHash, left, right) newLevelHashes.add(combined) } - return buildMerkleTree(newLevelHashes) + buildMerkleTree(newLevelHashes) } } } diff --git a/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt b/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt index e5533895e5..002a357ced 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/NullKeys.kt @@ -18,5 +18,4 @@ object NullKeys { /** A signature with a key and value of zero. Useful when you want a signature object that you know won't ever be used. */ val NULL_SIGNATURE = TransactionSignature(ByteArray(32), NullPublicKey, SignatureMetadata(1, -1)) - } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt b/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt index bc39699f55..7e17b7b295 100644 --- a/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt +++ b/core/src/main/kotlin/net/corda/core/crypto/SignedData.kt @@ -36,7 +36,7 @@ open class SignedData(val raw: SerializedBytes, val sig: DigitalSign * @throws IllegalArgumentException if the data is invalid. */ @Throws(IllegalArgumentException::class) - open protected fun verifyData(data: T) { + protected open fun verifyData(data: T) { // By default we accept anything } } diff --git a/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt b/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt index af0c406410..55946b4817 100644 --- a/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt +++ b/core/src/main/kotlin/net/corda/core/flows/AbstractStateReplacementFlow.kt @@ -70,7 +70,7 @@ abstract class AbstractStateReplacementFlow { val finalTx = stx + signatures serviceHub.recordTransactions(finalTx) - return stx.resolveBaseTransaction(serviceHub).outRef(0) + return stx.resolveBaseTransaction(serviceHub).outRef(0) } /** @@ -78,7 +78,7 @@ abstract class AbstractStateReplacementFlow { * * @return the transaction */ - abstract protected fun assembleTx(): UpgradeTx + protected abstract fun assembleTx(): UpgradeTx /** * Initiate sessions with parties we want signatures from. @@ -176,7 +176,7 @@ abstract class AbstractStateReplacementFlow { * The proposal is returned if acceptable, otherwise a [StateReplacementException] is thrown. */ @Throws(StateReplacementException::class) - abstract protected fun verifyProposal(stx: SignedTransaction, proposal: Proposal) + protected abstract fun verifyProposal(stx: SignedTransaction, proposal: Proposal) private fun checkMySignatureRequired(stx: SignedTransaction) { // TODO: use keys from the keyManagementService instead diff --git a/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt b/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt index a4fd196d8e..509f96409e 100644 --- a/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt +++ b/core/src/main/kotlin/net/corda/core/flows/CollectSignaturesFlow.kt @@ -78,7 +78,8 @@ class CollectSignaturesFlow @JvmOverloads constructor(val partiallySignedTx: Sig } - @Suspendable override fun call(): SignedTransaction { + @Suspendable + override fun call(): SignedTransaction { // Check the signatures which have already been provided and that the transaction is valid. // Usually just the Initiator and possibly an oracle would have signed at this point. val myKeys: Iterable = myOptionalKeys ?: listOf(ourIdentity.owningKey) @@ -206,7 +207,8 @@ abstract class SignTransactionFlow(val otherSideSession: FlowSession, fun tracker() = ProgressTracker(RECEIVING, VERIFYING, SIGNING) } - @Suspendable override fun call(): SignedTransaction { + @Suspendable + override fun call(): SignedTransaction { progressTracker.currentStep = RECEIVING // Receive transaction and resolve dependencies, check sufficient signatures is disabled as we don't have all signatures. val stx = subFlow(ReceiveTransactionFlow(otherSideSession, checkSufficientSignatures = false)) @@ -243,12 +245,13 @@ abstract class SignTransactionFlow(val otherSideSession: FlowSession, return stx + mySignatures } - @Suspendable private fun checkSignatures(stx: SignedTransaction) { + @Suspendable + private fun checkSignatures(stx: SignedTransaction) { // We set `ignoreUnrecognisedParties` to `true` in `groupPublicKeysByWellKnownParty`. This is because we don't // need to recognise all keys, but just the initiator's. val signingWellKnownIdentities = groupPublicKeysByWellKnownParty(serviceHub, stx.sigs.map(TransactionSignature::by), true) require(otherSideSession.counterparty in signingWellKnownIdentities) { - "The Initiator of CollectSignaturesFlow must have signed the transaction. Found ${signingWellKnownIdentities}, expected ${otherSideSession}" + "The Initiator of CollectSignaturesFlow must have signed the transaction. Found $signingWellKnownIdentities, expected $otherSideSession" } val signed = stx.sigs.map { it.by } val allSigners = stx.tx.requiredSigningKeys @@ -278,9 +281,10 @@ abstract class SignTransactionFlow(val otherSideSession: FlowSession, */ @Suspendable @Throws(FlowException::class) - abstract protected fun checkTransaction(stx: SignedTransaction) + protected abstract fun checkTransaction(stx: SignedTransaction) - @Suspendable private fun checkMySignaturesRequired(stx: SignedTransaction, signingKeys: Iterable) { + @Suspendable + private fun checkMySignaturesRequired(stx: SignedTransaction, signingKeys: Iterable) { require(signingKeys.all { it in stx.tx.requiredSigningKeys }) { "A signature was requested for a key that isn't part of the required signing keys for transaction ${stx.id}" } diff --git a/core/src/main/kotlin/net/corda/core/flows/FlowException.kt b/core/src/main/kotlin/net/corda/core/flows/FlowException.kt index 8dbe892a74..cd00434c37 100644 --- a/core/src/main/kotlin/net/corda/core/flows/FlowException.kt +++ b/core/src/main/kotlin/net/corda/core/flows/FlowException.kt @@ -26,6 +26,7 @@ open class FlowException(message: String?, cause: Throwable?) : constructor(message: String?) : this(message, null) constructor(cause: Throwable?) : this(cause?.toString(), cause) constructor() : this(null, null) + var originalErrorId: Long? = null override fun getErrorId(): Long? = originalErrorId } @@ -40,5 +41,6 @@ class UnexpectedFlowEndException(message: String, cause: Throwable?, val origina CordaRuntimeException(message, cause), IdentifiableException { constructor(message: String, cause: Throwable?) : this(message, cause, null) constructor(message: String) : this(message, null) + override fun getErrorId(): Long? = originalErrorId } diff --git a/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt b/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt index 206862d2ec..bf543fc1ba 100644 --- a/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt +++ b/core/src/main/kotlin/net/corda/core/flows/FlowInitiator.kt @@ -50,20 +50,21 @@ sealed class FlowInitiator : Principal { * class hierarchy (which is now deprecated). The returned object has less information than it could have, so * prefer to use fetch an invocation context directly if you can (e.g. in [net.corda.core.messaging.StateMachineInfo]) */ - val invocationContext: InvocationContext get() { - val unknownName = CordaX500Name("UNKNOWN", "UNKNOWN", "GB") - var actor: Actor? = null - val origin: InvocationOrigin - when (this) { - is FlowInitiator.RPC -> { - actor = Actor(Actor.Id(this.username), AuthServiceId("UNKNOWN"), unknownName) - origin = InvocationOrigin.RPC(actor) + val invocationContext: InvocationContext + get() { + val unknownName = CordaX500Name("UNKNOWN", "UNKNOWN", "GB") + var actor: Actor? = null + val origin: InvocationOrigin + when (this) { + is FlowInitiator.RPC -> { + actor = Actor(Actor.Id(this.username), AuthServiceId("UNKNOWN"), unknownName) + origin = InvocationOrigin.RPC(actor) + } + is FlowInitiator.Peer -> origin = InvocationOrigin.Peer(this.party.name) + is FlowInitiator.Service -> origin = InvocationOrigin.Service(this.serviceClassName, unknownName) + FlowInitiator.Shell -> origin = InvocationOrigin.Shell + is FlowInitiator.Scheduled -> origin = InvocationOrigin.Scheduled(this.scheduledState) } - is FlowInitiator.Peer -> origin = InvocationOrigin.Peer(this.party.name) - is FlowInitiator.Service -> origin = InvocationOrigin.Service(this.serviceClassName, unknownName) - FlowInitiator.Shell -> origin = InvocationOrigin.Shell - is FlowInitiator.Scheduled -> origin = InvocationOrigin.Scheduled(this.scheduledState) + return InvocationContext.newInstance(origin = origin, actor = actor) } - return InvocationContext.newInstance(origin = origin, actor = actor) - } } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt b/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt index 5d7e27ac47..3215129d3f 100644 --- a/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt +++ b/core/src/main/kotlin/net/corda/core/identity/CordaX500Name.kt @@ -118,9 +118,10 @@ data class CordaX500Name(val commonName: String?, private var _x500Principal: X500Principal? = null /** Return the [X500Principal] equivalent of this name. */ - val x500Principal: X500Principal get() { - return _x500Principal ?: X500Principal(this.x500Name.encoded).also { _x500Principal = it } - } + val x500Principal: X500Principal + get() { + return _x500Principal ?: X500Principal(this.x500Name.encoded).also { _x500Principal = it } + } override fun toString(): String = x500Principal.toString() } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/internal/Emoji.kt b/core/src/main/kotlin/net/corda/core/internal/Emoji.kt index b90994e72d..27b780ece0 100644 --- a/core/src/main/kotlin/net/corda/core/internal/Emoji.kt +++ b/core/src/main/kotlin/net/corda/core/internal/Emoji.kt @@ -50,7 +50,6 @@ object Emoji { @JvmStatic val CODE_WARNING_SIGN: String = codePointsString(0x26A0, 0xFE0F) - /** * When non-null, toString() methods are allowed to use emoji in the output as we're going to render them to a * sufficiently capable text surface. diff --git a/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt b/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt index c7a6cfd112..4a89cf2bc1 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FetchDataFlow.kt @@ -134,7 +134,6 @@ sealed class FetchDataFlow( } } - /** * Given a set of hashes either loads from from local storage or requests them from the other peer. Downloaded * attachments are saved to local storage automatically. diff --git a/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt b/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt index 55ef39aecf..489f2601f7 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FlowIORequest.kt @@ -51,7 +51,8 @@ sealed class FlowIORequest { val shouldRetrySend: Boolean ) : FlowIORequest>>() { override fun toString() = "SendAndReceive(${sessionToMessage.mapValues { (key, value) -> - "$key=${value.hash}" }}, shouldRetrySend=$shouldRetrySend)" + "$key=${value.hash}" + }}, shouldRetrySend=$shouldRetrySend)" } /** diff --git a/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt b/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt index 7ea31b7bb7..36002556c8 100644 --- a/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt +++ b/core/src/main/kotlin/net/corda/core/internal/FlowStateMachine.kt @@ -3,10 +3,12 @@ package net.corda.core.internal import co.paralleluniverse.fibers.Suspendable import net.corda.core.DoNotImplement import net.corda.core.concurrent.CordaFuture -import net.corda.core.flows.* -import net.corda.core.identity.Party -import net.corda.core.identity.PartyAndCertificate import net.corda.core.context.InvocationContext +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.FlowSession +import net.corda.core.flows.FlowStackSnapshot +import net.corda.core.flows.StateMachineRunId +import net.corda.core.identity.Party import net.corda.core.node.ServiceHub import org.slf4j.Logger diff --git a/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt b/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt index edbb545d20..196342194f 100644 --- a/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt +++ b/core/src/main/kotlin/net/corda/core/internal/LazyPool.kt @@ -39,10 +39,10 @@ class LazyPool( lifeCycle.requireState(State.STARTED) poolSemaphore.acquire() val pooled = poolQueue.poll() - if (pooled == null) { - return newInstance() + return if (pooled == null) { + newInstance() } else { - return clearIfNeeded(pooled) + clearIfNeeded(pooled) } } diff --git a/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt b/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt index 5974f97f8e..5d6a156803 100644 --- a/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt +++ b/core/src/main/kotlin/net/corda/core/internal/LazyStickyPool.kt @@ -66,6 +66,6 @@ class LazyStickyPool( } fun close(): Iterable { - return boxes.map { it.instance?.poll() }.filterNotNull() + return boxes.mapNotNull { it.instance?.poll() } } } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt b/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt index e12fffc037..511aa1604f 100644 --- a/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt +++ b/core/src/main/kotlin/net/corda/core/internal/ProgressTracker.kt @@ -1,3 +1,3 @@ package net.corda.core.internal -val STRUCTURAL_STEP_PREFIX = "Structural step change in child of " \ No newline at end of file +const val STRUCTURAL_STEP_PREFIX = "Structural step change in child of " \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt b/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt index 5ccee61be5..87ae81d527 100644 --- a/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt +++ b/core/src/main/kotlin/net/corda/core/internal/X509EdDSAEngine.kt @@ -29,7 +29,7 @@ class X509EdDSAEngine : Signature { override fun engineInitVerify(publicKey: PublicKey) { val parsedKey = try { publicKey as? EdDSAPublicKey ?: EdDSAPublicKey(X509EncodedKeySpec(publicKey.encoded)) - } catch(e: Exception) { + } catch (e: Exception) { throw (InvalidKeyException(e.message)) } engine.initVerify(parsedKey) @@ -43,9 +43,9 @@ class X509EdDSAEngine : Signature { override fun engineGetParameters(): AlgorithmParameters = engine.parameters override fun engineSetParameter(params: AlgorithmParameterSpec) = engine.setParameter(params) - @Suppress("DEPRECATION") + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun engineGetParameter(param: String): Any = engine.getParameter(param) - @Suppress("DEPRECATION") + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun engineSetParameter(param: String, value: Any?) = engine.setParameter(param, value) } diff --git a/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt b/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt index c51deac096..bdeba66462 100644 --- a/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt +++ b/core/src/main/kotlin/net/corda/core/internal/concurrent/CordaFutureImpl.kt @@ -142,7 +142,7 @@ interface OpenFuture : ValueOrException, CordaFuture internal class CordaFutureImpl(private val impl: CompletableFuture = CompletableFuture()) : Future by impl, OpenFuture { companion object { private val defaultLog = contextLogger() - internal val listenerFailedMessage = "Future listener failed:" + internal const val listenerFailedMessage = "Future listener failed:" } override fun set(value: V) = impl.complete(value) diff --git a/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt b/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt index cc62490065..c4ab6a2e43 100644 --- a/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt +++ b/core/src/main/kotlin/net/corda/core/internal/cordapp/CordappImpl.kt @@ -13,7 +13,7 @@ data class CordappImpl( override val contractClassNames: List, override val initiatedFlows: List>>, override val rpcFlows: List>>, - override val serviceFlows: List>>, + override val serviceFlows: List>>, override val schedulableFlows: List>>, override val services: List>, override val serializationWhitelists: List, diff --git a/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt b/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt index 84d734db29..ad4d40ec16 100644 --- a/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt +++ b/core/src/main/kotlin/net/corda/core/messaging/FlowHandle.kt @@ -54,7 +54,6 @@ interface FlowProgressHandle : FlowHandle { override fun close() } - @CordaSerializable data class FlowHandleImpl( override val id: StateMachineRunId, diff --git a/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt b/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt index 94ab6da2e9..e8dabb91ce 100644 --- a/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt +++ b/core/src/main/kotlin/net/corda/core/node/AppServiceHub.kt @@ -26,5 +26,4 @@ interface AppServiceHub : ServiceHub { * TODO it is assumed here that the flow object has an appropriate classloader. */ fun startTrackedFlow(flow: FlowLogic): FlowProgressHandle - } \ No newline at end of file diff --git a/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt b/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt index d24fa67e7a..69d217d544 100644 --- a/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt +++ b/core/src/main/kotlin/net/corda/core/node/NodeInfo.kt @@ -31,7 +31,8 @@ data class NodeInfo(val addresses: List, require(platformVersion > 0) { "Platform version must be at least 1" } } - @Transient private var _legalIdentities: List? = null + @Transient + private var _legalIdentities: List? = null /** * An ordered list of legal identities supported by this node. The node will always have at least one, so if you diff --git a/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt b/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt index b104eb58cc..aed57c5c71 100644 --- a/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt +++ b/core/src/main/kotlin/net/corda/core/node/services/vault/QueryCriteriaUtils.kt @@ -243,7 +243,7 @@ object Builder { fun Field.functionPredicate(predicate: ColumnPredicate, groupByColumns: List>? = null, orderBy: Sort.Direction? = null) = info().functionPredicate(predicate, groupByColumns, orderBy) fun FieldInfo.functionPredicate(predicate: ColumnPredicate, groupByColumns: List>? = null, orderBy: Sort.Direction? = null) - = CriteriaExpression.AggregateFunctionExpression(Column(this), predicate, groupByColumns, orderBy) + = CriteriaExpression.AggregateFunctionExpression(Column(this), predicate, groupByColumns, orderBy) fun > KProperty1.comparePredicate(operator: BinaryComparisonOperator, value: R) = predicate(compare(operator, value)) @Deprecated("Does not support fields from a MappedSuperclass. Use equivalent on a FieldInfo.") @@ -367,7 +367,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.sum(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.SUM), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.SUM), groupByColumns?.map { Column(it) }, orderBy) fun KProperty1.count() = functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.COUNT)) @JvmStatic @@ -387,7 +387,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.avg(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.AVG), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.AVG), groupByColumns?.map { Column(it) }, orderBy) fun KProperty1.min(groupByColumns: List>? = null, orderBy: Sort.Direction? = null) = functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MIN), groupByColumns?.map { Column(it) }, orderBy) @@ -400,7 +400,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.min(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MIN), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MIN), groupByColumns?.map { Column(it) }, orderBy) fun KProperty1.max(groupByColumns: List>? = null, orderBy: Sort.Direction? = null) = functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MAX), groupByColumns?.map { Column(it) }, orderBy) @@ -413,7 +413,7 @@ object Builder { @JvmStatic @JvmOverloads fun FieldInfo.max(groupByColumns: List? = null, orderBy: Sort.Direction? = null) = - functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MAX), groupByColumns?.map { Column(it) }, orderBy) + functionPredicate(ColumnPredicate.AggregateFunction(AggregateFunctionType.MAX), groupByColumns?.map { Column(it) }, orderBy) private fun Field.info(): FieldInfo = FieldInfo(name, declaringClass) } diff --git a/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt b/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt index e7770667d3..ca7834bdba 100644 --- a/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt +++ b/core/src/main/kotlin/net/corda/core/schemas/CommonSchema.kt @@ -19,7 +19,7 @@ object CommonSchema object CommonSchemaV1 : MappedSchema(schemaFamily = CommonSchema.javaClass, version = 1, mappedTypes = emptyList()) { @MappedSuperclass - open class LinearState( + class LinearState( /** [ContractState] attributes */ /** X500Name of participant parties **/ @@ -44,7 +44,7 @@ object CommonSchemaV1 : MappedSchema(schemaFamily = CommonSchema.javaClass, vers } @MappedSuperclass - open class FungibleState( + class FungibleState( /** [ContractState] attributes */ /** X500Name of participant parties **/ diff --git a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt index 799ed787c7..2632f97629 100644 --- a/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt +++ b/core/src/main/kotlin/net/corda/core/schemas/PersistentTypes.kt @@ -70,7 +70,8 @@ open class MappedSchema(schemaFamily: Class<*>, * [StateRef] will be set to the correct value by the framework (there's no need to set during mapping generation by the state itself). */ @MappedSuperclass -@CordaSerializable open class PersistentState(@EmbeddedId var stateRef: PersistentStateRef? = null) : StatePersistable +@CordaSerializable +class PersistentState(@EmbeddedId var stateRef: PersistentStateRef? = null) : StatePersistable /** * Embedded [StateRef] representation used in state mapping. diff --git a/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt b/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt index 2ad2aded38..3de86d449d 100644 --- a/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt +++ b/core/src/main/kotlin/net/corda/core/serialization/SerializationCustomSerializer.kt @@ -14,11 +14,11 @@ interface SerializationCustomSerializer { * Should facilitate the conversion of the third party object into the serializable * local class specified by [PROXY] */ - fun toProxy(obj: OBJ) : PROXY + fun toProxy(obj: OBJ): PROXY /** * Should facilitate the conversion of the proxy object into a new instance of the * unserializable type */ - fun fromProxy(proxy: PROXY) : OBJ + fun fromProxy(proxy: PROXY): OBJ } diff --git a/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt b/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt index d44cee239d..2af0347e8c 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/ContractUpgradeTransactions.kt @@ -212,17 +212,17 @@ data class ContractUpgradeLedgerTransaction( * Outputs are computed by running the contract upgrade logic on input states. This is done eagerly so that the * transaction is verified during construction. */ - override val outputs: List> = inputs.map { input -> + override val outputs: List> = inputs.map { (state) -> // TODO: if there are encumbrance states in the inputs, just copy them across without modifying - val upgradedState = upgradedContract.upgrade(input.state.data) - val inputConstraint = input.state.constraint + val upgradedState = upgradedContract.upgrade(state.data) + val inputConstraint = state.constraint val outputConstraint = when (inputConstraint) { is HashAttachmentConstraint -> HashAttachmentConstraint(upgradedContractAttachment.id) WhitelistedByZoneAttachmentConstraint -> WhitelistedByZoneAttachmentConstraint else -> throw IllegalArgumentException("Unsupported input contract constraint $inputConstraint") } // TODO: re-map encumbrance pointers - input.state.copy( + state.copy( data = upgradedState, contract = upgradedContractClassName, constraint = outputConstraint diff --git a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt index 46deccf2c6..5a3cd87ab1 100644 --- a/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt +++ b/core/src/main/kotlin/net/corda/core/transactions/WireTransaction.kt @@ -106,7 +106,7 @@ class WireTransaction(componentGroups: List, val privacySalt: Pr resolveIdentity: (PublicKey) -> Party?, resolveAttachment: (SecureHash) -> Attachment?, resolveStateRef: (StateRef) -> TransactionState<*>?, - resolveContractAttachment: (TransactionState) -> AttachmentId? + @SuppressWarnings("unused") resolveContractAttachment: (TransactionState) -> AttachmentId? ): LedgerTransaction { return toLedgerTransactionInternal(resolveIdentity, resolveAttachment, resolveStateRef, null) } diff --git a/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt b/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt index c7d5d75810..902bc8e9bd 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/EncodingUtils.kt @@ -31,7 +31,6 @@ fun ByteArray.toBase64(): String = Base64.getEncoder().encodeToString(this) /** Convert a byte array to a hex (Base16) capitalized encoded [String]. */ fun ByteArray.toHex(): String = DatatypeConverter.printHexBinary(this) - // [String] encoders and decoders /** Base58-String to the actual real [String], i.e. "JxF12TrwUP45BMd" -> "Hello World". */ @@ -50,7 +49,6 @@ fun String.base64ToByteArray(): ByteArray = Base64.getDecoder().decode(this) /** Hex-String to [ByteArray]. Accept any hex form (capitalized, lowercase, mixed). */ fun String.hexToByteArray(): ByteArray = DatatypeConverter.parseHexBinary(this) - // Encoding changers /** Encoding changer. Base58-[String] to Base64-[String], i.e. "SGVsbG8gV29ybGQ=" -> JxF12TrwUP45BMd" */ diff --git a/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt b/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt index 4e6f62b31d..b53bdc9f34 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/KotlinUtils.kt @@ -106,8 +106,10 @@ interface VariablePropertyDelegate : PropertyDelegate { @CordaSerializable private class TransientProperty internal constructor(private val initialiser: () -> T) : PropertyDelegate { - @Transient private var initialised = false - @Transient private var value: T? = null + @Transient + private var initialised = false + @Transient + private var value: T? = null @Synchronized override operator fun getValue(thisRef: Any?, property: KProperty<*>): T { diff --git a/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt b/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt index f37cf3b5de..4fa4797a29 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/ProgressTracker.kt @@ -61,11 +61,11 @@ class ProgressTracker(vararg steps: Step) { // Sentinel objects. Overrides equals() to survive process restarts and serialization. object UNSTARTED : Step("Unstarted") { - override fun equals(other: Any?) = other is UNSTARTED + override fun equals(other: Any?) = other === UNSTARTED } object DONE : Step("Done") { - override fun equals(other: Any?) = other is DONE + override fun equals(other: Any?) = other === DONE } @CordaSerializable diff --git a/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt b/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt index dcc8ba7e00..da3efc2020 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/UntrustworthyData.kt @@ -40,7 +40,6 @@ fun SerializedBytes.checkPayloadIs(type: Class): Untrustworthy } catch (ex: Exception) { throw IllegalArgumentException("Payload invalid", ex) } - return type.castIfPossible(payloadData)?.let { UntrustworthyData(it) } ?: - throw IllegalArgumentException("We were expecting a ${type.name} but we instead got a " + - "${payloadData.javaClass.name} (${payloadData})") + return type.castIfPossible(payloadData)?.let { UntrustworthyData(it) } ?: throw IllegalArgumentException("We were expecting a ${type.name} but we instead got a " + + "${payloadData.javaClass.name} ($payloadData)") } diff --git a/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt b/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt index b56c693aec..e851dae583 100644 --- a/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt +++ b/core/src/main/kotlin/net/corda/core/utilities/UuidGenerator.kt @@ -5,6 +5,6 @@ import java.util.* class UuidGenerator { companion object { - fun next() : UUID = UUID.randomUUID() + fun next(): UUID = UUID.randomUUID() } } \ No newline at end of file diff --git a/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java b/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java index 61bb135f56..41bd180466 100644 --- a/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java +++ b/core/src/test/java/net/corda/core/flows/FlowsInJavaTest.java @@ -25,7 +25,7 @@ public class FlowsInJavaTest { private Party bob; @Before - public void setUp() throws Exception { + public void setUp() { aliceNode = mockNet.createPartyNode(TestConstants.ALICE_NAME); bobNode = mockNet.createPartyNode(TestConstants.BOB_NAME); bob = singleIdentity(bobNode.getInfo()); @@ -112,7 +112,7 @@ public class FlowsInJavaTest { @Suspendable @Override - public Void call() throws FlowException { + public Void call() { FlowSession session = initiateFlow(otherParty); session.receive(Primitives.unwrap(receiveType)); return null; diff --git a/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt b/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt index 7afd26a416..189a1e0dd2 100644 --- a/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt +++ b/core/src/test/kotlin/net/corda/core/contracts/StructuresTests.kt @@ -41,7 +41,6 @@ class AttachmentTest { } assertEquals(1, closeCalls) } - } class UniqueIdentifierTests { @@ -73,5 +72,4 @@ class UniqueIdentifierTests { assertEquals(ids[1], ids[2]) assertEquals(ids[1].hashCode(), ids[2].hashCode()) } - } \ No newline at end of file diff --git a/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt b/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt index 2023cc76e5..e0a0ea15b4 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/EdDSATests.kt @@ -176,9 +176,9 @@ class EdDSATests { /** A test vector object for digital signature schemes. */ private data class SignatureTestVector(val privateKeyHex: String, - val publicKeyHex: String, - val messageToSignHex: String, - val signatureOutputHex: String) + val publicKeyHex: String, + val messageToSignHex: String, + val signatureOutputHex: String) // Required to implement a custom doSign function, because Corda's Crypto.doSign does not allow empty messages (testVector1). private fun doSign(privateKey: PrivateKey, clearData: ByteArray): ByteArray { diff --git a/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt b/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt index 42a221862e..4e5a56149b 100644 --- a/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt +++ b/core/src/test/kotlin/net/corda/core/crypto/X509NameConstraintsTest.kt @@ -126,6 +126,5 @@ class X509NameConstraintsTest { pathValidator.validate(certPath, params) true } - } } diff --git a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt index 74414e47b1..06f3907b21 100644 --- a/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/AttachmentTests.kt @@ -3,7 +3,6 @@ package net.corda.core.flows import co.paralleluniverse.fibers.Suspendable import net.corda.core.contracts.Attachment import net.corda.core.crypto.SecureHash -import net.corda.core.crypto.sha256 import net.corda.core.identity.Party import net.corda.core.internal.FetchAttachmentsFlow import net.corda.core.internal.FetchDataFlow @@ -82,7 +81,7 @@ class AttachmentTests { } @Test - fun `missing`() { + fun missing() { val aliceNode = mockNet.createPartyNode(ALICE_NAME) val bobNode = mockNet.createPartyNode(BOB_NAME) aliceNode.registerInitiatedFlow(FetchAttachmentsResponse::class.java) diff --git a/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt b/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt index b8f0275acb..dffb7925ba 100644 --- a/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt +++ b/core/src/test/kotlin/net/corda/core/flows/CollectSignaturesFlowTests.kt @@ -13,7 +13,11 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.getOrThrow import net.corda.node.internal.StartedNode import net.corda.testing.contracts.DummyContract -import net.corda.testing.core.* +import net.corda.testing.core.ALICE_NAME +import net.corda.testing.core.BOB_NAME +import net.corda.testing.core.CHARLIE_NAME +import net.corda.testing.core.TestIdentity +import net.corda.testing.core.singleIdentity import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.internal.InternalMockNetwork @@ -22,7 +26,6 @@ import net.corda.testing.node.internal.startFlow import org.junit.After import org.junit.Before import org.junit.Test -import kotlin.reflect.KClass import kotlin.test.assertFailsWith class CollectSignaturesFlowTests { @@ -76,9 +79,11 @@ class CollectSignaturesFlowTests { @InitiatedBy(TestFlow.Initiator::class) class Responder(private val otherSideSession: FlowSession) : FlowLogic() { - @Suspendable override fun call() { + @Suspendable + override fun call() { val signFlow = object : SignTransactionFlow(otherSideSession) { - @Suspendable override fun checkTransaction(stx: SignedTransaction) = requireThat { + @Suspendable + override fun checkTransaction(stx: SignedTransaction) = requireThat { val tx = stx.tx val ltx = tx.toLedgerTransaction(serviceHub) "There should only be one output state" using (tx.outputs.size == 1) diff --git a/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt b/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt index 8831e5905e..f64b243de5 100644 --- a/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt +++ b/core/src/test/kotlin/net/corda/core/identity/PartyAndCertificateTest.kt @@ -23,7 +23,7 @@ class PartyAndCertificateTest { @Test fun `reject a path with no roles`() { - val path = X509Utilities.buildCertPath(DEV_ROOT_CA.certificate) + val path = X509Utilities.buildCertPath(DEV_ROOT_CA.certificate) assertFailsWith { PartyAndCertificate(path) } } diff --git a/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt b/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt index ff80c8b33b..84d33b9e3c 100644 --- a/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt +++ b/core/src/test/kotlin/net/corda/core/identity/PartyTest.kt @@ -9,7 +9,7 @@ import kotlin.test.assertNotEquals class PartyTest { @Test - fun `equality`() { + fun equality() { val key = entropyToKeyPair(BigInteger.valueOf(20170207L)).public val differentKey = entropyToKeyPair(BigInteger.valueOf(7201702L)).public val anonymousParty = AnonymousParty(key) diff --git a/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt b/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt index a379e57673..bb759bc8d8 100644 --- a/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt +++ b/core/src/test/kotlin/net/corda/core/internal/AbstractAttachmentTest.kt @@ -11,7 +11,6 @@ import org.junit.Test import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths -import kotlin.streams.toList import kotlin.test.assertEquals class AbstractAttachmentTest { diff --git a/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt b/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt index 922a99117a..1f4ba6eec4 100644 --- a/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt +++ b/core/src/test/kotlin/net/corda/core/internal/LegalNameValidatorTest.kt @@ -61,7 +61,7 @@ class LegalNameValidatorTest { } // Latin capital letter turned m assertFailsWith { - LegalNameValidator.validateOrganization( "Test\u019CLtd", LegalNameValidator.Validation.FULL) + LegalNameValidator.validateOrganization("Test\u019CLtd", LegalNameValidator.Validation.FULL) } // Latin small letter turned e assertFailsWith { @@ -84,7 +84,7 @@ class LegalNameValidatorTest { } // Latin capital letter turned m assertFailsWith { - LegalNameValidator.validateNameAttribute( "Test\u019CLtd", LegalNameValidator.Validation.FULL) + LegalNameValidator.validateNameAttribute("Test\u019CLtd", LegalNameValidator.Validation.FULL) } // Latin small letter turned e assertFailsWith { diff --git a/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt b/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt index 7a97bc6e51..0b9db73064 100644 --- a/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt +++ b/core/src/test/kotlin/net/corda/core/node/VaultUpdateTests.kt @@ -14,7 +14,7 @@ import kotlin.test.assertFailsWith class VaultUpdateTests { private companion object { - val DUMMY_PROGRAM_ID = "net.corda.core.node.VaultUpdateTests.DummyContract" + const val DUMMY_PROGRAM_ID = "net.corda.core.node.VaultUpdateTests.DummyContract" val DUMMY_NOTARY = TestIdentity(DUMMY_NOTARY_NAME, 20).party val emptyUpdate = Vault.Update(emptySet(), emptySet(), type = Vault.UpdateType.GENERAL) } @@ -58,7 +58,7 @@ class VaultUpdateTests { @Test fun `nothing plus something is something`() { val before = emptyUpdate - val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef2, stateAndRef3)) + val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef2, stateAndRef3)) val expected = Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef2, stateAndRef3)) assertEquals(expected, after) } @@ -66,7 +66,7 @@ class VaultUpdateTests { @Test fun `something plus consume state 0 is something without state 0 output`() { val before = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1)) - val after = before + Vault.Update(setOf(stateAndRef0), setOf()) + val after = before + Vault.Update(setOf(stateAndRef0), setOf()) val expected = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef1)) assertEquals(expected, after) } @@ -74,7 +74,7 @@ class VaultUpdateTests { @Test fun `something plus produce state 4 is something with additional state 4 output`() { val before = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1)) - val after = before + Vault.Update(setOf(), setOf(stateAndRef4)) + val after = before + Vault.Update(setOf(), setOf(stateAndRef4)) val expected = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1, stateAndRef4)) assertEquals(expected, after) } @@ -82,7 +82,7 @@ class VaultUpdateTests { @Test fun `something plus consume states 0 and 1, and produce state 4, is something without state 0 and 1 outputs and only state 4 output`() { val before = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef0, stateAndRef1)) - val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef4)) + val after = before + Vault.Update(setOf(stateAndRef0, stateAndRef1), setOf(stateAndRef4)) val expected = Vault.Update(setOf(stateAndRef2, stateAndRef3), setOf(stateAndRef4)) assertEquals(expected, after) } diff --git a/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt b/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt index 7770f5af8a..5db6397e69 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/AttachmentSerializationTest.kt @@ -42,6 +42,7 @@ private fun createAttachmentData(content: String) = ByteArrayOutputStream().appl private fun Attachment.extractContent() = ByteArrayOutputStream().apply { extractFile("content", this) }.toString(UTF_8.name()) +@SuppressWarnings("deprecation") private fun StartedNode<*>.saveAttachment(content: String) = database.transaction { attachments.importAttachment(createAttachmentData(content).inputStream()) } diff --git a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt index cfb4c681a3..27e54e71f8 100644 --- a/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt +++ b/core/src/test/kotlin/net/corda/core/serialization/TransactionSerializationTests.kt @@ -83,7 +83,7 @@ class TransactionSerializationTests { stx.verifyRequiredSignatures() // Corrupt the data and ensure the signature catches the problem. - val bytesField = stx.id::bytes.javaField?.apply { setAccessible(true) } + val bytesField = stx.id::bytes.javaField?.apply { isAccessible = true } val bytes = bytesField?.get(stx.id) as ByteArray bytes[5] = bytes[5].inc() diff --git a/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt b/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt index 2cb630e01b..6ca1cf810b 100644 --- a/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt +++ b/core/src/test/kotlin/net/corda/core/transactions/CompatibleTransactionTests.kt @@ -52,12 +52,12 @@ class CompatibleTransactionTests { // Do not add attachments (empty list). private val componentGroupsA by lazy { listOf( - inputGroup, - outputGroup, - commandGroup, - notaryGroup, - timeWindowGroup, - signersGroup + inputGroup, + outputGroup, + commandGroup, + notaryGroup, + timeWindowGroup, + signersGroup ) } private val wireTransactionA by lazy { WireTransaction(componentGroups = componentGroupsA, privacySalt = privacySalt) } @@ -124,7 +124,8 @@ class CompatibleTransactionTests { @Test fun `WireTransaction constructors and compatibility`() { - val wireTransactionOldConstructor = WireTransaction(inputs, attachments, outputs, commands, notary, timeWindow, privacySalt) + val groups = WireTransaction.createComponentGroups(inputs, outputs, commands, attachments, notary, timeWindow) + val wireTransactionOldConstructor = WireTransaction(groups, privacySalt) assertEquals(wireTransactionA, wireTransactionOldConstructor) // Malformed tx - attachments is not List. For this example, we mistakenly added input-state (StateRef) serialised objects with ATTACHMENTS_GROUP.ordinal. @@ -386,7 +387,7 @@ class CompatibleTransactionTests { assertFailsWith { WireTransaction(componentGroups = componentGroupsLessSigners, privacySalt = PrivacySalt()) } // Test if there is no command to sign. - val commandsNoKey1= listOf(dummyCommand(DUMMY_KEY_2.public)) + val commandsNoKey1 = listOf(dummyCommand(DUMMY_KEY_2.public)) val componentGroupsNoKey1ToSign = listOf( inputGroup, @@ -399,7 +400,7 @@ class CompatibleTransactionTests { ) val wtxNoKey1 = WireTransaction(componentGroups = componentGroupsNoKey1ToSign, privacySalt = PrivacySalt()) - val allCommandsNoKey1Ftx= wtxNoKey1.buildFilteredTransaction(Predicate(::filterCommandsOnly)) + val allCommandsNoKey1Ftx = wtxNoKey1.buildFilteredTransaction(Predicate(::filterCommandsOnly)) allCommandsNoKey1Ftx.checkCommandVisibility(DUMMY_KEY_1.public) // This will pass, because there are indeed no commands to sign in the original transaction. } @@ -490,7 +491,7 @@ class CompatibleTransactionTests { // Remove both last signer (KEY1) and related command. // Update partial Merkle tree for signers. val updatedFilteredComponentsNoLastCommandAndSigners = listOf(noLastCommandDataGroup, noLastSignerGroup) - val ftxNoLastCommandAndSigners = ftxConstructor.invoke(key1CommandsFtx.id, updatedFilteredComponentsNoLastCommandAndSigners, key1CommandsFtx.groupHashes) as FilteredTransaction + val ftxNoLastCommandAndSigners = ftxConstructor.invoke(key1CommandsFtx.id, updatedFilteredComponentsNoLastCommandAndSigners, key1CommandsFtx.groupHashes) // verify() will pass as the transaction is well-formed. ftxNoLastCommandAndSigners.verify() // checkCommandVisibility() will not pass, because checkAllComponentsVisible(ComponentGroupEnum.SIGNERS_GROUP) will fail. @@ -499,7 +500,7 @@ class CompatibleTransactionTests { // Remove last signer for which there is no pointer from a visible commandData. This is the case of Key2. // Do not change partial Merkle tree for signers. // This time the object can be constructed as there is no pointer mismatch. - val ftxNoLastSigner = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2SamePMT, key2CommandsFtx.groupHashes) as FilteredTransaction + val ftxNoLastSigner = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2SamePMT, key2CommandsFtx.groupHashes) // verify() will fail as we didn't change the partial Merkle tree. assertFailsWith { ftxNoLastSigner.verify() } // checkCommandVisibility() will not pass. @@ -507,7 +508,7 @@ class CompatibleTransactionTests { // Remove last signer for which there is no pointer from a visible commandData. This is the case of Key2. // Update partial Merkle tree for signers. - val ftxNoLastSignerB = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2, key2CommandsFtx.groupHashes) as FilteredTransaction + val ftxNoLastSignerB = ftxConstructor.invoke(key2CommandsFtx.id, updatedFilteredComponentsNoSignersKey2, key2CommandsFtx.groupHashes) // verify() will pass, the transaction is well-formed. ftxNoLastSignerB.verify() // But, checkAllComponentsVisible() will not pass. @@ -532,14 +533,14 @@ class CompatibleTransactionTests { val alterFilteredComponents = listOf(key1CommandsFtx.filteredComponentGroups[0], alterSignerGroup) // Do not update groupHashes. - val ftxAlterSigner = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes) as FilteredTransaction + val ftxAlterSigner = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes) // Visible components in signers group cannot be verified against their partial Merkle tree. assertFailsWith { ftxAlterSigner.verify() } // Also, checkAllComponentsVisible() will not pass (groupHash matching will fail). assertFailsWith { ftxAlterSigner.checkCommandVisibility(DUMMY_KEY_1.public) } // Update groupHashes. - val ftxAlterSignerB = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes.subList(0, 6) + alterMTree.hash) as FilteredTransaction + val ftxAlterSignerB = ftxConstructor.invoke(key1CommandsFtx.id, alterFilteredComponents, key1CommandsFtx.groupHashes.subList(0, 6) + alterMTree.hash) // Visible components in signers group cannot be verified against their partial Merkle tree. assertFailsWith { ftxAlterSignerB.verify() } // Also, checkAllComponentsVisible() will not pass (top level Merkle tree cannot be verified against transaction's id). diff --git a/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt b/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt index efdfd28256..468f9cee95 100644 --- a/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt +++ b/core/src/test/kotlin/net/corda/core/transactions/TransactionEncumbranceTests.kt @@ -22,7 +22,7 @@ import org.junit.Test import java.time.Instant import java.time.temporal.ChronoUnit -val TEST_TIMELOCK_ID = "net.corda.core.transactions.TransactionEncumbranceTests\$DummyTimeLock" +const val TEST_TIMELOCK_ID = "net.corda.core.transactions.TransactionEncumbranceTests\$DummyTimeLock" class TransactionEncumbranceTests { private companion object { diff --git a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java index bf2c58b858..56dea67577 100644 --- a/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java +++ b/docs/source/example-code/src/main/java/net/corda/docs/FlowCookbookJava.java @@ -466,7 +466,7 @@ public class FlowCookbookJava { subFlow(new SendStateAndRefFlow(counterpartySession, dummyStates)); // On the receive side ... - List> resolvedStateAndRef = subFlow(new ReceiveStateAndRefFlow(counterpartySession)); + List> resolvedStateAndRef = subFlow(new ReceiveStateAndRefFlow<>(counterpartySession)); // DOCEND 14 try { diff --git a/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java b/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java index 8159838082..3baa5fbcb6 100644 --- a/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java +++ b/docs/source/example-code/src/main/java/net/corda/docs/java/tutorial/contract/CommercialPaper.java @@ -50,7 +50,7 @@ public class CommercialPaper implements Contract { requireThat(require -> { require.using("the paper must have matured", time.isAfter(input.getMaturityDate())); require.using("the received amount equals the face value", received == input.getFaceValue()); - require.using("the paper must be destroyed", outputs.size() == 0); + require.using("the paper must be destroyed", outputs.isEmpty()); require.using("the transaction is signed by the owner of the CP", cmd.getSigners().contains(input.getOwner().getOwningKey())); return null; }); diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt index ac592eaa8f..ffb9a58f47 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/CustomVaultQuery.kt @@ -143,9 +143,8 @@ object TopupIssuerFlow { // now invoke Cash subflow to Move issued assetType to issue requester progressTracker.currentStep = TRANSFERRING val moveCashFlow = CashPaymentFlow(amount, issueTo, anonymous = false) - val moveTx = subFlow(moveCashFlow) // NOTE: CashFlow PayCash calls FinalityFlow which performs a Broadcast (which stores a local copy of the txn to the ledger) - return moveTx + return subFlow(moveCashFlow) } } } diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt index 9b31523586..34e46f5ba3 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/WorkflowTransactionBuildTutorial.kt @@ -23,7 +23,7 @@ enum class WorkflowState { REJECTED } -val TRADE_APPROVAL_PROGRAM_ID = "net.corda.docs.TradeApprovalContract" +const val TRADE_APPROVAL_PROGRAM_ID = "net.corda.docs.TradeApprovalContract" /** * Minimal contract to encode a simple workflow with one initial state and two possible eventual states. diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt index 8d20dc5778..14a6746eeb 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/helloworld/templateContract.kt @@ -4,7 +4,7 @@ import net.corda.core.contracts.CommandData import net.corda.core.contracts.Contract import net.corda.core.transactions.LedgerTransaction -val TEMPLATE_CONTRACT_ID = "com.template.TemplateContract" +const val TEMPLATE_CONTRACT_ID = "com.template.TemplateContract" open class TemplateContract : Contract { // A transaction is considered valid if the verify() function of the contract of each of the transaction's input diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt index f62afd4c9c..94a8c1cabe 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/mocknetwork/TutorialMockNetwork.kt @@ -8,20 +8,12 @@ import net.corda.core.flows.FlowSession import net.corda.core.flows.InitiatedBy import net.corda.core.flows.InitiatingFlow import net.corda.core.identity.Party -import net.corda.core.messaging.MessageRecipients -import net.corda.core.serialization.deserialize -import net.corda.core.serialization.serialize -import net.corda.core.utilities.OpaqueBytes -import net.corda.core.utilities.getOrThrow import net.corda.core.utilities.unwrap -import net.corda.node.services.messaging.Message -import net.corda.node.services.statemachine.DataSessionMessage -import net.corda.node.services.statemachine.ExistingSessionMessage -import net.corda.testing.node.* +import net.corda.testing.node.MockNetwork +import net.corda.testing.node.StartedMockNode import org.junit.After import org.junit.Before import org.junit.Rule -import org.junit.Test import org.junit.rules.ExpectedException class TutorialMockNetwork { @@ -53,9 +45,9 @@ class TutorialMockNetwork { } } - lateinit private var mockNet: MockNetwork - lateinit private var nodeA: StartedMockNode - lateinit private var nodeB: StartedMockNode + private lateinit var mockNet: MockNetwork + private lateinit var nodeA: StartedMockNode + private lateinit var nodeB: StartedMockNode @Rule @JvmField @@ -76,8 +68,8 @@ class TutorialMockNetwork { // @Test // fun `fail if initiated doesn't send back 1 on first result`() { - // DOCSTART 1 - // TODO: Fix this test - accessing the MessagingService directly exposes internal interfaces + // DOCSTART 1 + // TODO: Fix this test - accessing the MessagingService directly exposes internal interfaces // nodeB.setMessagingServiceSpy(object : MessagingServiceSpy(nodeB.network) { // override fun send(message: Message, target: MessageRecipients, retryId: Long?, sequenceKey: Any, additionalHeaders: Map) { // val messageData = message.data.deserialize() as? ExistingSessionMessage @@ -91,7 +83,7 @@ class TutorialMockNetwork { // } // } // }) - // DOCEND 1 + // DOCEND 1 // val initiatingReceiveFlow = nodeA.startFlow(FlowA(nodeB.info.legalIdentities.first())) // diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt index 05fb4af8bd..66def91a3f 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/contract.kt @@ -9,7 +9,7 @@ import net.corda.core.transactions.LedgerTransaction import net.corda.core.contracts.* // Replace IOUContract's contract ID and definition with: -val IOU_CONTRACT_ID = "com.template.IOUContract" +const val IOU_CONTRACT_ID = "com.template.IOUContract" class IOUContract : Contract { // Our Create command. diff --git a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt index 27f4705501..546ac2fb39 100644 --- a/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt +++ b/docs/source/example-code/src/main/kotlin/net/corda/docs/tutorial/twoparty/flow.kt @@ -4,19 +4,15 @@ package net.corda.docs.tutorial.twoparty import co.paralleluniverse.fibers.Suspendable import net.corda.core.contracts.Command import net.corda.core.contracts.StateAndContract -import net.corda.core.flows.* +import net.corda.core.flows.CollectSignaturesFlow +import net.corda.core.flows.FinalityFlow +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.InitiatingFlow +import net.corda.core.flows.StartableByRPC import net.corda.core.identity.Party -import net.corda.core.messaging.CordaRPCOps -import net.corda.core.serialization.SerializationWhitelist import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.ProgressTracker -import net.corda.webserver.services.WebServerPluginRegistry -import java.util.function.Function -import javax.ws.rs.GET -import javax.ws.rs.Path -import javax.ws.rs.Produces -import javax.ws.rs.core.MediaType -import javax.ws.rs.core.Response + // DOCEND 01 @InitiatingFlow diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt index 2d43cb34ed..1ac8e1e909 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/CustomVaultQueryTest.kt @@ -24,7 +24,6 @@ import net.corda.node.services.vault.VaultSchemaV1 import net.corda.testing.core.singleIdentity import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode -import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.After import org.junit.Assert @@ -105,12 +104,12 @@ class CustomVaultQueryTest { val balancesNodesA = nodeA.transaction { nodeA.services.getCashBalances() } - println("BalanceA\n" + balancesNodesA) + println("BalanceA\n$balancesNodesA") val balancesNodesB = nodeB.transaction { nodeB.services.getCashBalances() } - println("BalanceB\n" + balancesNodesB) + println("BalanceB\n$balancesNodesB") return Pair(balancesNodesA, balancesNodesB) } diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt index a521faf5e1..b27f382ca7 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/FxTransactionBuildTutorialTest.kt @@ -4,15 +4,18 @@ import net.corda.core.identity.Party import net.corda.core.toFuture import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.getOrThrow -import net.corda.finance.* +import net.corda.finance.DOLLARS +import net.corda.finance.GBP +import net.corda.finance.POUNDS +import net.corda.finance.USD import net.corda.finance.contracts.getCashBalances import net.corda.finance.flows.CashIssueFlow +import net.corda.finance.issuedBy import net.corda.testing.core.singleIdentity import net.corda.testing.node.MockNetwork import net.corda.testing.node.StartedMockNode import org.junit.After import org.junit.Before -import org.junit.Ignore import org.junit.Test import kotlin.test.assertEquals @@ -71,8 +74,8 @@ class FxTransactionBuildTutorialTest { nodeB.services.getCashBalances() } - println("BalanceA\n" + balancesA) - println("BalanceB\n" + balancesB) + println("BalanceA\n$balancesA") + println("BalanceB\n$balancesB") // Verify the transfers occurred as expected assertEquals(POUNDS(100), balancesA[GBP]) assertEquals(DOLLARS(1000 - 200), balancesA[USD]) diff --git a/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt b/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt index c114399410..fc04b31387 100644 --- a/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt +++ b/docs/source/example-code/src/test/kotlin/net/corda/docs/tutorial/testdsl/TutorialTestDSL.kt @@ -3,7 +3,6 @@ package net.corda.docs.tutorial.testdsl import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.whenever import net.corda.core.contracts.TransactionVerificationException -import net.corda.core.crypto.generateKeyPair import net.corda.core.identity.CordaX500Name import net.corda.core.node.services.IdentityService import net.corda.core.utilities.days @@ -14,11 +13,14 @@ import net.corda.finance.contracts.CommercialPaper import net.corda.finance.contracts.ICommercialPaperState import net.corda.finance.contracts.asset.CASH import net.corda.finance.contracts.asset.Cash -import net.corda.testing.core.* +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.SerializationEnvironmentRule +import net.corda.testing.core.TestIdentity import net.corda.testing.internal.rigorousMock import net.corda.testing.node.MockServices import net.corda.testing.node.ledger -import net.corda.testing.node.makeTestIdentityService import net.corda.testing.node.transaction import org.junit.Rule import org.junit.Test diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt index 0acff416e8..fc0830dac1 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConfigurationTemplate.kt @@ -9,5 +9,4 @@ open class DatabaseConfigurationTemplate { protected open val config: (DatabaseConfiguration) -> String = { "" } fun generate(config: DatabaseConfiguration) = config(config).trimMargin() - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt index 1916000bb2..9133d0473c 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseConnection.kt @@ -17,8 +17,8 @@ class DatabaseConnection( fun open(): Connection { try { val connectionProps = Properties() - connectionProps.put("user", config.username) - connectionProps.put("password", config.password) + connectionProps["user"] = config.username + connectionProps["password"] = config.password retry (5) { conn = DriverManager.getConnection(connectionString, connectionProps) } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt index f0cb2074e4..51891fc9fa 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseSettings.kt @@ -63,5 +63,4 @@ class DatabaseSettings { val template: DatabaseConfigurationTemplate get() = databaseConfigTemplate - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt index dad351596c..4fb39c0944 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/DatabaseType.kt @@ -44,7 +44,5 @@ enum class DatabaseType(val settings: DatabaseSettings) { "postgresql" -> POSTGRES else -> null } - } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt b/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt index 6bdfa2ad80..8042812bf4 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/database/configuration/H2ConfigurationTemplate.kt @@ -14,5 +14,4 @@ class H2ConfigurationTemplate : DatabaseConfigurationTemplate() { |h2port=${it.port} """ } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt b/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt index b329c68e4c..320b3226da 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/file/LogSource.kt @@ -27,7 +27,7 @@ class LogSource( val logFiles = directory.list { it.filter { (!filePatternUsedForExclusion && it.fileName.toString().matches(fileRegex)) || - (filePatternUsedForExclusion && !it.fileName.toString().matches(fileRegex)) + (filePatternUsedForExclusion && !it.fileName.toString().matches(fileRegex)) }.toList() } val result = mutableListOf() @@ -43,5 +43,4 @@ class LogSource( } return result } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt index 0b65fc338e..ba91151edc 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/ConjunctiveWatch.kt @@ -12,7 +12,7 @@ class ConjunctiveWatch( override fun ready() = left.ready() && right.ready() override fun await(timeout: Duration): Boolean { - val countDownLatch = CountDownLatch(2) + val countDownLatch = CountDownLatch(2) listOf(left, right).parallelStream().forEach { if (it.await(timeout)) { countDownLatch.countDown() @@ -20,5 +20,4 @@ class ConjunctiveWatch( } return countDownLatch.await(timeout) } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt index 444d47ddb7..b4609bc151 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/DisjunctiveWatch.kt @@ -1,7 +1,6 @@ package net.corda.behave.monitoring import net.corda.behave.await -import rx.Observable import java.time.Duration import java.util.concurrent.CountDownLatch @@ -13,7 +12,7 @@ class DisjunctiveWatch( override fun ready() = left.ready() || right.ready() override fun await(timeout: Duration): Boolean { - val countDownLatch = CountDownLatch(1) + val countDownLatch = CountDownLatch(1) listOf(left, right).parallelStream().forEach { if (it.await(timeout)) { countDownLatch.countDown() @@ -21,6 +20,5 @@ class DisjunctiveWatch( } return countDownLatch.await(timeout) } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt index ae3b14dba4..389eff44ac 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/monitoring/Watch.kt @@ -13,6 +13,7 @@ interface Watch { operator fun times(other: Watch): Watch { return ConjunctiveWatch(this, other) } + operator fun div(other: Watch): Watch { return DisjunctiveWatch(this, other) } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt b/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt index 35bf5a88ed..a787b3ac8e 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/network/Network.kt @@ -147,8 +147,8 @@ class Network private constructor( val matches = LogSource(targetDirectory) .find(".*[Ee]xception.*") .groupBy { it.filename.toAbsolutePath() } - for (match in matches) { - log.info("Log(${match.key}):\n${match.value.joinToString("\n") { it.contents }}") + for ((key, value) in matches) { + log.info("Log($key):\n${value.joinToString("\n") { it.contents }}") } } } else { diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt index 5d9e9b46f2..9f9fa80418 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/Distribution.kt @@ -128,7 +128,7 @@ class Distribution private constructor( * @param version The version of the Corda distribution */ fun fromVersionString(version: String): Distribution = when (version) { - "master" -> MASTER + "master" -> MASTER "corda-3.0" -> fromArtifactory(version) else -> fromJarFile(version) } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt index b7b1fa5478..6ec510c75b 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/Configuration.kt @@ -56,5 +56,4 @@ class Configuration( private val log = contextLogger() const val DEFAULT_PASSWORD = "S0meS3cretW0rd" } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt index 332e7de951..244d94847f 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/ConfigurationTemplate.kt @@ -5,5 +5,4 @@ open class ConfigurationTemplate { protected open val config: (Configuration) -> String = { "" } fun generate(config: Configuration) = config(config).trimMargin() - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt index 37f506f4fd..57a1f96e6b 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CordappConfiguration.kt @@ -24,5 +24,4 @@ class CordappConfiguration(var apps: List = emptyList(), val includeFina private fun formatApp(config: Configuration, app: String): String { return "\"${app.replace("CORDA_VERSION", config.distribution.version)}\"" } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt index df829bff89..16252650d2 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/CurrencyConfiguration.kt @@ -16,5 +16,4 @@ class CurrencyConfiguration(private val issuableCurrencies: List) : Conf """ } } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt index ca9f3c37a8..e25257441d 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/DatabaseConfiguration.kt @@ -13,5 +13,4 @@ data class DatabaseConfiguration( ) { fun config() = type.settings.config(this) - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt index e3073668b5..a96ca3da05 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NetworkInterface.kt @@ -54,12 +54,9 @@ data class NetworkInterface( val s = Socket("localhost", portNumber) s.close() true - } catch (_: Exception) { false } } - } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt index dc7c74caa6..9cfa15b652 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryConfiguration.kt @@ -12,5 +12,4 @@ class NotaryConfiguration(private val notaryType: NotaryType = NotaryType.NONE) "notary { validating = true }" } } - } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt index abceb4b519..788d430cdc 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/NotaryType.kt @@ -5,7 +5,6 @@ enum class NotaryType { NONE, VALIDATING, NON_VALIDATING - } fun String.toNotaryType(): NotaryType? { diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt index 1c44a2f967..6da827f802 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/node/configuration/UserConfiguration.kt @@ -33,5 +33,4 @@ class UserConfiguration : ConfigurationTemplate(), Iterable } fun use(action: (Command) -> Unit): Int { - try { + use { start() action(this) - } finally { - close() } return exitCode } fun use(subscriber: Subscriber, action: (Command, Observable) -> Unit = { _, _ -> }): Int { - try { + use { output.subscribe(subscriber) start() action(this, output) - } finally { - close() } return exitCode } diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt b/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt index 2c0a5b735b..5d76ac83fc 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/process/JarCommand.kt @@ -23,12 +23,10 @@ class JarCommand( companion object { private fun extraArguments(enableRemoteDebugging: Boolean) = - if (enableRemoteDebugging) { - arrayOf("-Dcapsule.jvm.args=-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005") - } else { - arrayOf() - } - + if (enableRemoteDebugging) { + arrayOf("-Dcapsule.jvm.args=-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005") + } else { + arrayOf() + } } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt b/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt index 18dcc065e6..7912596804 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/process/output/OutputListener.kt @@ -5,5 +5,4 @@ interface OutputListener { fun onNewLine(line: String) fun onEndOfStream() - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt b/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt index cc42a60511..dad118d5d5 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/service/Service.kt @@ -59,7 +59,7 @@ abstract class Service( override fun toString() = "Service(name = $name, port = $port)" - protected open fun checkPrerequisites() { } + protected open fun checkPrerequisites() {} protected open fun startService() = true @@ -68,5 +68,4 @@ abstract class Service( protected open fun verify() = true protected open fun waitUntilStarted() = true - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt index 484944ee29..8a2b5c6b02 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/H2Service.kt @@ -9,10 +9,8 @@ class H2Service( companion object { - val database = "node" - val schema = "dbo" - val username = "sa" - + const val database = "node" + const val schema = "dbo" + const val username = "sa" } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt index b42f783569..e331dcde74 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/service/database/PostgreSQLService.kt @@ -41,11 +41,10 @@ class PostgreSQLService( } companion object { - val host = "localhost" - val database = "postgres" - val schema = "public" - val username = "postgres" - val driver = "postgresql-42.1.4.jar" + const val host = "localhost" + const val database = "postgres" + const val schema = "public" + const val username = "postgres" + const val driver = "postgresql-42.1.4.jar" } - } \ No newline at end of file diff --git a/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt b/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt index fcbde2d54f..d55a2d2c69 100644 --- a/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt +++ b/experimental/behave/src/main/kotlin/net/corda/behave/ssh/MonitoringSSHClient.kt @@ -53,10 +53,8 @@ class MonitoringSSHClient( } fun use(action: (MonitoringSSHClient) -> Unit) { - try { + use { action(this) - } finally { - close() } } @@ -65,5 +63,4 @@ class MonitoringSSHClient( fun write(charSequence: CharSequence) = client.write(charSequence) fun writeLine(string: String) = client.writeLine(string) - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/Scenarios.kt b/experimental/behave/src/scenario/kotlin/Scenarios.kt index ac65923a00..5977c40cd9 100644 --- a/experimental/behave/src/scenario/kotlin/Scenarios.kt +++ b/experimental/behave/src/scenario/kotlin/Scenarios.kt @@ -4,8 +4,8 @@ import org.junit.runner.RunWith @RunWith(Cucumber::class) @CucumberOptions( - glue = arrayOf("net.corda.behave.scenarios"), - plugin = arrayOf("pretty") + glue = ["net.corda.behave.scenarios"], + plugin = ["pretty"] ) @Suppress("KDocMissingDocumentation") class CucumberTest diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt index 62f7bf0680..4f811c8b90 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioRunner.kt @@ -1,4 +1,5 @@ @file:JvmName("ScenarioRunner") + package net.corda.behave.scenarios import joptsimple.OptionParser @@ -7,15 +8,15 @@ import kotlin.system.exitProcess fun main(args: Array) { val parser = OptionParser() val featurePath = parser.accepts("path").withRequiredArg().required().ofType(String::class.java) - .describedAs("Path location of .feature specifications") + .describedAs("Path location of .feature specifications") val glue = parser.accepts("glue").withOptionalArg().ofType(String::class.java) - .describedAs("location of additional step definitions, hooks and plugins") - .defaultsTo("net.corda.behave.scenarios") + .describedAs("location of additional step definitions, hooks and plugins") + .defaultsTo("net.corda.behave.scenarios") val plugin = parser.accepts("plugin").withOptionalArg().ofType(String::class.java) - .describedAs("register additional plugins (see https://cucumber.io/docs/reference/jvm)") - .defaultsTo("pretty") + .describedAs("register additional plugins (see https://cucumber.io/docs/reference/jvm)") + .defaultsTo("pretty") val tags = parser.accepts("tags").withOptionalArg().ofType(String::class.java) - .describedAs("only run scenarios marked as @") + .describedAs("only run scenarios marked as @") val dryRun = parser.accepts("d") val options = try { @@ -27,14 +28,14 @@ fun main(args: Array) { } val cliArgs = listOf("--glue", - options.valueOf(glue), - "--plugin", - options.valueOf(plugin), - options.valueOf(featurePath)) + - (if (options.hasArgument("tags")) - listOf("--tags", options.valueOf(tags)) - else emptyList()) + - if (options.has(dryRun)) listOf("-d") else emptyList() + options.valueOf(glue), + "--plugin", + options.valueOf(plugin), + options.valueOf(featurePath)) + + (if (options.hasArgument("tags")) + listOf("--tags", options.valueOf(tags)) + else emptyList()) + + if (options.has(dryRun)) listOf("-d") else emptyList() println("Cucumber CLI scenario runner args: $cliArgs") cucumber.api.cli.Main.main(cliArgs.toTypedArray()) diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt index af016f5ad7..d0422b934e 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/ScenarioState.kt @@ -17,7 +17,7 @@ class ScenarioState { error(message) } - fun error(message: String, ex: Throwable? = null): T { + fun error(message: String, ex: Throwable? = null): T { this.network?.signalFailure(message, ex) if (ex != null) { throw Exception(message, ex) @@ -74,7 +74,7 @@ class ScenarioState { network.stop() } - private fun nodeName(name: String) = "$name" + private fun nodeName(name: String) = name private fun newNode(name: String): Node.Builder { val builder = Node.new() @@ -82,5 +82,4 @@ class ScenarioState { nodes.add(builder) return builder } - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt index e37e9c475d..fbc06d59a9 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/StepsContainer.kt @@ -12,7 +12,7 @@ import net.corda.core.utilities.loggerFor class StepsContainer(val state: ScenarioState) : En { companion object { - val stepsProviders: List by lazy { + val stepsProviders: List by lazy { FastClasspathScanner().addClassLoader(this::class.java.classLoader).scan() .getNamesOfClassesImplementing(StepsProvider::class.java) .mapNotNull { this::class.java.classLoader.loadClass(it).asSubclass(StepsProvider::class.java) } diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt index 5dcb7e9b41..6930331f10 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Cash.kt @@ -33,7 +33,7 @@ class Cash(state: ScenarioState) : Substeps(state) { } } - fun issueCash(issueToNode: String, amount: Long, currency: String): SignedTransaction { + fun issueCash(issueToNode: String, amount: Long, currency: String): SignedTransaction { return withClient(issueToNode) { try { val notaryList = it.notaryIdentities() @@ -48,10 +48,10 @@ class Cash(state: ScenarioState) : Substeps(state) { } } - fun transferCash(senderNode: String, sendToNode: String, amount: Long, currency: String): SignedTransaction { + fun transferCash(senderNode: String, sendToNode: String, amount: Long, currency: String): SignedTransaction { return withClient(senderNode) { try { - val sendToX500Name = node(sendToNode).config.cordaX500Name + val sendToX500Name = node(sendToNode).config.cordaX500Name val sendToParty = node(senderNode).rpc { it.wellKnownPartyFromX500Name(sendToX500Name) ?: throw IllegalStateException("Unable to locate $sendToX500Name in Network Map Service") } @@ -62,5 +62,4 @@ class Cash(state: ScenarioState) : Substeps(state) { } } } - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt index 49e77d67d2..b74c34b293 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Database.kt @@ -19,5 +19,4 @@ class Database(state: ScenarioState) : Substeps(state) { assertThat(latch.await(10.seconds)).isTrue() } } - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt index a1e7ddd875..7bf9eb4bf6 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/helpers/Ssh.kt @@ -39,5 +39,4 @@ class Ssh(state: ScenarioState) : Substeps(state) { state.fail("Unable to find SSH start-up message for node $nodeName") } } - } \ No newline at end of file diff --git a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/steps/ConfigurationSteps.kt b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/steps/ConfigurationSteps.kt index 5a87b21162..a50f92719a 100644 --- a/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/steps/ConfigurationSteps.kt +++ b/experimental/behave/src/scenario/kotlin/net/corda/behave/scenarios/steps/ConfigurationSteps.kt @@ -60,7 +60,6 @@ class ConfigurationSteps : StepsBlock { Given("^node (\\w+) has app installed: (.+)$") { name, app -> node(name).withApp(app) } - } } diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt index eb0809cccc..2f8869681f 100644 --- a/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt +++ b/experimental/behave/src/test/kotlin/net/corda/behave/monitoring/MonitoringTests.kt @@ -60,5 +60,4 @@ class MonitoringTests { val aggregate = watch1 / watch2 / watch3 assertThat(aggregate.await(1.seconds)).isFalse() } - } \ No newline at end of file diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt index 642ba937c4..11ddb590e2 100644 --- a/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt +++ b/experimental/behave/src/test/kotlin/net/corda/behave/network/NetworkTests.kt @@ -38,5 +38,4 @@ class NetworkTests { it.keepAlive(30.seconds) } } - } \ No newline at end of file diff --git a/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt b/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt index 1b823524ec..a8d690afd0 100644 --- a/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt +++ b/experimental/behave/src/test/kotlin/net/corda/behave/service/PostreSQLServiceTests.kt @@ -15,5 +15,4 @@ class PostreSQLServiceTests { service.stop() assertThat(didStart).isTrue() } - } \ No newline at end of file diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt index 8a30c2319f..6bc15cd304 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt @@ -49,7 +49,7 @@ fun String.simplifyClass(): String { return if (this.endsWith('>')) { val templateStart = this.indexOf('<') val clazz = (this.substring(0, templateStart)) - val params = this.substring(templateStart+1, this.length-1).split(',').map { it.simplifyClass() }.joinToString() + val params = this.substring(templateStart+1, this.length-1).split(',').joinToString { it.simplifyClass() } "${clazz.simplifyClass()} <$params>" } @@ -108,20 +108,22 @@ class ListProperty( private val values: MutableList = mutableListOf()) : Property(name, type) { override fun stringify(sb: IndentingStringBuilder) { sb.apply { - if (values.isEmpty()) { - appendln("$name : $type : [ << EMPTY LIST >> ]") - } else if (values.first() is Stringify) { - appendln("$name : $type : [") - values.forEach { - (it as Stringify).stringify(this) + when { + values.isEmpty() -> appendln("$name : $type : [ << EMPTY LIST >> ]") + values.first() is Stringify -> { + appendln("$name : $type : [") + values.forEach { + (it as Stringify).stringify(this) + } + appendln("]") } - appendln("]") - } else { - appendln("$name : $type : [") - values.forEach { - appendln(it.toString()) + else -> { + appendln("$name : $type : [") + values.forEach { + appendln(it.toString()) + } + appendln("]") } - appendln("]") } } } diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt index a027249079..c831665036 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobLoader.kt @@ -25,9 +25,9 @@ class InMemoryBlobHandler(config_: Config) : BlobHandler(config_) { /** * */ -abstract class BlobHandler (val config: Config) { +abstract class BlobHandler(val config: Config) { companion object { - fun make(config: Config) : BlobHandler { + fun make(config: Config): BlobHandler { return when (config.mode) { Mode.file -> FileBlobHandler(config) Mode.inMem -> InMemoryBlobHandler(config) @@ -35,6 +35,6 @@ abstract class BlobHandler (val config: Config) { } } - abstract fun getBytes() : ByteArray + abstract fun getBytes(): ByteArray } diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt index 48d81a8eb7..1ec7fe6557 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/IndentingStringBuilder.kt @@ -9,7 +9,7 @@ package net.corda.blobinspector * currently being added to the string. * @property indent How deeply the next line should be offset from the first column */ -class IndentingStringBuilder(s : String = "", private val offset : Int = 4) { +class IndentingStringBuilder(s: String = "", private val offset: Int = 4) { private val sb = StringBuilder(s) private var indenting = true private var indent = 0 @@ -21,18 +21,17 @@ class IndentingStringBuilder(s : String = "", private val offset : Int = 4) { appender(ln) - if (ln.endsWith("{") || ln.endsWith("[")){ + if (ln.endsWith("{") || ln.endsWith("[")) { indent += offset } } fun appendln(ln: String) { - wrap(ln) { s -> sb.appendln("${"".padStart(if (indenting) indent else 0, ' ')}$s") } + wrap(ln) { s -> sb.appendln("${"".padStart(if (indenting) indent else 0, ' ')}$s") } indenting = true } - fun append(ln: String) { indenting = false diff --git a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt index 0e13b9e087..9abe288afa 100644 --- a/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt +++ b/experimental/blobinspector/src/main/kotlin/net/corda/blobinspector/Main.kt @@ -21,7 +21,7 @@ private fun modeOption() = Option("m", "mode", true, "mode, file is the default" * @return An instantiated but unpopulated [Config] object instance suitable for the mode into * which we've been placed. This Config object should be populated via [loadModeSpecificOptions] */ -fun getMode(args: Array) : Config { +fun getMode(args: Array): Config { // For now we only care what mode we're being put in, we can build the rest of the args and parse them // later val options = Options().apply { @@ -31,7 +31,7 @@ fun getMode(args: Array) : Config { val cmd = try { DefaultParser().parse(options, args, true) } catch (e: org.apache.commons.cli.ParseException) { - println (e) + println(e) HelpFormatter().printHelp("blobinspector", options) throw IllegalArgumentException("OH NO!!!") } @@ -56,10 +56,10 @@ fun loadModeSpecificOptions(config: Config, args: Array) { addOption(modeOption()) } - populate (try { + populate(try { DefaultParser().parse(modeSpecificOptions, args, false) } catch (e: org.apache.commons.cli.ParseException) { - println ("Error: ${e.message}") + println("Error: ${e.message}") HelpFormatter().printHelp("blobinspector", modeSpecificOptions) System.exit(1) return @@ -71,7 +71,7 @@ fun loadModeSpecificOptions(config: Config, args: Array) { * Executable entry point */ fun main(args: Array) { - println ("<<< WARNING: this tool is experimental and under active development >>>") + println("<<< WARNING: this tool is experimental and under active development >>>") getMode(args).let { mode -> loadModeSpecificOptions(mode, args) BlobHandler.make(mode) diff --git a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt index a018baaf49..c0a87a667e 100644 --- a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt +++ b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/FileParseTests.kt @@ -5,13 +5,12 @@ import java.net.URI import org.junit.Test import net.corda.testing.common.internal.ProjectStructure.projectRootDir - class FileParseTests { @Suppress("UNUSED") - var localPath : URI = projectRootDir.toUri().resolve( + var localPath: URI = projectRootDir.toUri().resolve( "tools/blobinspector/src/test/resources/net/corda/blobinspector") - fun setupArgsWithFile(path: String) = Array(5) { + fun setupArgsWithFile(path: String) = Array(5) { when (it) { 0 -> "-m" 1 -> "file" @@ -22,7 +21,7 @@ class FileParseTests { } } - private val filesToTest = listOf ( + private val filesToTest = listOf( "FileParseTests.1Int", "FileParseTests.2Int", "FileParseTests.3Int", @@ -33,9 +32,9 @@ class FileParseTests { "FileParseTests.StringList", "FileParseTests.MapIntString", "FileParseTests.MapIntClass" - ) + ) - fun testFile(file : String) { + fun testFile(file: String) { val path = FileParseTests::class.java.getResource(file) val args = setupArgsWithFile(path.toString()) @@ -67,9 +66,15 @@ class FileParseTests { val args = verbose.let { if (it) - Array(4) { when (it) { 0 -> "-f" ; 1 -> path.toString(); 2 -> "-d"; 3 -> "-vs"; else -> "error" } } + Array(4) { + when (it) { 0 -> "-f"; 1 -> path.toString(); 2 -> "-d"; 3 -> "-vs"; else -> "error" + } + } else - Array(3) { when (it) { 0 -> "-f" ; 1 -> path.toString(); 2 -> "-d"; else -> "error" } } + Array(3) { + when (it) { 0 -> "-f"; 1 -> path.toString(); 2 -> "-d"; else -> "error" + } + } } val handler = getMode(args).let { mode -> @@ -78,7 +83,5 @@ class FileParseTests { } inspectBlob(handler.config, handler.getBytes()) - } - } diff --git a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt index 9b69363386..80560576a4 100644 --- a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt +++ b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/ModeParse.kt @@ -8,7 +8,7 @@ import kotlin.test.assertFalse class ModeParse { @Test fun fileIsSetToFile() { - val opts1 = Array(2) { + val opts1 = Array(2) { when (it) { 0 -> "-m" 1 -> "file" @@ -21,14 +21,14 @@ class ModeParse { @Test fun nothingIsSetToFile() { - val opts1 = Array(0) { "" } + val opts1 = Array(0) { "" } assertEquals(Mode.file, getMode(opts1).mode) } @Test fun filePathIsSet() { - val opts1 = Array(4) { + val opts1 = Array(4) { when (it) { 0 -> "-m" 1 -> "file" @@ -39,7 +39,7 @@ class ModeParse { } val config = getMode(opts1) - assertTrue (config is FileConfig) + assertTrue(config is FileConfig) assertEquals(Mode.file, config.mode) assertEquals("unset", (config as FileConfig).file) @@ -50,28 +50,34 @@ class ModeParse { @Test fun schemaIsSet() { - Array(2) { when (it) { 0 -> "-f"; 1 -> "path/to/file"; else -> "error" } }.let { options -> + Array(2) { + when (it) { 0 -> "-f"; 1 -> "path/to/file"; else -> "error" + } + }.let { options -> getMode(options).apply { loadModeSpecificOptions(this, options) - assertFalse (schema) + assertFalse(schema) } } - Array(3) { when (it) { 0 -> "--schema"; 1 -> "-f"; 2 -> "path/to/file"; else -> "error" } }.let { + Array(3) { + when (it) { 0 -> "--schema"; 1 -> "-f"; 2 -> "path/to/file"; else -> "error" + } + }.let { getMode(it).apply { loadModeSpecificOptions(this, it) - assertTrue (schema) + assertTrue(schema) } } - Array(3) { when (it) { 0 -> "-f"; 1 -> "path/to/file"; 2 -> "-s"; else -> "error" } }.let { + Array(3) { + when (it) { 0 -> "-f"; 1 -> "path/to/file"; 2 -> "-s"; else -> "error" + } + }.let { getMode(it).apply { loadModeSpecificOptions(this, it) - assertTrue (schema) + assertTrue(schema) } } - } - - } \ No newline at end of file diff --git a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt index 10d470685b..3dcafbc88d 100644 --- a/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt +++ b/experimental/blobinspector/src/test/kotlin/net/corda/blobinspector/SimplifyClassTests.kt @@ -8,8 +8,8 @@ class SimplifyClassTests { fun test1() { data class A(val a: Int) - println (A::class.java.name) - println (A::class.java.name.simplifyClass()) + println(A::class.java.name) + println(A::class.java.name.simplifyClass()) } @Test diff --git a/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt b/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt index f08bdd52e9..7a014a9c2b 100644 --- a/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt +++ b/experimental/kryo-hook/src/main/kotlin/net/corda/kryohook/KryoHook.kt @@ -13,7 +13,7 @@ import java.util.concurrent.ConcurrentHashMap class KryoHookAgent { companion object { @JvmStatic - fun premain(argumentsString: String?, instrumentation: Instrumentation) { + fun premain(@SuppressWarnings("unused") argumentsString: String?, instrumentation: Instrumentation) { Runtime.getRuntime().addShutdownHook(Thread { val statsTrees = KryoHook.events.values.flatMap { readTrees(it, 0).second @@ -51,9 +51,9 @@ fun prettyStatsTree(indent: Int, statsTree: StatsTree, builder: StringBuilder) { * Later we "parse" these lists into a tree. */ object KryoHook : ClassFileTransformer { - val classPool = ClassPool.getDefault() + val classPool = ClassPool.getDefault()!! - val hookClassName = javaClass.name + val hookClassName = javaClass.name!! override fun transform( loader: ClassLoader?, @@ -95,14 +95,14 @@ object KryoHook : ClassFileTransformer { val events = ConcurrentHashMap>() @JvmStatic - fun writeEnter(kryo: Kryo, output: Output, obj: Any) { + fun writeEnter(@SuppressWarnings("unused") kryo: Kryo, output: Output, obj: Any) { events.getOrPut(Strand.currentStrand().id) { ArrayList() }.add( StatsEvent.Enter(obj.javaClass.name, output.total()) ) } @JvmStatic - fun writeExit(kryo: Kryo, output: Output, obj: Any) { - events.get(Strand.currentStrand().id)!!.add( + fun writeExit(@SuppressWarnings("unused") kryo: Kryo, output: Output, obj: Any) { + events[Strand.currentStrand().id]!!.add( StatsEvent.Exit(obj.javaClass.name, output.total()) ) } diff --git a/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt b/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt index 1cc522206e..2ae0c41e9d 100644 --- a/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt +++ b/experimental/quasar-hook/src/main/kotlin/net/corda/quasarhook/QuasarInstrumentationHook.kt @@ -144,9 +144,9 @@ class QuasarInstrumentationHookAgent { } object QuasarInstrumentationHook : ClassFileTransformer { - val classPool = ClassPool.getDefault() + val classPool = ClassPool.getDefault()!! - val hookClassName = "net.corda.quasarhook.QuasarInstrumentationHookKt" + const val hookClassName = "net.corda.quasarhook.QuasarInstrumentationHookKt" val instrumentMap = mapOf Unit>( "co/paralleluniverse/fibers/Stack" to { clazz -> @@ -198,10 +198,10 @@ object QuasarInstrumentationHook : ClassFileTransformer { data class Glob(val parts: List, val isFull: Boolean) { override fun toString(): String { - if (isFull) { - return parts.joinToString(".") + return if (isFull) { + parts.joinToString(".") } else { - return "${parts.joinToString(".")}**" + "${parts.joinToString(".")}**" } } } @@ -229,8 +229,8 @@ data class PackageTree(val branches: Map) { * Truncate the tree below [other]. */ fun truncate(other: PackageTree): PackageTree { - if (other.isEmpty()) { - return empty + return if (other.isEmpty()) { + empty } else { val truncatedBranches = HashMap(branches) other.branches.forEach { (key, tree) -> @@ -238,7 +238,7 @@ data class PackageTree(val branches: Map) { previousTree?.truncate(tree) ?: empty } } - return PackageTree(truncatedBranches) + PackageTree(truncatedBranches) } } diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java b/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java index f0fd4bf668..3f8fffbe50 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/CandidacyStatus.java @@ -55,7 +55,7 @@ public class CandidacyStatus { * @return true if the input was absent from the underlying map */ public boolean putIfAbsent(final String methodSignature) { - return null == candidateMethods.putIfAbsent(methodSignature, CandidateMethod.of(methodSignature)); + return candidateMethods.putIfAbsent(methodSignature, CandidateMethod.of(methodSignature)) == null; } /** @@ -166,10 +166,10 @@ public class CandidacyStatus { public Set getDisallowedMethods() { final Set out = new HashSet<>(); - for (final String candidateName : candidateMethods.keySet()) { - final CandidateMethod candidate = candidateMethods.get(candidateName); + for (final Map.Entry stringCandidateMethodEntry : candidateMethods.entrySet()) { + final CandidateMethod candidate = stringCandidateMethodEntry.getValue(); if (candidate.getCurrentState() == CandidateMethod.State.DISALLOWED) { - out.add(candidateName); + out.add(stringCandidateMethodEntry.getKey()); } } diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java b/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java index f5e742b95c..579d591322 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/SandboxAwareClassWriter.java @@ -51,7 +51,8 @@ public final class SandboxAwareClassWriter extends ClassWriter { } public String getCommonSuperClassBorrowed(final String type1, final String type2) throws ClassNotFoundException { - Class c, d; + Class c; + Class d; try { c = Class.forName(type1.replace('/', '.'), false, loader); d = Class.forName(type2.replace('/', '.'), false, loader); diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java b/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java index 08cbbd794b..c282faf89f 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/Utils.java @@ -8,9 +8,9 @@ import java.util.regex.Pattern; */ public final class Utils { - public final static String SANDBOX_PREFIX_INTERNAL = "sandbox/"; + public static final String SANDBOX_PREFIX_INTERNAL = "sandbox/"; - public final static String CLASSFILE_NAME_SUFFIX = "^(.*)\\.class$"; + public static final String CLASSFILE_NAME_SUFFIX = "^(.*)\\.class$"; public static final Pattern JAVA_LANG_PATTERN_INTERNAL = Pattern.compile("^java/lang/(.*)"); @@ -141,7 +141,7 @@ public final class Utils { return remaining; final StringBuilder out = new StringBuilder(); - while (remaining.length() > 0) { + while (!remaining.isEmpty()) { final Matcher refTypeFound = REFTYPE_PATTERN_INTERNAL.matcher(remaining); if (refTypeFound.find()) { final int startOfType = refTypeFound.start(); diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java b/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java index 2a99ffbdca..89cc01ffb9 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/WhitelistClassLoader.java @@ -315,9 +315,9 @@ public final class WhitelistClassLoader extends ClassLoader { try (final FileSystem zfs = FileSystems.newFileSystem(zipUri, env)) { final Path jarRoot = zfs.getRootDirectories().iterator().next(); - for (final String newName : transformedClasses.keySet()) { - final byte[] newClassDef = transformedClasses.get(newName); - final String relativePathName = Utils.convertQualifiedClassNameToInternalForm(newName) + ".class"; + for (final Map.Entry stringEntry : transformedClasses.entrySet()) { + final byte[] newClassDef = stringEntry.getValue(); + final String relativePathName = Utils.convertQualifiedClassNameToInternalForm(stringEntry.getKey()) + ".class"; final Path outPath = jarRoot.resolve(relativePathName); Files.createDirectories(outPath.getParent()); diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java b/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java index 7274d914c7..1f6bcaa33d 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/costing/RuntimeCostAccounter.java @@ -12,33 +12,13 @@ public class RuntimeCostAccounter { private static Thread primaryThread; - private static final ThreadLocal allocationCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal allocationCost = ThreadLocal.withInitial(() -> 0L); - private static final ThreadLocal jumpCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal jumpCost = ThreadLocal.withInitial(() -> 0L); - private static final ThreadLocal invokeCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal invokeCost = ThreadLocal.withInitial(() -> 0L); - private static final ThreadLocal throwCost = new ThreadLocal() { - @Override - protected Long initialValue() { - return 0L; - } - }; + private static final ThreadLocal throwCost = ThreadLocal.withInitial(() -> 0L); private static final long BASELINE_ALLOC_KILL_THRESHOLD = 1024 * 1024; diff --git a/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java b/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java index 33ab308a2e..45b8dca6ce 100644 --- a/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java +++ b/experimental/sandbox/src/main/java/net/corda/sandbox/tools/SandboxCreator.java @@ -31,7 +31,7 @@ public final class SandboxCreator { private final WhitelistClassLoader wlcl; private final boolean hasInputJar; - private final static OptionParser parser = new OptionParser(); + private static final OptionParser parser = new OptionParser(); private static void usage() { System.err.println(USAGE_STRING); diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java b/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java index 371b27226d..5cc600e898 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/CandidateMethodTest.java @@ -11,8 +11,8 @@ import static org.junit.Assert.assertEquals; public class CandidateMethodTest { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(CandidateMethodTest.class); - private final static String OBJECT_INIT_METHOD = "java/lang/Object.:()V"; - private final static String SYSTEM_OUT_PRINTLN = "java/io/PrintStream.println:(Ljava/lang/String;)V"; + private static final String OBJECT_INIT_METHOD = "java/lang/Object.:()V"; + private static final String SYSTEM_OUT_PRINTLN = "java/io/PrintStream.println:(Ljava/lang/String;)V"; private CandidateMethod candidateMethod; diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java b/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java index 9c2ae06b4e..2e74a65fe1 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/Constants.java @@ -1,11 +1,11 @@ package net.corda.sandbox; class Constants { - public final static String INVALID_CLASS = "foobar"; - public final static String BASE_DETERMINISTIC_METHODS = "resource/CallObjectMethods"; - public final static String SYSTEM_OUT_PRINTLN_CLASS = "resource/CallPrintln"; - public final static String INVOKEDYNAMIC_METHOD_CLASS = "resource/UseLambdaToForceInvokeDynamic"; - public final static String NATIVE_METHOD_CLASS = "resource/CallNative"; - public final static String BASIC_COLLECTIONS_CLASS = "resource/UseBasicCollections"; - public final static String FINALIZER_CLASS = "resource/UseFinalizer"; + public static final String INVALID_CLASS = "foobar"; + public static final String BASE_DETERMINISTIC_METHODS = "resource/CallObjectMethods"; + public static final String SYSTEM_OUT_PRINTLN_CLASS = "resource/CallPrintln"; + public static final String INVOKEDYNAMIC_METHOD_CLASS = "resource/UseLambdaToForceInvokeDynamic"; + public static final String NATIVE_METHOD_CLASS = "resource/CallNative"; + public static final String BASIC_COLLECTIONS_CLASS = "resource/UseBasicCollections"; + public static final String FINALIZER_CLASS = "resource/UseFinalizer"; } diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java b/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java index 16cbda6e84..ac5e826fcf 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/TestUtils.java @@ -1,20 +1,23 @@ package net.corda.sandbox; -import net.corda.sandbox.costing.*; -import org.junit.*; +import net.corda.sandbox.costing.RuntimeCostAccounter; +import org.junit.Assert; -import javax.xml.bind.*; -import java.io.*; -import java.nio.file.FileSystem; +import javax.xml.bind.DatatypeConverter; +import java.io.IOException; +import java.io.InputStream; import java.nio.file.*; -import java.nio.file.attribute.*; -import java.util.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; public class TestUtils { - private static ArrayList tmpFileSystems = new ArrayList<>(); + private static List tmpFileSystems = new ArrayList<>(); private static Path jarFSDir = null; private static Path tmpdir; diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java b/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java index bcc5e94172..2dc5398086 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/WhitelistClassLoaderTest.java @@ -2,8 +2,6 @@ package net.corda.sandbox; import static org.junit.Assert.*; -import org.junit.Test; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java b/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java index 16b3972390..9d6b2d968e 100644 --- a/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java +++ b/experimental/sandbox/src/test/java/net/corda/sandbox/costing/SandboxedRewritingTest.java @@ -95,7 +95,7 @@ public class SandboxedRewritingTest { final Object o = clz.newInstance(); final Method m = clz.getMethod("makeObject"); final Object ret = m.invoke(o); - assertTrue(Object.class == ret.getClass()); + assertTrue(ret.getClass() == Object.class); checkAllCosts(1, 0, 2, 0); } diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt index 0190b9c2fa..fe4a7efbb4 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Literal.kt @@ -164,7 +164,7 @@ fun arrange(init: ContractBuilder.() -> Unit): Arrangement { data class Parameter(val initialValue: T) : Perceivable -fun variable(v: T) = Parameter(v) +fun variable(v: T) = Parameter(v) class RollOutBuilder(val startDate: LocalDate, val endDate: LocalDate, val frequency: Frequency, val vars: T) : ContractBuilder() { override fun final() = diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt index af72738962..d5f87515e8 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Perceivable.kt @@ -34,7 +34,7 @@ data class Const(val value: T) : Perceivable { if (value is BigDecimal && other.value is BigDecimal) { return this.value.compareTo(other.value) == 0 } - return value.equals(other.value) + return value == other.value } return false } @@ -82,7 +82,7 @@ data class ActorPerceivable(val actor: Party) : Perceivable fun signedBy(actor: Party) : Perceivable = ActorPerceivable(actor) fun signedByOneOf(actors: Collection): Perceivable = - if (actors.size == 0) + if (actors.isEmpty()) const(true) else actors.drop(1).fold(signedBy(actors.first())) { total, next -> total or signedBy(next) } diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt index 9ae517a824..3632bfa6a7 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/PrettyPrint.kt @@ -57,7 +57,7 @@ private class PrettyPrint(arr : Arrangement) { camelName += "_" + partyMap.size.toString() } - partyMap.put(party.owningKey, camelName) + partyMap[party.owningKey] = camelName usedPartyNames.add(camelName) return camelName diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt index 7abb5ed97d..529ee297cf 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/UniversalContract.kt @@ -116,12 +116,12 @@ class UniversalContract : Contract { val arr = replaceStartEnd(rollOut.template, start.toInstant(), nextStart.toInstant()) - if (nextStart < end) { + return if (nextStart < end) { // TODO: we may have to save original start date in order to roll out correctly val newRollOut = RollOut(nextStart, end, rollOut.frequency, rollOut.template) - return replaceNext(arr, newRollOut) + replaceNext(arr, newRollOut) } else { - return removeNext(arr) + removeNext(arr) } } @@ -132,7 +132,7 @@ class UniversalContract : Contract { is EndDate -> uncheckedCast(const(end)) is StartDate -> uncheckedCast(const(start)) is UnaryPlus -> UnaryPlus(replaceStartEnd(p.arg, start, end)) - is PerceivableOperation -> PerceivableOperation(replaceStartEnd(p.left, start, end), p.op, replaceStartEnd(p.right, start, end)) + is PerceivableOperation -> PerceivableOperation(replaceStartEnd(p.left, start, end), p.op, replaceStartEnd(p.right, start, end)) is Interest -> uncheckedCast(Interest(replaceStartEnd(p.amount, start, end), p.dayCountConvention, replaceStartEnd(p.interest, start, end), replaceStartEnd(p.start, start, end), replaceStartEnd(p.end, start, end))) is Fixing -> uncheckedCast(Fixing(p.source, replaceStartEnd(p.date, start, end), p.tenor)) is PerceivableAnd -> uncheckedCast(replaceStartEnd(p.left, start, end) and replaceStartEnd(p.right, start, end)) @@ -221,7 +221,7 @@ class UniversalContract : Contract { 1 -> { val outState = tx.outputsOfType().single() requireThat { - "output state must match action result state" using (arrangement.equals(outState.details)) + "output state must match action result state" using (arrangement == outState.details) "output state must match action result state" using (rest == zero) } } @@ -230,7 +230,7 @@ class UniversalContract : Contract { val allContracts = And(tx.outputsOfType().map { it.details }.toSet()) requireThat { - "output states must match action result state" using (arrangement.equals(allContracts)) + "output states must match action result state" using (arrangement == allContracts) } } @@ -250,7 +250,7 @@ class UniversalContract : Contract { "the transaction is signed by all liable parties" using (liableParties(outState.details).all { it in cmd.signers }) "output state does not reflect move command" using - (replaceParty(inState.details, value.from, value.to).equals(outState.details)) + (replaceParty(inState.details, value.from, value.to) == outState.details) } } is Commands.Fix -> { @@ -269,7 +269,7 @@ class UniversalContract : Contract { requireThat { "relevant fixing must be included" using unusedFixes.isEmpty() "output state does not reflect fix command" using - (expectedArr.equals(outState.details)) + (expectedArr == outState.details) } } else -> throw IllegalArgumentException("Unrecognised command") diff --git a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt index 65aee09b89..cca488f4c8 100644 --- a/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt +++ b/experimental/src/main/kotlin/net/corda/finance/contracts/universal/Util.kt @@ -20,7 +20,7 @@ private fun signingParties(perceivable: Perceivable) : ImmutableSet ImmutableSet.of() is TerminalEvent -> ImmutableSet.of( perceivable.reference ) is PerceivableComparison<*> -> ImmutableSet.of() // todo - else -> throw IllegalArgumentException("signingParties " + perceivable) + else -> throw IllegalArgumentException("signingParties $perceivable") } private fun liablePartiesVisitor(arrangement: Arrangement): ImmutableSet = @@ -33,7 +33,7 @@ private fun liablePartiesVisitor(arrangement: Arrangement): ImmutableSet(), { builder, k -> builder.addAll(liablePartiesVisitor(k)) }).build() is RollOut -> liablePartiesVisitor(arrangement.template) is Continuation -> ImmutableSet.of() - else -> throw IllegalArgumentException("liableParties " + arrangement) + else -> throw IllegalArgumentException("liableParties $arrangement") } private fun liablePartiesVisitor(action: Action): ImmutableSet { @@ -76,7 +76,7 @@ fun replaceParty(perceivable: Perceivable, from: Party, to: Party): Per is PerceivableAnd -> replaceParty(perceivable.left, from, to) and replaceParty(perceivable.right, from, to) is PerceivableOr -> replaceParty(perceivable.left, from, to) or replaceParty(perceivable.right, from, to) is TimePerceivable -> perceivable - else -> throw IllegalArgumentException("replaceParty " + perceivable) + else -> throw IllegalArgumentException("replaceParty $perceivable") } fun replaceParty(action: Action, from: Party, to: Party): Action = diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt index 599be9f0cb..51c5f3716c 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Caplet.kt @@ -67,7 +67,7 @@ class Caplet { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, stateFixed) output(UNIVERSAL_PROGRAM_ID, stateFinal) @@ -83,7 +83,7 @@ class Caplet { } @Test - fun `fixing`() { + fun fixing() { transaction { input(UNIVERSAL_PROGRAM_ID, stateStart) output(UNIVERSAL_PROGRAM_ID, stateFixed) diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt index b173ace1a4..0b3d22d311 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ContractDefinition.kt @@ -14,17 +14,14 @@ val highStreetBank = TestIdentity(CordaX500Name("MegaCorp", "London", "GB")).par val momAndPop = TestIdentity(CordaX500Name("MiniCorp", "London", "GB")).party val acmeCorporationHasDefaulted = TerminalEvent(acmeCorp, generateKeyPair().public) - // Currencies val USD: Currency = Currency.getInstance("USD") val GBP: Currency = Currency.getInstance("GBP") val EUR: Currency = Currency.getInstance("EUR") val KRW: Currency = Currency.getInstance("KRW") - class ContractDefinition { - val cds_contract = arrange { actions { acmeCorp may { @@ -40,7 +37,6 @@ class ContractDefinition { } } - val american_fx_option = arrange { actions { acmeCorp may { @@ -57,7 +53,6 @@ class ContractDefinition { } } - val european_fx_option = arrange { actions { acmeCorp may { @@ -80,7 +75,6 @@ class ContractDefinition { } } - /* @Test fun `builder problem - should not compile`() { val arr = arrange { @@ -128,5 +122,4 @@ class ContractDefinition { assertEquals(1, arr.actions.size) } } - } diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt index f5fa59ddf1..5017fa4ad9 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/FXSwap.kt @@ -60,7 +60,7 @@ class FXSwap { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, inState) output(UNIVERSAL_PROGRAM_ID, outState1) diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt index 12d71721ff..623a5b7074 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/RollOutTests.kt @@ -26,7 +26,6 @@ class RollOutTests { } } - val contract2 = arrange { rollOut("2016-09-01".ld, "2017-09-01".ld, Frequency.Monthly) { actions { @@ -157,7 +156,7 @@ class RollOutTests { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, stateStart) output(UNIVERSAL_PROGRAM_ID, stateStep1a) @@ -172,5 +171,4 @@ class RollOutTests { this.verifies() } } - } diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt index 5dfbdf28ec..245b1f5b9e 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/Swaption.kt @@ -72,10 +72,9 @@ class Swaption { } } - @Test @Ignore + @Test + @Ignore fun `pretty print`() { - println ( prettyPrint(contractInitial) ) + println(prettyPrint(contractInitial)) } - - } diff --git a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt index e8eb2cc71f..013dc08c91 100644 --- a/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt +++ b/experimental/src/test/kotlin/net/corda/finance/contracts/universal/ZeroCouponBond.kt @@ -46,7 +46,6 @@ class ZeroCouponBond { assertEquals(Zero(), Zero()) } - @Test fun `issue - signature`() { transaction { @@ -61,7 +60,7 @@ class ZeroCouponBond { } @Test - fun `execute`() { + fun execute() { transaction { input(UNIVERSAL_PROGRAM_ID, inState) output(UNIVERSAL_PROGRAM_ID, outState) @@ -105,21 +104,20 @@ class ZeroCouponBond { tweak { output(UNIVERSAL_PROGRAM_ID, outStateMove) command(acmeCorp.owningKey, - UniversalContract.Commands.Move(acmeCorp, momAndPop)) + UniversalContract.Commands.Move(acmeCorp, momAndPop)) this `fails with` "the transaction is signed by all liable parties" } tweak { output(UNIVERSAL_PROGRAM_ID, inState) command(listOf(acmeCorp.owningKey, momAndPop.owningKey, highStreetBank.owningKey), - UniversalContract.Commands.Move(acmeCorp, momAndPop)) + UniversalContract.Commands.Move(acmeCorp, momAndPop)) this `fails with` "output state does not reflect move command" } output(UNIVERSAL_PROGRAM_ID, outStateMove) command(listOf(acmeCorp.owningKey, momAndPop.owningKey, highStreetBank.owningKey), - UniversalContract.Commands.Move(acmeCorp, momAndPop)) + UniversalContract.Commands.Move(acmeCorp, momAndPop)) this.verifies() } } - } diff --git a/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java b/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java index 221e02427c..0cf5ce0085 100644 --- a/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java +++ b/finance/src/main/java/net/corda/finance/contracts/JavaCommercialPaper.java @@ -194,7 +194,7 @@ public class JavaCommercialPaper implements Contract { if (!cmd.getSigners().contains(input.getOwner().getOwningKey())) throw new IllegalStateException("Failed requirement: the transaction is signed by the owner of the CP"); - final Instant time = null == timeWindow + final Instant time = timeWindow == null ? null : timeWindow.getUntilTime(); final Amount> received = StateSumming.sumCashBy(tx.getOutputStates(), input.getOwner()); diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt b/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt index 7707bf71cf..5776137005 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/CommercialPaper.kt @@ -42,7 +42,7 @@ import java.util.* * to do this in the Apache BVal project). */ -val CP_PROGRAM_ID = "net.corda.finance.contracts.CommercialPaper" +const val CP_PROGRAM_ID = "net.corda.finance.contracts.CommercialPaper" // TODO: Generalise the notion of an owned instrument into a superclass/supercontract. Consider composition vs inheritance. class CommercialPaper : Contract { diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt b/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt index be6ada5492..b15c4b20fb 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/FinanceTypes.kt @@ -87,9 +87,8 @@ data class Tenor(val name: String) { } // Move date to the closest business day when it falls on a weekend/holiday val adjustedMaturityDate = calendar.applyRollConvention(maturityDate, DateRollConvention.ModifiedFollowing) - val daysToMaturity = BusinessCalendar.calculateDaysBetween(startDate, adjustedMaturityDate, DayCountBasisYear.Y360, DayCountBasisDay.DActual) - return daysToMaturity + return BusinessCalendar.calculateDaysBetween(startDate, adjustedMaturityDate, DayCountBasisYear.Y360, DayCountBasisDay.DActual) } override fun toString(): String = name diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt index d96b5b5c09..ba31fabc5b 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/GetBalances.kt @@ -46,7 +46,7 @@ private fun rowsToAmount(currency: Currency, rows: Vault.Page>) private fun rowsToBalances(rows: List): Map> { val balances = LinkedHashMap>() - for (index in 0..rows.size - 1 step 2) { + for (index in 0 until rows.size step 2) { val ccy = Currency.getInstance(rows[index + 1] as String) balances[ccy] = Amount(rows[index] as Long, ccy) } diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt index 998edb5326..73681e44b7 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Cash.kt @@ -46,7 +46,7 @@ import java.util.* */ class Cash : OnLedgerAsset() { override fun extractCommands(commands: Collection>): List> - = commands.select() + = commands.select() // DOCSTART 1 /** A state representing a cash claim against some party. */ @@ -159,7 +159,7 @@ class Cash : OnLedgerAsset() { // If we want to remove cash from the ledger, that must be signed for by the issuer. // A mis-signed or duplicated exit command will just be ignored here and result in the exit amount being zero. val exitKeys: Set = inputs.flatMap { it.exitKeys }.toSet() - val exitCommand = tx.commands.select(parties = null, signers = exitKeys).filter { it.value.amount.token == key }.singleOrNull() + val exitCommand = tx.commands.select(parties = null, signers = exitKeys).singleOrNull { it.value.amount.token == key } val amountExitingLedger = exitCommand?.value?.amount ?: Amount(0, Issued(issuer, currency)) requireThat { diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt index 677728874b..40d2ab3d4c 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/CommodityContract.kt @@ -146,7 +146,7 @@ class CommodityContract : OnLedgerAsset>): List> - = commands.select() + = commands.select() /** * Puts together an issuance transaction from the given template, that starts out being owned by the given pubkey. diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt index 23d905288f..38384d92d2 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/Obligation.kt @@ -1,10 +1,22 @@ package net.corda.finance.contracts.asset -import net.corda.core.contracts.* -import net.corda.finance.contracts.NetCommand -import net.corda.finance.contracts.NetType -import net.corda.finance.contracts.NettableState -import net.corda.finance.contracts.asset.Obligation.Lifecycle.NORMAL +import net.corda.core.contracts.Amount +import net.corda.core.contracts.CommandAndState +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.CommandWithParties +import net.corda.core.contracts.Contract +import net.corda.core.contracts.ContractClassName +import net.corda.core.contracts.ContractState +import net.corda.core.contracts.FungibleAsset +import net.corda.core.contracts.InsufficientBalanceException +import net.corda.core.contracts.Issued +import net.corda.core.contracts.MoveCommand +import net.corda.core.contracts.StateAndRef +import net.corda.core.contracts.TransactionState +import net.corda.core.contracts.TypeOnlyCommandData +import net.corda.core.contracts.requireThat +import net.corda.core.contracts.select +import net.corda.core.contracts.verifyMoveCommand import net.corda.core.crypto.SecureHash import net.corda.core.identity.AbstractParty import net.corda.core.identity.AnonymousParty @@ -16,6 +28,10 @@ import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.NonEmptySet import net.corda.core.utilities.seconds +import net.corda.finance.contracts.NetCommand +import net.corda.finance.contracts.NetType +import net.corda.finance.contracts.NettableState +import net.corda.finance.contracts.asset.Obligation.Lifecycle.NORMAL import net.corda.finance.utils.sumFungibleOrNull import net.corda.finance.utils.sumObligations import net.corda.finance.utils.sumObligationsOrNull @@ -159,12 +175,12 @@ class Obligation

: Contract { val netB = other.bilateralNetState require(netA == netB) { "net substates of the two state objects must be identical" } - if (obligor.owningKey == other.obligor.owningKey) { + return if (obligor.owningKey == other.obligor.owningKey) { // Both sides are from the same obligor to beneficiary - return copy(quantity = quantity + other.quantity) + copy(quantity = quantity + other.quantity) } else { // Issuer and beneficiary are backwards - return copy(quantity = quantity - other.quantity) + copy(quantity = quantity - other.quantity) } } @@ -265,7 +281,7 @@ class Obligation

: Contract { // If we want to remove obligations from the ledger, that must be signed for by the issuer. // A mis-signed or duplicated exit command will just be ignored here and result in the exit amount being zero. val exitKeys: Set = inputs.flatMap { it.exitKeys }.toSet() - val exitCommand = tx.commands.select>(parties = null, signers = exitKeys).filter { it.value.amount.token == key }.singleOrNull() + val exitCommand = tx.commands.select>(parties = null, signers = exitKeys).singleOrNull { it.value.amount.token == key } val amountExitingLedger = exitCommand?.value?.amount ?: Amount(0, Issued(issuer, terms)) requireThat { @@ -312,7 +328,7 @@ class Obligation

: Contract { groupingKey: Issued>) { val obligor = groupingKey.issuer.party val template = groupingKey.product - val inputAmount: Amount>> = inputs.sumObligationsOrNull

() ?: throw IllegalArgumentException("there is at least one obligation input for this group") + val inputAmount: Amount>> = inputs.sumObligationsOrNull() ?: throw IllegalArgumentException("there is at least one obligation input for this group") val outputAmount: Amount>> = outputs.sumObligationsOrZero(groupingKey) // Sum up all asset state objects that are moving and fulfil our requirements @@ -502,12 +518,14 @@ class Obligation

: Contract { */ @Suppress("unused") fun generateExit(tx: TransactionBuilder, amountIssued: Amount>>, - assetStates: List>>): Set - = OnLedgerAsset.generateExit(tx, amountIssued, assetStates, - deriveState = { state, amount, owner -> state.copy(data = state.data.withNewOwnerAndAmount(amount, owner)) }, - generateMoveCommand = { -> Commands.Move() }, - generateExitCommand = { amount -> Commands.Exit(amount) } - ) + assetStates: List>>): Set { + val changeOwner = assetStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amountIssued) + return OnLedgerAsset.generateExit(tx, amountIssued, assetStates, changeOwner, + deriveState = { state, amount, owner -> state.copy(data = state.data.withNewOwnerAndAmount(amount, owner)) }, + generateMoveCommand = { Commands.Move() }, + generateExitCommand = { amount -> Commands.Exit(amount) } + ) + } /** * Puts together an issuance transaction for the specified currency obligation amount that starts out being owned by @@ -568,7 +586,7 @@ class Obligation

: Contract { val signers = states.map { it.beneficiary }.union(states.map { it.obligor }).toSet() // Create a lookup table of the party that each public key represents. - states.map { it.obligor }.forEach { partyLookup.put(it.owningKey, it) } + states.map { it.obligor }.forEach { partyLookup[it.owningKey] = it } // Suppress compiler warning as 'groupStates' is an unused variable when destructuring 'groups'. @Suppress("UNUSED_VARIABLE") @@ -666,15 +684,15 @@ class Obligation

: Contract { val assetState = ref.state.data val amount = Amount(assetState.amount.quantity, assetState.amount.token.product) - if (obligationRemaining >= amount) { + obligationRemaining -= if (obligationRemaining >= amount) { tx.addOutputState(assetState.withNewOwnerAndAmount(assetState.amount, obligationOwner), PROGRAM_ID, notary) - obligationRemaining -= amount + amount } else { val change = Amount(obligationRemaining.quantity, assetState.amount.token) // Split the state in two, sending the change back to the previous beneficiary tx.addOutputState(assetState.withNewOwnerAndAmount(change, obligationOwner), PROGRAM_ID, notary) tx.addOutputState(assetState.withNewOwnerAndAmount(assetState.amount - change, assetState.owner), PROGRAM_ID, notary) - obligationRemaining -= Amount(0L, obligationRemaining.token) + Amount(0L, obligationRemaining.token) } assetSigners.add(assetState.owner) } diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt index eb0078d8ad..28c1751be4 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/OnLedgerAsset.kt @@ -30,7 +30,7 @@ data class PartyAndAmount(val party: AbstractParty, val amount: Amount< * At the same time, other contracts that just want assets and don't care much who is currently holding it can ignore * the issuer/depositRefs and just examine the amount fields. */ -abstract class OnLedgerAsset> : Contract { +abstract class OnLedgerAsset> : Contract { companion object { private val log = contextLogger() /** @@ -74,8 +74,6 @@ abstract class OnLedgerAsset> : C * * @param tx A builder, which may contain inputs, outputs and commands already. The relevant components needed * to move the cash will be added on top. - * @param amount How much currency to send. - * @param to a key of the recipient. * @param acceptableStates a list of acceptable input states to use. * @param payChangeTo party to pay any change to; this is normally a confidential identity of the calling * party. We use a new confidential identity here so that the recipient is not identifiable. @@ -230,11 +228,11 @@ abstract class OnLedgerAsset> : C @Throws(InsufficientBalanceException::class) @JvmStatic @Deprecated("Replaced with generateExit() which takes in a party to pay change to") - fun , T: Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, - assetStates: List>, - deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, - generateMoveCommand: () -> CommandData, - generateExitCommand: (Amount>) -> CommandData): Set { + fun , T : Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, + assetStates: List>, + deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, + generateMoveCommand: () -> CommandData, + generateExitCommand: (Amount>) -> CommandData): Set { val owner = assetStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amountIssued) return generateExit(tx, amountIssued, assetStates, owner, deriveState, generateMoveCommand, generateExitCommand) } @@ -252,16 +250,16 @@ abstract class OnLedgerAsset> : C */ @Throws(InsufficientBalanceException::class) @JvmStatic - fun , T: Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, - assetStates: List>, - payChangeTo: AbstractParty, - deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, - generateMoveCommand: () -> CommandData, - generateExitCommand: (Amount>) -> CommandData): Set { + fun , T : Any> generateExit(tx: TransactionBuilder, amountIssued: Amount>, + assetStates: List>, + payChangeTo: AbstractParty, + deriveState: (TransactionState, Amount>, AbstractParty) -> TransactionState, + generateMoveCommand: () -> CommandData, + generateExitCommand: (Amount>) -> CommandData): Set { require(assetStates.isNotEmpty()) { "List of states to exit cannot be empty." } val currency = amountIssued.token.product val amount = Amount(amountIssued.quantity, currency) - var acceptableCoins = assetStates.filter { ref -> ref.state.data.amount.token == amountIssued.token } + var acceptableCoins = assetStates.filter { (state) -> state.data.amount.token == amountIssued.token } tx.notary = acceptableCoins.firstOrNull()?.state?.notary // TODO: We should be prepared to produce multiple transactions exiting inputs from // different notaries, or at least group states by notary and take the set with the @@ -318,20 +316,20 @@ abstract class OnLedgerAsset> : C * @param amountIssued the amount to be exited, represented as a quantity of issued currency. * @param assetStates the asset states to take funds from. No checks are done about ownership of these states, it is * the responsibility of the caller to check that they do not exit funds held by others. - * @param payChangeTo party to pay any change to; this is normally a confidential identity of the calling - * party. * @return the public keys which must sign the transaction for it to be valid. */ @Throws(InsufficientBalanceException::class) @Deprecated("Replaced with generateExit() which takes in a party to pay change to") fun generateExit(tx: TransactionBuilder, amountIssued: Amount>, assetStates: List>): Set { + val changeOwner = assetStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amountIssued) return generateExit( tx, amountIssued, assetStates, + changeOwner, deriveState = { state, amount, owner -> deriveState(state, amount, owner) }, - generateMoveCommand = { -> generateMoveCommand() }, + generateMoveCommand = { generateMoveCommand() }, generateExitCommand = { amount -> generateExitCommand(amount) } ) } @@ -355,7 +353,7 @@ abstract class OnLedgerAsset> : C assetStates, payChangeTo, deriveState = { state, amount, owner -> deriveState(state, amount, owner) }, - generateMoveCommand = { -> generateMoveCommand() }, + generateMoveCommand = { generateMoveCommand() }, generateExitCommand = { amount -> generateExitCommand(amount) } ) } diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt index 8a7fea0725..9166a13e0c 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/AbstractCashSelection.kt @@ -8,6 +8,7 @@ import net.corda.core.crypto.SecureHash import net.corda.core.flows.FlowLogic import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party +import net.corda.core.internal.uncheckedCast import net.corda.core.node.ServiceHub import net.corda.core.node.services.StatesNotAvailableException import net.corda.core.utilities.* @@ -33,13 +34,13 @@ abstract class AbstractCashSelection { fun getInstance(metadata: () -> java.sql.DatabaseMetaData): AbstractCashSelection { return instance.get() ?: { - val _metadata = metadata() + val metadataLocal = metadata() val cashSelectionAlgos = ServiceLoader.load(AbstractCashSelection::class.java, this::class.java.classLoader).toList() - val cashSelectionAlgo = cashSelectionAlgos.firstOrNull { it.isCompatible(_metadata) } + val cashSelectionAlgo = cashSelectionAlgos.firstOrNull { it.isCompatible(metadataLocal) } cashSelectionAlgo?.let { instance.set(cashSelectionAlgo) cashSelectionAlgo - } ?: throw ClassNotFoundException("\nUnable to load compatible cash selection algorithm implementation for JDBC driver name '${_metadata.driverName}'." + + } ?: throw ClassNotFoundException("\nUnable to load compatible cash selection algorithm implementation for JDBC driver name '${metadataLocal.driverName}'." + "\nPlease specify an implementation in META-INF/services/${AbstractCashSelection::class.qualifiedName}." + "\nAvailable implementations: $cashSelectionAlgos") }.invoke() @@ -65,7 +66,6 @@ abstract class AbstractCashSelection { /** * A vendor specific query(ies) to gather Cash states that are available. - * @param statement The service hub to allow access to the database session * @param amount The amount of currency desired (ignoring issues, but specifying the currency) * @param lockId The FlowLogic.runId.uuid of the flow, which is used to soft reserve the states. * Also, previous outputs of the flow will be eligible as they are implicitly locked with this id until the flow completes. @@ -148,7 +148,7 @@ abstract class AbstractCashSelection { if (stateRefs.isNotEmpty()) { // TODO: future implementation to retrieve contract states from a Vault BLOB store - stateAndRefs.addAll(services.loadStates(stateRefs) as Collection>) + stateAndRefs.addAll(uncheckedCast(services.loadStates(stateRefs))) } val success = stateAndRefs.isNotEmpty() && totalPennies >= amount.quantity diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt index b0575e356b..497336acbd 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/asset/cash/selection/CashSelectionPostgreSQLImpl.kt @@ -70,7 +70,7 @@ class CashSelectionPostgreSQLImpl : AbstractCashSelection() { paramOffset += 1 } withIssuerRefs.map { it.bytes }.forEach { - statement.setBytes( 3 + paramOffset, it) + statement.setBytes(3 + paramOffset, it) paramOffset += 1 } statement.setLong(3 + paramOffset, amount.quantity) diff --git a/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt b/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt index 982a93c706..de2eb3bea2 100644 --- a/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt +++ b/finance/src/main/kotlin/net/corda/finance/contracts/math/Interpolators.kt @@ -100,7 +100,7 @@ class CubicSplineInterpolator(private val xs: DoubleArray, private val ys: Doubl val segmentMap = TreeMap() for (i in 0 until n) { val coefficients = doubleArrayOf(ys[i], b[i], c[i], d[i]) - segmentMap.put(xs[i], Polynomial(coefficients)) + segmentMap[xs[i]] = Polynomial(coefficients) } return SplineFunction(segmentMap) } diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt index a9e9abcb53..0edd0987e9 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashConfigDataFlow.kt @@ -33,7 +33,7 @@ class ConfigHolder(services: AppServiceHub) : SingletonSerializeAsToken() { // Warning!! You are about to see a major hack! val baseDirectory = services.declaredField("serviceHub").value .let { it.javaClass.getMethod("getConfiguration").apply { isAccessible = true }.invoke(it) } - .let { it.javaClass.getMethod("getBaseDirectory").apply { isAccessible = true }.invoke(it)} + .let { it.javaClass.getMethod("getBaseDirectory").apply { isAccessible = true }.invoke(it) } .let { it.javaClass.getMethod("toString").apply { isAccessible = true }.invoke(it) as String } var issuableCurrenciesValue: List @@ -52,7 +52,6 @@ class ConfigHolder(services: AppServiceHub) : SingletonSerializeAsToken() { } } - /** * Flow to obtain cash cordapp app configuration. */ diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt index eae18a7faf..dfd49938a9 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashExitFlow.kt @@ -15,9 +15,6 @@ import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.ProgressTracker import net.corda.finance.contracts.asset.Cash import net.corda.finance.contracts.asset.cash.selection.AbstractCashSelection -import net.corda.finance.flows.AbstractCashFlow.Companion.FINALISING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.finance.issuedBy import java.util.* @@ -53,10 +50,12 @@ class CashExitFlow(private val amount: Amount, .getInstance { serviceHub.jdbcSession().metaData } .unconsumedCashStatesForSpending(serviceHub, amount, setOf(issuer.party), builder.notary, builder.lockId, setOf(issuer.reference)) val signers = try { + val changeOwner = exitStates.map { it.state.data.owner }.toSet().firstOrNull() ?: throw InsufficientBalanceException(amount) Cash().generateExit( builder, amount.issuedBy(issuer), - exitStates) + exitStates, + changeOwner) } catch (e: InsufficientBalanceException) { throw CashException("Exiting more cash than exists", e) } diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt index 04a3c1cd90..95a58e8cfb 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueAndPaymentFlow.kt @@ -27,7 +27,7 @@ class CashIssueAndPaymentFlow(val amount: Amount, val anonymous: Boolean, val notary: Party, progressTracker: ProgressTracker) : AbstractCashFlow(progressTracker) { - constructor(amount: Amount, + constructor(amount: Amount, issueRef: OpaqueBytes, recipient: Party, anonymous: Boolean, diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt index 385767703e..39ef76823b 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashIssueFlow.kt @@ -9,9 +9,6 @@ import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.ProgressTracker import net.corda.finance.contracts.asset.Cash -import net.corda.finance.flows.AbstractCashFlow.Companion.FINALISING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.SIGNING_TX import net.corda.finance.issuedBy import java.util.* diff --git a/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt b/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt index f3afc3a107..dc71e54884 100644 --- a/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt +++ b/finance/src/main/kotlin/net/corda/finance/flows/CashPaymentFlow.kt @@ -11,10 +11,6 @@ import net.corda.core.serialization.CordaSerializable import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.ProgressTracker import net.corda.finance.contracts.asset.Cash -import net.corda.finance.flows.AbstractCashFlow.Companion.FINALISING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_ID -import net.corda.finance.flows.AbstractCashFlow.Companion.GENERATING_TX -import net.corda.finance.flows.AbstractCashFlow.Companion.SIGNING_TX import java.util.* /** diff --git a/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt b/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt index 3384878d9e..13df7822f0 100644 --- a/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt +++ b/finance/src/main/kotlin/net/corda/finance/plugin/FinanceJSONSupport.kt @@ -11,7 +11,7 @@ import com.fasterxml.jackson.databind.module.SimpleModule import net.corda.finance.contracts.BusinessCalendar import java.time.LocalDate -fun registerFinanceJSONMappers(objectMapper: ObjectMapper): Unit { +fun registerFinanceJSONMappers(objectMapper: ObjectMapper) { val financeModule = SimpleModule("finance").apply { addSerializer(BusinessCalendar::class.java, CalendarSerializer) addDeserializer(BusinessCalendar::class.java, CalendarDeserializer) diff --git a/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt b/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt index 5f3d7c8f37..c6eaa830c7 100644 --- a/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt +++ b/finance/src/main/kotlin/net/corda/finance/utils/StateSummingUtilities.kt @@ -62,13 +62,10 @@ fun Iterable.sumCommoditiesOrZero(currency: Issued) = * Sums the obligation states in the list, throwing an exception if there are none. All state objects in the * list are presumed to be nettable. */ -fun

Iterable.sumObligations(): Amount>> - = filterIsInstance>().map { it.amount }.sumOrThrow() +fun

Iterable.sumObligations(): Amount>> = filterIsInstance>().map { it.amount }.sumOrThrow() /** Sums the obligation states in the list, returning null if there are none. */ -fun

Iterable.sumObligationsOrNull(): Amount>>? - = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrNull() +fun

Iterable.sumObligationsOrNull(): Amount>>? = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrNull() /** Sums the obligation states in the list, returning zero of the given product if there are none. */ -fun

Iterable.sumObligationsOrZero(issuanceDef: Issued>): Amount>> - = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrZero(issuanceDef) +fun

Iterable.sumObligationsOrZero(issuanceDef: Issued>): Amount>> = filterIsInstance>().filter { it.lifecycle == Obligation.Lifecycle.NORMAL }.map { it.amount }.sumOrZero(issuanceDef) diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt index e3eb4f2779..2b6b79d9a6 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/DummyFungibleContract.kt @@ -19,7 +19,7 @@ import java.util.* class DummyFungibleContract : OnLedgerAsset() { override fun extractCommands(commands: Collection>): List> - = commands.select() + = commands.select() data class State( override val amount: Amount>, @@ -109,7 +109,7 @@ class DummyFungibleContract : OnLedgerAsset = inputs.flatMap { it.exitKeys }.toSet() - val exitCommand = tx.commands.select(parties = null, signers = exitKeys).filter { it.value.amount.token == key }.singleOrNull() + val exitCommand = tx.commands.select(parties = null, signers = exitKeys).singleOrNull { it.value.amount.token == key } val amountExitingLedger = exitCommand?.value?.amount ?: Amount(0, Issued(issuer, currency)) requireThat { diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt b/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt index e6d8d6417e..2834c8e20c 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/asset/ObligationTests.kt @@ -608,8 +608,8 @@ class ObligationTests { val futureTestTime = TEST_TX_TIME + 7.days transaction { attachments(Obligation.PROGRAM_ID) - input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` futureTestTime) - output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` futureTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) + input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at futureTestTime) + output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at futureTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) command(BOB_PUBKEY, Obligation.Commands.SetLifecycle(Lifecycle.DEFAULTED)) timeWindow(TEST_TX_TIME) this `fails with` "the due date has passed" @@ -619,8 +619,8 @@ class ObligationTests { ledgerServices.ledger(DUMMY_NOTARY) { transaction { attachments(Obligation.PROGRAM_ID) - input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` pastTestTime) - output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) `at` pastTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) + input(Obligation.PROGRAM_ID, oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at pastTestTime) + output(Obligation.PROGRAM_ID, "Alice's defaulted $1,000,000 obligation to Bob", (oneMillionDollars.OBLIGATION between Pair(ALICE, BOB) at pastTestTime).copy(lifecycle = Lifecycle.DEFAULTED)) command(BOB_PUBKEY, Obligation.Commands.SetLifecycle(Lifecycle.DEFAULTED)) timeWindow(TEST_TX_TIME) this.verifies() diff --git a/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt b/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt index 57d4de1b97..4534663689 100644 --- a/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt +++ b/finance/src/test/kotlin/net/corda/finance/contracts/math/InterpolatorsTest.kt @@ -31,13 +31,11 @@ class InterpolatorsTest { @Test fun `linear interpolator interpolates missing values correctly`() { val xs = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0) - val ys = xs val toInterpolate = doubleArrayOf(1.5, 2.5, 2.8, 3.3, 3.7, 4.3, 4.7) - val expected = toInterpolate - val interpolator = LinearInterpolator(xs, ys) + val interpolator = LinearInterpolator(xs, xs) val actual = toInterpolate.map { interpolator.interpolate(it) }.toDoubleArray() - Assert.assertArrayEquals(expected, actual, 0.01) + Assert.assertArrayEquals(toInterpolate, actual, 0.01) } @Test diff --git a/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt b/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt index 080212bc3e..3a732a6679 100644 --- a/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt +++ b/finance/src/test/kotlin/net/corda/finance/flows/CashIssueFlowTests.kt @@ -26,7 +26,7 @@ class CashIssueFlowTests { fun start() { mockNet = MockNetwork(servicePeerAllocationStrategy = RoundRobin(), cordappPackages = listOf("net.corda.finance.contracts.asset")) bankOfCordaNode = mockNet.createPartyNode(BOC_NAME) - bankOfCorda = bankOfCordaNode.info.identityFromX500Name(BOC_NAME) + bankOfCorda = bankOfCordaNode.info.identityFromX500Name(BOC_NAME) notary = mockNet.defaultNotaryIdentity } diff --git a/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt b/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt index f20c421ac1..fda31169e3 100644 --- a/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt +++ b/finance/src/test/kotlin/net/corda/finance/schemas/SampleCashSchemaV2.kt @@ -26,7 +26,7 @@ object SampleCashSchemaV2 : MappedSchema(schemaFamily = CashSchema.javaClass, ve @ElementCollection @Column(name = "participants") - @CollectionTable(name="cash_states_v2_participants", joinColumns = [JoinColumn(name = "output_index", referencedColumnName = "output_index"), JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")]) + @CollectionTable(name = "cash_states_v2_participants", joinColumns = [JoinColumn(name = "output_index", referencedColumnName = "output_index"), JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")]) override var participants: MutableSet? = null } } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt index 40333af921..4469d5885f 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/ArtemisTcpTransport.kt @@ -103,7 +103,7 @@ class ArtemisTcpTransport { direction: ConnectionDirection, hostAndPortList: List, config: SSLConfiguration?, - enableSSL: Boolean = true): List{ + enableSSL: Boolean = true): List { val tcpTransports = ArrayList(hostAndPortList.size) hostAndPortList.forEach { tcpTransports.add(tcpTransport(direction, it, config, enableSSL)) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt b/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt index 9392c176c7..1a482e1ff0 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/RPCApi.kt @@ -248,22 +248,22 @@ object RPCApi { } } -private val TAG_FIELD_NAME = "tag" -private val RPC_ID_FIELD_NAME = "rpc-id" -private val RPC_ID_TIMESTAMP_FIELD_NAME = "rpc-id-timestamp" -private val RPC_SESSION_ID_FIELD_NAME = "rpc-session-id" -private val RPC_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-session-id-timestamp" -private val RPC_EXTERNAL_ID_FIELD_NAME = "rpc-external-id" -private val RPC_EXTERNAL_ID_TIMESTAMP_FIELD_NAME = "rpc-external-id-timestamp" -private val RPC_EXTERNAL_SESSION_ID_FIELD_NAME = "rpc-external-session-id" -private val RPC_EXTERNAL_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-external-session-id-timestamp" -private val RPC_IMPERSONATED_ACTOR_ID = "rpc-impersonated-actor-id" -private val RPC_IMPERSONATED_ACTOR_STORE_ID = "rpc-impersonated-actor-store-id" -private val RPC_IMPERSONATED_ACTOR_OWNING_LEGAL_IDENTITY = "rpc-impersonated-actor-owningLegalIdentity" -private val DEDUPLICATION_IDENTITY_FIELD_NAME = "deduplication-identity" -private val OBSERVABLE_ID_FIELD_NAME = "observable-id" -private val OBSERVABLE_ID_TIMESTAMP_FIELD_NAME = "observable-id-timestamp" -private val METHOD_NAME_FIELD_NAME = "method-name" +private const val TAG_FIELD_NAME = "tag" +private const val RPC_ID_FIELD_NAME = "rpc-id" +private const val RPC_ID_TIMESTAMP_FIELD_NAME = "rpc-id-timestamp" +private const val RPC_SESSION_ID_FIELD_NAME = "rpc-session-id" +private const val RPC_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-session-id-timestamp" +private const val RPC_EXTERNAL_ID_FIELD_NAME = "rpc-external-id" +private const val RPC_EXTERNAL_ID_TIMESTAMP_FIELD_NAME = "rpc-external-id-timestamp" +private const val RPC_EXTERNAL_SESSION_ID_FIELD_NAME = "rpc-external-session-id" +private const val RPC_EXTERNAL_SESSION_ID_TIMESTAMP_FIELD_NAME = "rpc-external-session-id-timestamp" +private const val RPC_IMPERSONATED_ACTOR_ID = "rpc-impersonated-actor-id" +private const val RPC_IMPERSONATED_ACTOR_STORE_ID = "rpc-impersonated-actor-store-id" +private const val RPC_IMPERSONATED_ACTOR_OWNING_LEGAL_IDENTITY = "rpc-impersonated-actor-owningLegalIdentity" +private const val DEDUPLICATION_IDENTITY_FIELD_NAME = "deduplication-identity" +private const val OBSERVABLE_ID_FIELD_NAME = "observable-id" +private const val OBSERVABLE_ID_TIMESTAMP_FIELD_NAME = "observable-id-timestamp" +private const val METHOD_NAME_FIELD_NAME = "method-name" fun ClientMessage.replyId(): InvocationId { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt index 649dc967ae..3abfe24be4 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/ArtemisMessagingComponent.kt @@ -49,7 +49,6 @@ class ArtemisMessagingComponent { */ val bridgedCertificateSubject = SimpleString("sender-subject-name") - object Type { const val KEY = "corda_p2p_message_type" const val SESSION_INIT_VALUE = "session_init" @@ -128,5 +127,4 @@ class ArtemisMessagingComponent { override val queueName: String = "$P2P_PREFIX${identity.toStringShort()}" } - } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt index 385ae81eba..70d51246f4 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/SignedNodeInfo.kt @@ -60,6 +60,7 @@ inline fun NodeInfo.sign(signer: (PublicKey, SerializedBytes) -> Digit class NodeInfoAndSigned private constructor(val nodeInfo: NodeInfo, val signed: SignedNodeInfo) { constructor(nodeInfo: NodeInfo, signer: (PublicKey, SerializedBytes) -> DigitalSignature) : this(nodeInfo, nodeInfo.sign(signer)) constructor(signedNodeInfo: SignedNodeInfo) : this(signedNodeInfo.verified(), signedNodeInfo) + operator fun component1(): NodeInfo = nodeInfo operator fun component2(): SignedNodeInfo = signed } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt index 330b947a81..27477fa0d6 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/bridging/AMQPBridgeManager.kt @@ -37,7 +37,7 @@ import kotlin.concurrent.withLock * The Netty thread pool used by the AMQPBridges is also shared and managed by the AMQPBridgeManager. */ @VisibleForTesting -class AMQPBridgeManager(config: NodeSSLConfiguration, val artemisMessageClientFactory: () -> ArtemisSessionProvider) : BridgeManager { +class AMQPBridgeManager(config: NodeSSLConfiguration, private val artemisMessageClientFactory: () -> ArtemisSessionProvider) : BridgeManager { private val lock = ReentrantLock() private val bridgeNameToBridgeMap = mutableMapOf() diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt index 13ca193f4b..b5c8f09b2f 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/config/User.kt @@ -6,6 +6,6 @@ data class User( val password: String, val permissions: Set) { override fun toString(): String = "${javaClass.simpleName}($username, permissions=$permissions)" - @Deprecated("Use toConfig().root().unwrapped() instead") + @Deprecated("Use toConfig().root().unwrapped() instead", ReplaceWith("toConfig().root().unwrapped()")) fun toMap(): Map = toConfig().root().unwrapped() } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt index 6ee2cbdd01..6b2da4bfeb 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/network/NetworkMap.kt @@ -13,7 +13,6 @@ import net.corda.nodeapi.internal.crypto.X509Utilities import java.security.cert.X509Certificate import java.time.Instant - const val NETWORK_PARAMS_FILE_NAME = "network-parameters" const val NETWORK_PARAMS_UPDATE_FILE_NAME = "network-parameters-update" @@ -71,6 +70,7 @@ fun SignedDataWithCert.verifiedNetworkMapCert(rootCert: X509Certifi class NetworkMapAndSigned private constructor(val networkMap: NetworkMap, val signed: SignedNetworkMap) { constructor(networkMap: NetworkMap, signer: (SerializedBytes) -> DigitalSignatureWithCert) : this(networkMap, networkMap.signWithCert(signer)) constructor(signed: SignedNetworkMap) : this(signed.verified(), signed) + operator fun component1(): NetworkMap = networkMap operator fun component2(): SignedNetworkMap = signed } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt index 28939f1abf..31ca0cf166 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/CordaPersistence.kt @@ -258,9 +258,8 @@ fun rx.Observable.wrapWithDatabaseTransaction(db: CordaPersistence? /** Check if any nested cause is of [SQLException] type. */ private fun Throwable.hasSQLExceptionCause(): Boolean = - if (cause == null) - false - else if (cause is SQLException) - true - else - cause?.hasSQLExceptionCause() ?: false \ No newline at end of file + when (cause) { + null -> false + is SQLException -> true + else -> cause?.hasSQLExceptionCause() ?: false + } \ No newline at end of file diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt index acc995d3d1..365fe63bcc 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/persistence/HibernateConfiguration.kt @@ -156,7 +156,7 @@ class HibernateConfiguration( // A tweaked version of `org.hibernate.type.descriptor.java.PrimitiveByteArrayTypeDescriptor` that truncates logged messages. private object CordaPrimitiveByteArrayTypeDescriptor : PrimitiveByteArrayTypeDescriptor() { - private val LOG_SIZE_LIMIT = 1024 + private const val LOG_SIZE_LIMIT = 1024 override fun extractLoggableRepresentation(value: ByteArray?): String { return if (value == null) { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt index 2b7f767c5d..c3a3fcce91 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/engine/ConnectionStateMachine.kt @@ -62,6 +62,7 @@ internal class ConnectionStateMachine(serverMode: Boolean, transport = Engine.transport() transport.idleTimeout = IDLE_TIMEOUT transport.context = connection + @Suppress("UsePropertyAccessSyntax") transport.setEmitFlowEventOnSend(true) connection.collect(collector) val sasl = transport.sasl() diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt index d8ead67682..2581dbfd76 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/protonwrapper/netty/AMQPServer.kt @@ -90,7 +90,7 @@ class AMQPServer(val hostName: String, parent.password, parent.trace, { - parent.clientChannels.put(it.first.remoteAddress(), it.first) + parent.clientChannels[it.first.remoteAddress()] = it.first parent._onConnection.onNext(it.second) }, { @@ -194,5 +194,4 @@ class AMQPServer(val hostName: String, private val _onConnection = PublishSubject.create().toSerialized() val onConnection: Observable get() = _onConnection - } \ No newline at end of file diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt index e7e942c595..071f3e3ec0 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/ByteBufferStreams.kt @@ -1,4 +1,5 @@ @file:JvmName("ByteBufferStreams") + package net.corda.nodeapi.internal.serialization import net.corda.core.internal.LazyPool @@ -10,9 +11,9 @@ import java.nio.ByteBuffer import kotlin.math.min internal val serializeOutputStreamPool = LazyPool( - clear = ByteBufferOutputStream::reset, - shouldReturnToPool = { it.size() < 256 * 1024 }, // Discard if it grew too large - newInstance = { ByteBufferOutputStream(64 * 1024) }) + clear = ByteBufferOutputStream::reset, + shouldReturnToPool = { it.size() < 256 * 1024 }, // Discard if it grew too large + newInstance = { ByteBufferOutputStream(64 * 1024) }) internal fun byteArrayOutput(task: (ByteBufferOutputStream) -> T): ByteArray { return serializeOutputStreamPool.run { underlying -> diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt index 8451ac62b2..390d6b3624 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/SerializeAsTokenContextImpl.kt @@ -46,7 +46,7 @@ class SerializeAsTokenContextImpl(override val serviceHub: ServiceHub, init: Ser if (className !in classNameToSingleton) { // Only allowable if we are in SerializeAsTokenContext init (readOnly == false) if (readOnly) { - throw UnsupportedOperationException("Attempt to write token for lazy registered ${className}. All tokens should be registered during context construction.") + throw UnsupportedOperationException("Attempt to write token for lazy registered $className. All tokens should be registered during context construction.") } classNameToSingleton[className] = toBeTokenized } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt index f3ddd3947f..e0672e64a3 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPPrimitiveSerializer.kt @@ -12,7 +12,7 @@ import java.lang.reflect.Type * [ByteArray] is automatically marshalled to/from the Proton-J wrapper, [Binary]. */ class AMQPPrimitiveSerializer(clazz: Class<*>) : AMQPSerializer { - override val typeDescriptor = Symbol.valueOf(SerializerFactory.primitiveTypeName(clazz)!!) + override val typeDescriptor = Symbol.valueOf(SerializerFactory.primitiveTypeName(clazz)!!)!! override val type: Type = clazz // NOOP since this is a primitive type. diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt index f845d5348c..8811a63eac 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializationScheme.kt @@ -68,6 +68,7 @@ abstract class AbstractAMQPSerializationScheme( val List.customSerializers get() = flatMap { it.serializationCustomSerializers }.toSet() } + // Parameter "context" is unused directy but passed in by reflection. Removing it will cause failures. private fun registerCustomSerializers(context: SerializationContext, factory: SerializerFactory) { with(factory) { register(publicKeySerializer) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt index 30d6052211..884c6b057e 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPSerializerFactories.kt @@ -1,4 +1,5 @@ @file:JvmName("AMQPSerializerFactories") + package net.corda.nodeapi.internal.serialization.amqp import net.corda.core.serialization.SerializationContext diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt index dee5d8e425..41cae57a92 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/AMQPStreams.kt @@ -1,4 +1,5 @@ @file:JvmName("AMQPStreams") + package net.corda.nodeapi.internal.serialization.amqp import net.corda.nodeapi.internal.serialization.ByteBufferInputStream diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt index e16872809e..a6be5082a9 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ArraySerializer.kt @@ -32,7 +32,7 @@ open class ArraySerializer(override val type: Type, factory: SerializerFactory) "${type.componentType().typeName}$arrayType" } - override val typeDescriptor by lazy { + override val typeDescriptor: Symbol by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") } internal val elementType: Type by lazy { type.componentType() } @@ -95,7 +95,7 @@ abstract class PrimArraySerializer(type: Type, factory: SerializerFactory) : Arr companion object { // We don't need to handle the unboxed byte type as that is coercible to a byte array, but // the other 7 primitive types we do - val primTypes: Map PrimArraySerializer> = mapOf( + private val primTypes: Map PrimArraySerializer> = mapOf( IntArray::class.java to { f -> PrimIntArraySerializer(f) }, CharArray::class.java to { f -> PrimCharArraySerializer(f) }, BooleanArray::class.java to { f -> PrimBooleanArraySerializer(f) }, diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt index 9c41c37fe3..2c2604710e 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CollectionSerializer.kt @@ -14,10 +14,10 @@ import kotlin.collections.LinkedHashSet /** * Serialization / deserialization of predefined set of supported [Collection] types covering mostly [List]s and [Set]s. */ -class CollectionSerializer(val declaredType: ParameterizedType, factory: SerializerFactory) : AMQPSerializer { +class CollectionSerializer(private val declaredType: ParameterizedType, factory: SerializerFactory) : AMQPSerializer { override val type: Type = declaredType as? DeserializedParameterizedType ?: DeserializedParameterizedType.make(SerializerFactory.nameForType(declaredType)) - override val typeDescriptor by lazy { + override val typeDescriptor: Symbol by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") } @@ -53,10 +53,8 @@ class CollectionSerializer(val declaredType: ParameterizedType, factory: Seriali (declaredType as? ParameterizedType) ?: DeserializedParameterizedType(collectionClass, arrayOf(SerializerFactory.AnyType)) - private fun findMostSuitableCollectionType(actualClass: Class<*>): Class> = supportedTypes.keys.findLast { it.isAssignableFrom(actualClass) }!! - } private val concreteBuilder: (List<*>) -> Collection<*> = findConcreteType(declaredType.rawType as Class<*>) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt index bb40f19454..4f0b6f065f 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CorDappCustomSerializer.kt @@ -59,7 +59,7 @@ class CorDappCustomSerializer( override val type = types[CORDAPP_TYPE] val proxyType = types[PROXY_TYPE] - override val typeDescriptor = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(type)}") + override val typeDescriptor: Symbol = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(type)}") val descriptor: Descriptor = Descriptor(typeDescriptor) private val proxySerializer: ObjectSerializer by lazy { ObjectSerializer(proxyType, factory) } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt index 631cfc1bf6..ccdd67a718 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/CustomSerializer.kt @@ -64,7 +64,7 @@ abstract class CustomSerializer : AMQPSerializer, SerializerFor { override fun isSerializerFor(clazz: Class<*>): Boolean = clazz == this.clazz override val type: Type get() = clazz - override val typeDescriptor by lazy { + override val typeDescriptor: Symbol by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${SerializerFingerPrinter().fingerprintForDescriptors(superClassSerializer.typeDescriptor.toString(), nameForType(clazz))}") } private val typeNotation: TypeNotation = RestrictedType( @@ -100,7 +100,7 @@ abstract class CustomSerializer : AMQPSerializer, SerializerFor { */ abstract class CustomSerializerImp(protected val clazz: Class, protected val withInheritance: Boolean) : CustomSerializer() { override val type: Type get() = clazz - override val typeDescriptor = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(clazz)}") + override val typeDescriptor: Symbol = Symbol.valueOf("$DESCRIPTOR_DOMAIN:${nameForType(clazz)}") override fun writeClassInfo(output: SerializationOutput) {} override val descriptor: Descriptor = Descriptor(typeDescriptor) override fun isSerializerFor(clazz: Class<*>): Boolean = if (withInheritance) this.clazz.isAssignableFrom(clazz) else this.clazz == clazz diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt index edbf8843cf..20d577ee1d 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializationInput.kt @@ -8,7 +8,6 @@ import net.corda.core.utilities.ByteSequence import net.corda.nodeapi.internal.serialization.* import org.apache.qpid.proton.amqp.Binary import org.apache.qpid.proton.amqp.DescribedType -import org.apache.qpid.proton.amqp.UnsignedByte import org.apache.qpid.proton.amqp.UnsignedInteger import org.apache.qpid.proton.codec.Data import java.io.InputStream @@ -32,28 +31,6 @@ class DeserializationInput @JvmOverloads constructor(private val serializerFacto private val objectHistory: MutableList = mutableListOf() companion object { - private const val BYTES_NEEDED_TO_PEEK: Int = 23 - - fun peekSize(bytes: ByteArray): Int { - // There's an 8 byte header, and then a 0 byte plus descriptor followed by constructor - val eighth = bytes[8].toInt() - check(eighth == 0x0) { "Expected to find a descriptor in the AMQP stream" } - // We should always have an Envelope, so the descriptor should be a 64-bit long (0x80) - val ninth = UnsignedByte.valueOf(bytes[9]).toInt() - check(ninth == 0x80) { "Expected to find a ulong in the AMQP stream" } - // Skip 8 bytes - val eighteenth = UnsignedByte.valueOf(bytes[18]).toInt() - check(eighteenth == 0xd0 || eighteenth == 0xc0) { "Expected to find a list8 or list32 in the AMQP stream" } - val size = if (eighteenth == 0xc0) { - // Next byte is size - UnsignedByte.valueOf(bytes[19]).toInt() - 3 // Minus three as PEEK_SIZE assumes 4 byte unsigned integer. - } else { - // Next 4 bytes is size - UnsignedByte.valueOf(bytes[19]).toInt().shl(24) + UnsignedByte.valueOf(bytes[20]).toInt().shl(16) + UnsignedByte.valueOf(bytes[21]).toInt().shl(8) + UnsignedByte.valueOf(bytes[22]).toInt() - } - return size + BYTES_NEEDED_TO_PEEK - } - @VisibleForTesting @Throws(NotSerializableException::class) fun withDataBytes(byteSequence: ByteSequence, encodingWhitelist: EncodingWhitelist, task: (ByteBuffer) -> T): T { @@ -140,13 +117,12 @@ class DeserializationInput @JvmOverloads constructor(private val serializerFacto envelope) } - internal fun readObjectOrNull(obj: Any?, schema: SerializationSchemas, type: Type, context: SerializationContext, - offset: Int = 0 + internal fun readObjectOrNull(obj: Any?, schema: SerializationSchemas, type: Type, context: SerializationContext ): Any? { - return if (obj == null) null else readObject(obj, schema, type, context, offset) + return if (obj == null) null else readObject(obj, schema, type, context) } - internal fun readObject(obj: Any, schemas: SerializationSchemas, type: Type, context: SerializationContext, debugIndent: Int = 0): Any = + internal fun readObject(obj: Any, schemas: SerializationSchemas, type: Type, context: SerializationContext): Any = if (obj is DescribedType && ReferencedObject.DESCRIPTOR == obj.descriptor) { // It must be a reference to an instance that has already been read, cheaply and quickly returning it by reference. val objectIndex = (obj.described as UnsignedInteger).toInt() diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt index 729a98ded2..1a9b05a9c1 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/DeserializedParameterizedType.kt @@ -28,7 +28,7 @@ class DeserializedParameterizedType(private val rawType: Class<*>, private val p private val _typeName: String = makeTypeName() private fun makeTypeName(): String { - val paramsJoined = params.map { it.typeName }.joinToString(", ") + val paramsJoined = params.joinToString(", ") { it.typeName } return "${rawType.name}<$paramsJoined>" } @@ -145,14 +145,14 @@ class DeserializedParameterizedType(private val rawType: Class<*>, private val p } override fun equals(other: Any?): Boolean { - if (other is ParameterizedType) { + return if (other is ParameterizedType) { if (this === other) { - return true + true } else { - return this.ownerType == other.ownerType && this.rawType == other.rawType && Arrays.equals(this.actualTypeArguments, other.actualTypeArguments) + this.ownerType == other.ownerType && this.rawType == other.rawType && Arrays.equals(this.actualTypeArguments, other.actualTypeArguments) } } else { - return false + false } } } \ No newline at end of file diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt index a83e4744cf..28a72d984a 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/EvolutionSerializer.kt @@ -91,7 +91,7 @@ abstract class EvolutionSerializer( val constructorArgs = arrayOfNulls(constructor.parameters.size) constructor.parameters.withIndex().forEach { - readersAsSerialized.get(it.value.name!!)?.apply { + readersAsSerialized[it.value.name!!]?.apply { this.resultsIndex = it.index } ?: if (!it.value.type.isMarkedNullable) { throw NotSerializableException( diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt index 79ee00f5e5..086b8b1d27 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinter.kt @@ -94,7 +94,7 @@ class SerializerFingerPrinter : FingerPrinter { // serialise the object in the first place (and thus the cache lookup fails). This is also // true of Any, where we need Example and Example to have the same fingerprint return if ((type in alreadySeen) - && (type !is SerializerFactory.AnyType) + && (type !== SerializerFactory.AnyType) && (type !is TypeVariable<*>) && (type !is WildcardType)) { hasher.putUnencodedChars(ALREADY_SEEN_HASH) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt index f9158b74c7..59d2d7f2d0 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/ObjectSerializer.kt @@ -23,7 +23,7 @@ open class ObjectSerializer(val clazz: Type, factory: SerializerFactory) : AMQPS private val logger = contextLogger() } - open internal val propertySerializers: PropertySerializers by lazy { + internal open val propertySerializers: PropertySerializers by lazy { propertiesForSerialization(kotlinConstructor, clazz, factory) } @@ -32,12 +32,12 @@ open class ObjectSerializer(val clazz: Type, factory: SerializerFactory) : AMQPS private val typeName = nameForType(clazz) override val typeDescriptor = Symbol.valueOf( - "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") + "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}")!! // We restrict to only those annotated or whitelisted private val interfaces = interfacesForSerialization(clazz, factory) - open internal val typeNotation: TypeNotation by lazy { + internal open val typeNotation: TypeNotation by lazy { CompositeType(typeName, null, generateProvides(), Descriptor(typeDescriptor), generateFields()) } diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt index 03f99f35e7..0b6dd5cb0f 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/PropertySerializers.kt @@ -79,7 +79,7 @@ class PrivatePropertyReader(val field: Field, parentType: Type) : PropertyReader // So this used to report as an error, but given we serialise exceptions all the time it // provides for very scary log files so move this to trace level loggerFor().let { logger -> - logger.trace("Using kotlin introspection on internal type ${field}") + logger.trace("Using kotlin introspection on internal type $field") logger.trace("Unexpected internal Kotlin error", e) } true diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt index 7a952e5310..ad47301f28 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutput.kt @@ -124,18 +124,18 @@ open class SerializationOutput @JvmOverloads constructor( // assigned to them first as they will be first read from the stream on receiving end. // Skip for primitive types as they are too small and overhead of referencing them will be much higher than their content if (suitableForObjectReference(obj.javaClass)) { - objectHistory.put(obj, objectHistory.size) + objectHistory[obj] = objectHistory.size } } else { data.writeReferencedObject(ReferencedObject(retrievedRefCount)) } } - open internal fun writeTypeNotations(vararg typeNotation: TypeNotation): Boolean { + internal open fun writeTypeNotations(vararg typeNotation: TypeNotation): Boolean { return schemaHistory.addAll(typeNotation) } - open internal fun requireSerializer(type: Type) { + internal open fun requireSerializer(type: Type) { if (type != SerializerFactory.AnyType && type != Object::class.java) { val serializer = serializerFactory.get(null, type) if (serializer !in serializerHistory) { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt index 89a636d5b8..b1e27f8b36 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializerFactory.kt @@ -144,7 +144,7 @@ open class SerializerFactory( return if (actualClass.typeParameters.isNotEmpty()) { // The actual class can never have type variables resolved, due to the JVM's use of type erasure, so let's try and resolve them // Search for declared type in the inheritance hierarchy and then see if that fills in all the variables - val implementationChain: List? = findPathToDeclared(actualClass, declaredType, mutableListOf()) + val implementationChain: List? = findPathToDeclared(actualClass, declaredType, mutableListOf()) if (implementationChain != null) { val start = implementationChain.last() val rest = implementationChain.dropLast(1).drop(1) @@ -305,6 +305,7 @@ open class SerializerFactory( return if (declaredSuperClass == null || !customSerializer.isSerializerFor(declaredSuperClass) || !customSerializer.revealSubclassesInSchema) { + @Suppress("UNCHECKED_CAST") customSerializer as? AMQPSerializer } else { // Make a subclass serializer for the subclass and return that... diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt index e4d5869f06..59bd371a33 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/SingletonSerializer.kt @@ -12,7 +12,7 @@ import java.lang.reflect.Type */ class SingletonSerializer(override val type: Class<*>, val singleton: Any, factory: SerializerFactory) : AMQPSerializer { override val typeDescriptor = Symbol.valueOf( - "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}") + "$DESCRIPTOR_DOMAIN:${factory.fingerPrinter.fingerprint(type)}")!! private val interfaces = interfacesForSerialization(type, factory) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt index 829aac7b58..edb7f2711d 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/amqp/TransformsSchema.kt @@ -72,7 +72,7 @@ abstract class Transform : DescribedType { */ class UnknownTransform : Transform() { companion object : DescribedTypeConstructor { - val typeName = "UnknownTransform" + const val typeName = "UnknownTransform" override fun newInstance(obj: Any?) = UnknownTransform() @@ -90,7 +90,7 @@ class UnknownTransform : Transform() { */ class UnknownTestTransform(val a: Int, val b: Int, val c: Int) : Transform() { companion object : DescribedTypeConstructor { - val typeName = "UnknownTest" + const val typeName = "UnknownTest" override fun newInstance(obj: Any?): UnknownTestTransform { val described = obj as List<*> @@ -117,7 +117,7 @@ class EnumDefaultSchemaTransform(val old: String, val new: String) : Transform() /** * Value encoded into the schema that identifies a transform as this type */ - val typeName = "EnumDefault" + const val typeName = "EnumDefault" override fun newInstance(obj: Any?): EnumDefaultSchemaTransform { val described = obj as List<*> @@ -154,7 +154,7 @@ class RenameSchemaTransform(val from: String, val to: String) : Transform() { /** * Value encoded into the schema that identifies a transform as this type */ - val typeName = "Rename" + const val typeName = "Rename" override fun newInstance(obj: Any?): RenameSchemaTransform { val described = obj as List<*> @@ -213,9 +213,7 @@ data class TransformsSchema(val types: Map')) { this.substring(0, this.indexOf('<')) } else this -fun AMQPField.getTypeAsClass(classloader: ClassLoader) = typeStrToType[Pair(type, mandatory)] ?: when (type) { +fun AMQPField.getTypeAsClass(classloader: ClassLoader) = (typeStrToType[Pair(type, mandatory)] ?: when (type) { "string" -> String::class.java "binary" -> ByteArray::class.java "*" -> if (requires.isEmpty()) Any::class.java else { classloader.loadClass(requires[0].stripGenerics()) } else -> classloader.loadClass(type.stripGenerics()) -} +})!! fun AMQPField.validateType(classloader: ClassLoader) = when (type) { diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt index c821509b84..13ecd2682c 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/CordaClosureSerializer.kt @@ -6,7 +6,7 @@ import com.esotericsoftware.kryo.serializers.ClosureSerializer import java.io.Serializable object CordaClosureSerializer : ClosureSerializer() { - val ERROR_MESSAGE = "Unable to serialize Java Lambda expression, unless explicitly declared e.g., Runnable r = (Runnable & Serializable) () -> System.out.println(\"Hello world!\");" + const val ERROR_MESSAGE = "Unable to serialize Java Lambda expression, unless explicitly declared e.g., Runnable r = (Runnable & Serializable) () -> System.out.println(\"Hello world!\");" override fun write(kryo: Kryo, output: Output, target: Any) { if (!isSerializable(target)) { @@ -21,7 +21,7 @@ object CordaClosureSerializer : ClosureSerializer() { } object CordaClosureBlacklistSerializer : ClosureSerializer() { - val ERROR_MESSAGE = "Java 8 Lambda expressions are not supported for serialization." + const val ERROR_MESSAGE = "Java 8 Lambda expressions are not supported for serialization." override fun write(kryo: Kryo, output: Output, target: Any) { throw IllegalArgumentException(ERROR_MESSAGE) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt index d41e526855..bf400d9e36 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/DefaultKryoCustomizer.kt @@ -216,6 +216,7 @@ object DefaultKryoCustomizer { if (kryo.serializationContext() != null) { val attachmentHash = SecureHash.SHA256(input.readBytes(32)) val contract = input.readString() + @Suppress("UNCHECKED_CAST") val additionalContracts = kryo.readClassAndObject(input) as Set val uploader = input.readString() val context = kryo.serializationContext()!! @@ -233,6 +234,7 @@ object DefaultKryoCustomizer { } else { val attachment = GeneratedAttachment(input.readBytesWithLength()) val contract = input.readString() + @Suppress("UNCHECKED_CAST") val additionalContracts = kryo.readClassAndObject(input) as Set val uploader = input.readString() return ContractAttachment(attachment, contract, additionalContracts, uploader) diff --git a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt index 977f4077fc..bd29023e63 100644 --- a/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt +++ b/node-api/src/main/kotlin/net/corda/nodeapi/internal/serialization/kryo/KryoStreams.kt @@ -1,4 +1,5 @@ @file:JvmName("KryoStreams") + package net.corda.nodeapi.internal.serialization.kryo import com.esotericsoftware.kryo.io.Input diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java index c798548987..db8da10b45 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/ForbiddenLambdaSerializationTests.java @@ -43,7 +43,7 @@ public final class ForbiddenLambdaSerializationTests { assertThat(throwable).isNotNull(); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); if (ctx != SerializationContext.UseCase.RPCServer && ctx != SerializationContext.UseCase.Storage) { - assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.INSTANCE.getERROR_MESSAGE()); + assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.ERROR_MESSAGE); } else { assertThat(throwable).hasMessageContaining("RPC not allowed to deserialise internal classes"); } @@ -65,7 +65,7 @@ public final class ForbiddenLambdaSerializationTests { assertThat(throwable).isInstanceOf(IllegalArgumentException.class); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); if (ctx != SerializationContext.UseCase.RPCServer && ctx != SerializationContext.UseCase.Storage) { - assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.INSTANCE.getERROR_MESSAGE()); + assertThat(throwable).hasMessage(CordaClosureBlacklistSerializer.ERROR_MESSAGE); } else { assertThat(throwable).hasMessageContaining("RPC not allowed to deserialise internal classes"); } diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java index 6482240ba9..4da40c0239 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/LambdaCheckpointSerializationTest.java @@ -51,7 +51,7 @@ public final class LambdaCheckpointSerializationTest { assertThat(throwable).isNotNull(); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); - assertThat(throwable).hasMessage(CordaClosureSerializer.INSTANCE.getERROR_MESSAGE()); + assertThat(throwable).hasMessage(CordaClosureSerializer.ERROR_MESSAGE); } private SerializedBytes serialize(final T target) { diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java index 24d393b336..985abc619d 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/ErrorMessageTests.java @@ -2,7 +2,6 @@ package net.corda.nodeapi.internal.serialization.amqp; import net.corda.nodeapi.internal.serialization.AllWhitelist; import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationContext; -import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationContextKt; import org.assertj.core.api.Assertions; import org.junit.Ignore; import org.junit.Test; diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java index 80621a0a99..9a0162422a 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaNestedClassesTests.java @@ -1,7 +1,6 @@ package net.corda.nodeapi.internal.serialization.amqp; import com.google.common.collect.ImmutableList; -import kotlin.Suppress; import net.corda.core.contracts.ContractState; import net.corda.core.identity.AbstractParty; import net.corda.core.serialization.SerializedBytes; diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java index f32254110c..66819afa99 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/JavaSerializationOutputTests.java @@ -1,21 +1,16 @@ package net.corda.nodeapi.internal.serialization.amqp; -import com.google.common.collect.ImmutableList; -import net.corda.core.contracts.ContractState; -import net.corda.core.identity.AbstractParty; import net.corda.core.serialization.ConstructorForDeserialization; import net.corda.nodeapi.internal.serialization.AllWhitelist; import net.corda.core.serialization.SerializedBytes; import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationContext; import org.apache.qpid.proton.codec.DecoderImpl; import org.apache.qpid.proton.codec.EncoderImpl; -import org.jetbrains.annotations.NotNull; import org.junit.Test; import javax.annotation.Nonnull; import java.io.NotSerializableException; import java.nio.ByteBuffer; -import java.util.List; import java.util.Objects; import static org.junit.Assert.assertTrue; diff --git a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java index 126ff34f71..30402c3ea0 100644 --- a/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java +++ b/node-api/src/test/java/net/corda/nodeapi/internal/serialization/amqp/testutils/TestSerializationContext.java @@ -11,7 +11,7 @@ import java.util.Map; public class TestSerializationContext { - static private Map serializationProperties = new HashMap(); + private static Map serializationProperties = new HashMap<>(); public static SerializationContext testSerializationContext = new SerializationContextImpl( ByteSequence.of(new byte[] { 'c', 'o', 'r', 'd', 'a', (byte)0, (byte)0, (byte)1}), diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt index 19c07d1efd..b43207c56b 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderStaticContractTests.kt @@ -36,7 +36,7 @@ class AttachmentsClassLoaderStaticContractTests { class AttachmentDummyContract : Contract { companion object { - private val ATTACHMENT_PROGRAM_ID = "net.corda.nodeapi.internal.AttachmentsClassLoaderStaticContractTests\$AttachmentDummyContract" + private const val ATTACHMENT_PROGRAM_ID = "net.corda.nodeapi.internal.AttachmentsClassLoaderStaticContractTests\$AttachmentDummyContract" } data class State(val magicNumber: Int = 0) : ContractState { diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt index 7ac2ca9d4b..ad5ce974dd 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/AttachmentsClassLoaderTests.kt @@ -10,7 +10,12 @@ import net.corda.core.internal.declaredField import net.corda.core.internal.toWireTransaction import net.corda.core.node.ServiceHub import net.corda.core.node.services.AttachmentStorage -import net.corda.core.serialization.* +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.MissingAttachmentsException +import net.corda.core.serialization.SerializationContext +import net.corda.core.serialization.SerializationFactory +import net.corda.core.serialization.deserialize +import net.corda.core.serialization.serialize import net.corda.core.utilities.ByteSequence import net.corda.core.utilities.OpaqueBytes import net.corda.node.internal.cordapp.CordappLoader @@ -28,10 +33,12 @@ import net.corda.testing.internal.kryoSpecific import net.corda.testing.internal.rigorousMock import net.corda.testing.services.MockAttachmentStorage import org.apache.commons.io.IOUtils -import org.junit.Assert.* +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test -import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.net.URL import java.net.URLClassLoader @@ -125,6 +132,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `test overlapping file exception`() { val storage = attachments val att0 = attachmentId @@ -137,7 +145,8 @@ class AttachmentsClassLoaderTests { } @Test - fun `basic`() { + @Suppress("DEPRECATION") + fun basic() { val storage = attachments val att0 = attachmentId val att1 = storage.importAttachment(fakeAttachment("file1.txt", "some data").inputStream()) @@ -149,6 +158,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `Check platform independent path handling in attachment jars`() { val storage = MockAttachmentStorage() @@ -169,6 +179,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `loading class AnotherDummyContract`() { val storage = attachments val att0 = attachmentId @@ -190,6 +201,7 @@ class AttachmentsClassLoaderTests { } @Test + @Suppress("DEPRECATION") fun `testing Kryo with ClassLoader (with top level class name)`() { val contract = createContract2Cash() @@ -212,6 +224,7 @@ class AttachmentsClassLoaderTests { class Data(val contract: Contract) @Test + @Suppress("DEPRECATION") fun `testing Kryo with ClassLoader (without top level class name)`() { val data = Data(createContract2Cash()) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt index c213b15c3f..0d6659e31d 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/SignedNodeInfoTest.kt @@ -18,7 +18,6 @@ import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Rule import org.junit.Test import java.security.KeyPair -import java.security.PrivateKey import java.security.PublicKey import java.security.SignatureException diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt index b5e6d50d5f..688e6d53f9 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/config/ConfigParsingTest.kt @@ -18,32 +18,32 @@ import kotlin.reflect.full.primaryConstructor class ConfigParsingTest { @Test - fun `String`() { + fun String() { testPropertyType("hello world!", "bye") } @Test - fun `Int`() { + fun Int() { testPropertyType(1, 2) } @Test - fun `Long`() { + fun Long() { testPropertyType(Long.MAX_VALUE, Long.MIN_VALUE) } @Test - fun `Double`() { + fun Double() { testPropertyType(1.2, 3.4) } @Test - fun `Boolean`() { + fun Boolean() { testPropertyType(true, false) } @Test - fun `Enum`() { + fun Enum() { testPropertyType(TestEnum.Value2, TestEnum.Value1, valuesToString = true) } @@ -56,17 +56,17 @@ class ConfigParsingTest { } @Test - fun `LocalDate`() { + fun LocalDate() { testPropertyType(LocalDate.now(), LocalDate.now().plusDays(1), valuesToString = true) } @Test - fun `Instant`() { + fun Instant() { testPropertyType(Instant.now(), Instant.now().plusMillis(100), valuesToString = true) } @Test - fun `NetworkHostAndPort`() { + fun NetworkHostAndPort() { testPropertyType( NetworkHostAndPort("localhost", 2223), NetworkHostAndPort("localhost", 2225), @@ -74,18 +74,18 @@ class ConfigParsingTest { } @Test - fun `Path`() { + fun Path() { val path = "tmp" / "test" testPropertyType(path, path / "file", valuesToString = true) } @Test - fun `URL`() { + fun URL() { testPropertyType(URL("http://localhost:1234"), URL("http://localhost:1235"), valuesToString = true) } @Test - fun `UUID`() { + fun UUID() { testPropertyType(UUID.randomUUID(), UUID.randomUUID(), valuesToString = true) } @@ -136,7 +136,7 @@ class ConfigParsingTest { } @Test - fun `Set`() { + fun Set() { val data = StringSetData(setOf("a", "b")) assertThat(config("values" to listOf("a", "a", "b")).parseAs()).isEqualTo(data) assertThat(data.toConfig()).isEqualTo(config("values" to listOf("a", "b"))) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt index f2825bbecd..d78f7a6bab 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/network/NodeInfoFilesCopierTest.kt @@ -14,7 +14,6 @@ import rx.schedulers.TestScheduler import java.nio.file.Path import java.time.Duration import java.util.concurrent.TimeUnit -import kotlin.streams.toList class NodeInfoFilesCopierTest { companion object { @@ -113,7 +112,7 @@ class NodeInfoFilesCopierTest { } @Test - fun `clear`() { + fun clear() { // Configure 2 nodes. nodeInfoFilesCopier.addConfig(node1RootPath) nodeInfoFilesCopier.addConfig(node2RootPath) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt index 8efb66fffd..1a5f283bd2 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/MapsSerializationTest.kt @@ -55,7 +55,7 @@ class MapsSerializationTest { val wrongPayloadType = WrongPayloadType(payload) assertThatThrownBy { wrongPayloadType.serialize() } .isInstanceOf(IllegalArgumentException::class.java).hasMessageContaining( - "Map type class java.util.HashMap is unstable under iteration. Suggested fix: use java.util.LinkedHashMap instead.") + "Map type class java.util.HashMap is unstable under iteration. Suggested fix: use java.util.LinkedHashMap instead.") } @CordaSerializable diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt index c2d25b4ff0..bfefdde7e5 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/PrivateKeySerializationTest.kt @@ -40,7 +40,6 @@ class PrivateKeySerializationTest(private val privateKey: PrivateKey, private va fun `failed with wrong UseCase`() { assertThatThrownBy { privateKey.serialize(context = SerializationDefaults.P2P_CONTEXT) } .isInstanceOf(IllegalStateException::class.java) - .hasMessageContaining("UseCase '${P2P}' is not within") - + .hasMessageContaining("UseCase '$P2P' is not within") } } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt index c6151409c6..b4f3f7f6d5 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/EnumEvolvabilityTests.kt @@ -397,6 +397,7 @@ class EnumEvolvabilityTests { val f = sf.javaClass.getDeclaredField("transformsCache") f.isAccessible = true + @Suppress("UNCHECKED_CAST") val transformsCache = f.get(sf) as ConcurrentHashMap>> assertEquals(0, transformsCache.size) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt index 70c709f4aa..b3e3a5622b 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/ErrorMessagesTests.kt @@ -15,7 +15,7 @@ class ErrorMessagesTests { val VERBOSE get() = false } - private fun errMsg(property:String, testname: String) = + private fun errMsg(property: String, testname: String) = "Property '$property' or its getter is non public, this renders class 'class $testname\$C' unserializable -> class $testname\$C" // Java allows this to be set at the class level yet Kotlin doesn't for some reason diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt index f7a75ec229..46573d8ab4 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/FingerPrinterTesting.kt @@ -7,7 +7,7 @@ import net.corda.nodeapi.internal.serialization.AllWhitelist import net.corda.nodeapi.internal.serialization.amqp.testutils.TestSerializationOutput import net.corda.nodeapi.internal.serialization.amqp.testutils.serializeAndReturnSchema -class FingerPrinterTesting : FingerPrinter { +class FingerPrinterTesting : FingerPrinter { private var index = 0 private val cache = mutableMapOf() @@ -29,18 +29,19 @@ class FingerPrinterTestingTests { companion object { const val VERBOSE = true } + @Test fun testingTest() { val fpt = FingerPrinterTesting() - assertEquals ("0", fpt.fingerprint(Integer::class.java)) - assertEquals ("1", fpt.fingerprint(String::class.java)) - assertEquals ("0", fpt.fingerprint(Integer::class.java)) - assertEquals ("1", fpt.fingerprint(String::class.java)) + assertEquals("0", fpt.fingerprint(Integer::class.java)) + assertEquals("1", fpt.fingerprint(String::class.java)) + assertEquals("0", fpt.fingerprint(Integer::class.java)) + assertEquals("1", fpt.fingerprint(String::class.java)) } @Test fun worksAsReplacement() { - data class C (val a: Int, val b: Long) + data class C(val a: Int, val b: Long) val factory = SerializerFactory( AllWhitelist, @@ -50,8 +51,7 @@ class FingerPrinterTestingTests { val blob = TestSerializationOutput(VERBOSE, factory).serializeAndReturnSchema(C(1, 2L)) - assertEquals (1, blob.schema.types.size) - assertEquals ("", blob.schema.types[0].descriptor.toString()) + assertEquals(1, blob.schema.types.size) + assertEquals("", blob.schema.types[0].descriptor.toString()) } - } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt index 2eed1e0e00..8bf29c3f6c 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/OverridePKSerializerTest.kt @@ -21,7 +21,7 @@ class OverridePKSerializerTest { override fun readObject(obj: Any, schemas: SerializationSchemas, input: DeserializationInput, context: SerializationContext - ) : PublicKey { + ): PublicKey { throw SerializerTestException("Custom read call") } diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt index cefc3e51ab..eba38ccb6d 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/RoundTripTests.kt @@ -10,9 +10,10 @@ import org.junit.Test class RoundTripTests { @Test fun mutableBecomesImmutable() { - data class C(val l : MutableList) + data class C(val l: MutableList) + val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(mutableListOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(mutableListOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) Assertions.assertThatThrownBy { @@ -23,15 +24,16 @@ class RoundTripTests { @Test fun mutableStillMutable() { class C { - val l : MutableList + val l: MutableList @Suppress("Unused") - constructor (l : MutableList) { + constructor (l: MutableList) { this.l = l.toMutableList() } } + val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(mutableListOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(mutableListOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) newC.l.add("d") @@ -39,14 +41,14 @@ class RoundTripTests { @Test fun mutableStillMutable2() { - data class C (val l : MutableList){ + data class C(val l: MutableList) { @ConstructorForDeserialization @Suppress("Unused") - constructor (l : Collection) : this (l.toMutableList()) + constructor (l: Collection) : this(l.toMutableList()) } val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(mutableListOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(mutableListOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) newC.l.add("d") @@ -54,10 +56,11 @@ class RoundTripTests { @Test fun mutableBecomesImmutable4() { - data class C(val l : List) + data class C(val l: List) + val factory = testDefaultFactoryNoEvolution() - val bytes = SerializationOutput(factory).serialize(C(listOf ("a", "b", "c"))) + val bytes = SerializationOutput(factory).serialize(C(listOf("a", "b", "c"))) val newC = DeserializationInput(factory).deserialize(bytes) - val newC2 = newC.copy (l = (newC.l + "d")) + val newC2 = newC.copy(l = (newC.l + "d")) } } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt index 90016c1511..d3bea49d1b 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationOutputTests.kt @@ -7,7 +7,13 @@ import com.nhaarman.mockito_kotlin.whenever import net.corda.client.rpc.RPCException import net.corda.core.CordaException import net.corda.core.CordaRuntimeException -import net.corda.core.contracts.* +import net.corda.core.contracts.Amount +import net.corda.core.contracts.Contract +import net.corda.core.contracts.ContractAttachment +import net.corda.core.contracts.ContractState +import net.corda.core.contracts.PrivacySalt +import net.corda.core.contracts.StateRef +import net.corda.core.contracts.TransactionState import net.corda.core.crypto.Crypto import net.corda.core.crypto.SecureHash import net.corda.core.crypto.secureRandomBytes @@ -16,25 +22,47 @@ import net.corda.core.identity.AbstractParty import net.corda.core.identity.CordaX500Name import net.corda.core.internal.AbstractAttachment import net.corda.core.internal.x500Name -import net.corda.core.serialization.* +import net.corda.core.serialization.ConstructorForDeserialization +import net.corda.core.serialization.CordaSerializable +import net.corda.core.serialization.EncodingWhitelist +import net.corda.core.serialization.MissingAttachmentsException +import net.corda.core.serialization.SerializationContext +import net.corda.core.serialization.SerializationFactory import net.corda.core.transactions.LedgerTransaction import net.corda.core.utilities.OpaqueBytes import net.corda.nodeapi.internal.DEV_INTERMEDIATE_CA import net.corda.nodeapi.internal.crypto.ContentSignerBuilder -import net.corda.nodeapi.internal.serialization.* +import net.corda.nodeapi.internal.serialization.AllWhitelist +import net.corda.nodeapi.internal.serialization.CordaSerializationEncoding +import net.corda.nodeapi.internal.serialization.EmptyWhitelist +import net.corda.nodeapi.internal.serialization.GeneratedAttachment import net.corda.nodeapi.internal.serialization.amqp.SerializerFactory.Companion.isPrimitive -import net.corda.nodeapi.internal.serialization.amqp.testutils.* -import net.corda.nodeapi.internal.serialization.carpenter.ClassCarpenterImpl +import net.corda.nodeapi.internal.serialization.amqp.testutils.deserialize +import net.corda.nodeapi.internal.serialization.amqp.testutils.serialize +import net.corda.nodeapi.internal.serialization.amqp.testutils.testDefaultFactory +import net.corda.nodeapi.internal.serialization.amqp.testutils.testDefaultFactoryNoEvolution +import net.corda.nodeapi.internal.serialization.amqp.testutils.testSerializationContext +import net.corda.nodeapi.internal.serialization.encodingNotPermittedFormat import net.corda.testing.contracts.DummyContract import net.corda.testing.core.BOB_NAME import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.core.TestIdentity import net.corda.testing.internal.rigorousMock import org.apache.activemq.artemis.api.core.SimpleString -import org.apache.qpid.proton.amqp.* +import org.apache.qpid.proton.amqp.Decimal128 +import org.apache.qpid.proton.amqp.Decimal32 +import org.apache.qpid.proton.amqp.Decimal64 +import org.apache.qpid.proton.amqp.Symbol +import org.apache.qpid.proton.amqp.UnsignedByte +import org.apache.qpid.proton.amqp.UnsignedInteger +import org.apache.qpid.proton.amqp.UnsignedLong +import org.apache.qpid.proton.amqp.UnsignedShort import org.apache.qpid.proton.codec.DecoderImpl import org.apache.qpid.proton.codec.EncoderImpl -import org.assertj.core.api.Assertions.* +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatExceptionOfType +import org.assertj.core.api.Assertions.assertThatThrownBy +import org.assertj.core.api.Assertions.catchThrowable import org.bouncycastle.cert.X509v2CRLBuilder import org.bouncycastle.cert.jcajce.JcaX509CRLConverter import org.bouncycastle.jce.provider.BouncyCastleProvider @@ -50,7 +78,20 @@ import java.io.NotSerializableException import java.math.BigDecimal import java.math.BigInteger import java.security.cert.X509CRL -import java.time.* +import java.time.DayOfWeek +import java.time.Duration +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.Month +import java.time.MonthDay +import java.time.OffsetDateTime +import java.time.OffsetTime +import java.time.Period +import java.time.Year +import java.time.YearMonth +import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import java.util.* import kotlin.reflect.full.superclasses @@ -233,7 +274,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi } EncoderImpl(decoder) DeserializationInput.withDataBytes(bytes, encodingWhitelist) { - decoder.setByteBuffer(it) + decoder.byteBuffer = it // Check that a vanilla AMQP decoder can deserialize without schema. val result = decoder.readObject() as Envelope assertNotNull(result) @@ -889,7 +930,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi @Test fun `test generic in constructor serialize`() { - val obj = GenericSubclass(OtherGeneric()) + val obj = GenericSubclass(OtherGeneric()) serdes(obj) } @@ -1186,7 +1227,7 @@ class SerializationOutputTests(private val compression: CordaSerializationEncodi factory.register(net.corda.nodeapi.internal.serialization.amqp.custom.BigDecimalSerializer) factory.register(net.corda.nodeapi.internal.serialization.amqp.custom.CurrencySerializer) - val c = C(Amount(100, BigDecimal("1.5"), Currency.getInstance("USD"))) + val c = C(Amount(100, BigDecimal("1.5"), Currency.getInstance("USD"))) // were the issue not fixed we'd blow up here SerializationOutput(factory, compression).serialize(c) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt index a75d94da25..a9c75359b7 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/SerializationSchemaTests.kt @@ -17,8 +17,8 @@ val TESTING_CONTEXT = SerializationContextImpl(amqpMagic, // Test factory that lets us count the number of serializer registration attempts class TestSerializerFactory( - wl : ClassWhitelist, - cl : ClassLoader + wl: ClassWhitelist, + cl: ClassLoader ) : SerializerFactory(wl, cl) { var registerCount = 0 @@ -83,16 +83,17 @@ class TestSerializationFactory : SerializationFactory() { class SerializationSchemaTests { @Test fun onlyRegisterCustomSerializersOnce() { - @CordaSerializable data class C(val a: Int) + @CordaSerializable + data class C(val a: Int) val c = C(1) val testSerializationFactory = TestSerializationFactory() val expectedCustomSerializerCount = 40 - assertEquals (0, testFactory.registerCount) - c.serialize (testSerializationFactory, TESTING_CONTEXT) - assertEquals (expectedCustomSerializerCount, testFactory.registerCount) - c.serialize (testSerializationFactory, TESTING_CONTEXT) - assertEquals (expectedCustomSerializerCount, testFactory.registerCount) + assertEquals(0, testFactory.registerCount) + c.serialize(testSerializationFactory, TESTING_CONTEXT) + assertEquals(expectedCustomSerializerCount, testFactory.registerCount) + c.serialize(testSerializationFactory, TESTING_CONTEXT) + assertEquals(expectedCustomSerializerCount, testFactory.registerCount) } } \ No newline at end of file diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt index 63edbf04bc..398c647a25 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/amqp/StaticInitialisationOfSerializedObjectTest.kt @@ -68,7 +68,6 @@ class StaticInitialisationOfSerializedObjectTest { assertEquals(1, serialisersByType.size) } - @Test fun deserializeTest() { data class D(val c: C2) @@ -99,8 +98,7 @@ class StaticInitialisationOfSerializedObjectTest { // Version of a serializer factory that will allow the class carpenter living on the // factory to have a different whitelist applied to it than the factory class TestSerializerFactory(wl1: ClassWhitelist, wl2: ClassWhitelist) : - SerializerFactory(wl1, ClassCarpenterImpl(ClassLoader.getSystemClassLoader(), wl2)) { - } + SerializerFactory(wl1, ClassCarpenterImpl(ClassLoader.getSystemClassLoader(), wl2)) // This time have the serialization factory and the carpenter use different whitelists @Test diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt index 23d55a8c72..1079766bed 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/CarpenterExceptionTests.kt @@ -27,7 +27,7 @@ class TestClassLoader(private var exclude: List) : ClassLoader() { } interface TestInterface { - fun runThing() : Int + fun runThing(): Int } // Create a custom serialization factory where we need to be able to both specify a carpenter @@ -63,10 +63,10 @@ class CarpenterExceptionTests { val a1 = CLA().loadClass(A::class.java.name) val a2 = CLB().loadClass(A::class.java.name) - assertTrue (TypeToken.of(a1).isSubtypeOf(a2)) - assertTrue (a1 is Type) - assertTrue (a2 is Type) - assertTrue (a3 is Type) + assertTrue(TypeToken.of(a1).isSubtypeOf(a2)) + assertTrue(a1 is Type) + assertTrue(a2 is Type) + assertTrue(a3 is Type) assertEquals(a1, a2) assertEquals(a1, a3) assertEquals(a2, a3) @@ -74,11 +74,11 @@ class CarpenterExceptionTests { @Test fun carpenterExceptionRethrownAsNotSerializableException() { - data class C2 (val i: Int) : TestInterface { + data class C2(val i: Int) : TestInterface { override fun runThing() = 1 } - data class C1 (val i: Int, val c: C2) + data class C1(val i: Int, val c: C2) // We need two factories to ensure when we deserialize the blob we don't just use the serializer // we built to serialise things diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt index 1668c748ec..4c8e37bcdf 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterTestUtils.kt @@ -40,7 +40,7 @@ fun Schema.mangleNames(names: List): Schema { * rather than have it create its own */ class SerializerFactoryExternalCarpenter(classCarpenter: ClassCarpenter) - : SerializerFactory (classCarpenter.whitelist, classCarpenter) + : SerializerFactory(classCarpenter.whitelist, classCarpenter) open class AmqpCarpenterBase(whitelist: ClassWhitelist) { var cc = ClassCarpenterImpl(whitelist = whitelist) diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt index 66041b90a9..8199cab18b 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/ClassCarpenterWhitelistTest.kt @@ -53,7 +53,8 @@ class ClassCarpenterWhitelistTest { // it's marked as CordaSerializable @Test fun notWhitelistedButAnnotated() { - @CordaSerializable data class A(val a: Int) + @CordaSerializable + data class A(val a: Int) class WL : ClassWhitelist { override fun hasListed(type: Class<*>) = false diff --git a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt index ff6564b5ed..59d5c379a8 100644 --- a/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt +++ b/node-api/src/test/kotlin/net/corda/nodeapi/internal/serialization/carpenter/MultiMemberCompositeSchemaToClassCarpenterTests.kt @@ -98,6 +98,5 @@ class MultiMemberCompositeSchemaToClassCarpenterTests : AmqpCarpenterBase(AllWhi assertEquals(pinochio.getMethod("getA").invoke(p), amqpObj.a) assertEquals(pinochio.getMethod("getB").invoke(p), amqpObj.b) } - } diff --git a/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt b/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt index 73c9aa026f..3750d76ef2 100644 --- a/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/AuthDBTests.kt @@ -40,7 +40,7 @@ class AuthDBTests : NodeBasedTest() { private lateinit var db: UsersDB companion object { - private val cacheExpireAfterSecs: Long = 1 + private const val cacheExpireAfterSecs: Long = 1 @JvmStatic @Parameterized.Parameters(name = "password encryption format = {0}") @@ -215,7 +215,7 @@ class AuthDBTests : NodeBasedTest() { @After fun tearDown() { - db.close() + db.close() } private fun encodePassword(s: String) = encodePassword(s, passwordEncryption) @@ -232,7 +232,7 @@ private class UsersDB : AutoCloseable { val jdbcUrl: String companion object { - val DB_CREATE_SCHEMA = """ + const val DB_CREATE_SCHEMA = """ CREATE TABLE users (username VARCHAR(256), password TEXT); CREATE TABLE user_roles (username VARCHAR(256), role_name VARCHAR(256)); CREATE TABLE roles_permissions (role_name VARCHAR(256), permission TEXT); @@ -243,7 +243,7 @@ private class UsersDB : AutoCloseable { session { it.execute("INSERT INTO users VALUES ('${user.username}', '${user.password}')") for (role in user.roles) { - it.execute("INSERT INTO user_roles VALUES ('${user.username}', '${role}')") + it.execute("INSERT INTO user_roles VALUES ('${user.username}', '$role')") } } } @@ -271,7 +271,7 @@ private class UsersDB : AutoCloseable { } private val dataSource: DataSource - inline private fun session(statement: (Statement) -> Unit) { + private inline fun session(statement: (Statement) -> Unit) { dataSource.connection.use { it.autoCommit = false it.createStatement().use(statement) @@ -283,7 +283,7 @@ private class UsersDB : AutoCloseable { users: List = emptyList(), roleAndPermissions: List = emptyList()) { - jdbcUrl = "jdbc:h2:mem:${name};DB_CLOSE_DELAY=-1" + jdbcUrl = "jdbc:h2:mem:$name;DB_CLOSE_DELAY=-1" dataSource = DataSourceFactory.createDataSource(Properties().apply { put("dataSourceClassName", "org.h2.jdbcx.JdbcDataSource") put("dataSource.url", jdbcUrl) @@ -322,7 +322,6 @@ private val hashedPasswords = mapOf( * A functional object for producing password encoded according to the given scheme. */ private fun encodePassword(s: String, format: PasswordEncryption) = when (format) { - PasswordEncryption.NONE -> s - PasswordEncryption.SHIRO_1_CRYPT -> hashedPasswords[format]!![s] ?: - DefaultPasswordService().encryptPassword(s.toCharArray()) - } \ No newline at end of file + PasswordEncryption.NONE -> s + PasswordEncryption.SHIRO_1_CRYPT -> hashedPasswords[format]!![s] ?: DefaultPasswordService().encryptPassword(s.toCharArray()) +} \ No newline at end of file diff --git a/node/src/integration-test/kotlin/net/corda/node/BootTests.kt b/node/src/integration-test/kotlin/net/corda/node/BootTests.kt index 3224fb1d4e..da6c55249c 100644 --- a/node/src/integration-test/kotlin/net/corda/node/BootTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/BootTests.kt @@ -28,8 +28,7 @@ class BootTests { fun `java deserialization is disabled`() { driver { val user = User("u", "p", setOf(startFlow())) - val future = CordaRPCClient(startNode(rpcUsers = listOf(user)).getOrThrow().rpcAddress). - start(user.username, user.password).proxy.startFlow(::ObjectInputStreamFlow).returnValue + val future = CordaRPCClient(startNode(rpcUsers = listOf(user)).getOrThrow().rpcAddress).start(user.username, user.password).proxy.startFlow(::ObjectInputStreamFlow).returnValue assertThatThrownBy { future.getOrThrow() }.isInstanceOf(InvalidClassException::class.java).hasMessage("filter status: REJECTED") } } diff --git a/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt b/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt index b28e954608..f4881a075a 100644 --- a/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/NodeUnloadHandlerTests.kt @@ -25,7 +25,7 @@ class NodeUnloadHandlerTests { startNode(providedName = DUMMY_BANK_A_NAME).getOrThrow() // just want to fall off the end of this for the mo... } - Assert.assertTrue("Timed out waiting for AbstractNode to invoke the test service shutdown callback",latch.await(30, TimeUnit.SECONDS)) + Assert.assertTrue("Timed out waiting for AbstractNode to invoke the test service shutdown callback", latch.await(30, TimeUnit.SECONDS)) } @CordaService @@ -43,7 +43,5 @@ class NodeUnloadHandlerTests { log.info("shutting down") latch.countDown() } - } - } \ No newline at end of file diff --git a/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt b/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt index 95075e6bdb..2826ecf5d6 100644 --- a/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/amqp/AMQPBridgeTest.kt @@ -35,14 +35,12 @@ class AMQPBridgeTest { private val log = loggerFor() - private val ALICE = TestIdentity(ALICE_NAME) private val BOB = TestIdentity(BOB_NAME) private val artemisPort = freePort() private val artemisPort2 = freePort() private val amqpPort = freePort() private val artemisAddress = NetworkHostAndPort("localhost", artemisPort) - private val artemisAddress2 = NetworkHostAndPort("localhost", artemisPort2) private val amqpAddress = NetworkHostAndPort("localhost", amqpPort) private abstract class AbstractNodeConfiguration : NodeConfiguration diff --git a/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt b/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt index 417da3155a..d6970efa58 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/events/ScheduledFlowIntegrationTests.kt @@ -25,7 +25,6 @@ import net.corda.core.node.services.vault.QueryCriteria import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.NonEmptySet import net.corda.core.utilities.getOrThrow -import net.corda.core.utilities.seconds import net.corda.testMessage.ScheduledState import net.corda.testMessage.SpentState import net.corda.testing.contracts.DummyContract diff --git a/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt index c9728af7d7..57530bfe43 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/rpc/RpcSslTest.kt @@ -8,7 +8,6 @@ import net.corda.node.services.Permissions.Companion.all import net.corda.testing.common.internal.withCertificates import net.corda.testing.common.internal.withKeyStores import net.corda.testing.driver.DriverParameters -import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver import net.corda.testing.driver.internal.RandomFree import net.corda.testing.internal.useSslRpcOverrides diff --git a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt index 1b7e5a7f96..86633a6a79 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/FlowVersioningTest.kt @@ -45,5 +45,4 @@ class FlowVersioningTest : NodeBasedTest() { @Suspendable override fun call() = otherSideSession.send(otherSideSession.getCounterpartyFlowInfo().flowVersion) } - } \ No newline at end of file diff --git a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt index b0d40d62cb..8451252c09 100644 --- a/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt +++ b/node/src/integration-test/kotlin/net/corda/node/services/statemachine/LargeTransactionsTest.kt @@ -3,7 +3,13 @@ package net.corda.node.services.statemachine import co.paralleluniverse.fibers.Suspendable import net.corda.client.rpc.CordaRPCClient import net.corda.core.crypto.SecureHash -import net.corda.core.flows.* +import net.corda.core.flows.FlowLogic +import net.corda.core.flows.FlowSession +import net.corda.core.flows.InitiatedBy +import net.corda.core.flows.InitiatingFlow +import net.corda.core.flows.ReceiveTransactionFlow +import net.corda.core.flows.SendTransactionFlow +import net.corda.core.flows.StartableByRPC import net.corda.core.internal.InputStreamAndHash import net.corda.core.internal.concurrent.transpose import net.corda.core.messaging.startFlow @@ -13,9 +19,12 @@ import net.corda.node.services.config.MB import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.contracts.DummyContract import net.corda.testing.contracts.DummyState -import net.corda.testing.core.* +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.dummyCommand import net.corda.testing.driver.DriverParameters -import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver import net.corda.testing.driver.internal.RandomFree import net.corda.testing.node.User diff --git a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt index c160a4a680..54d2e2ad0b 100644 --- a/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt +++ b/node/src/integration-test/kotlin/net/corda/services/messaging/P2PMessagingTest.kt @@ -16,7 +16,6 @@ import net.corda.node.services.messaging.MessagingService import net.corda.node.services.messaging.ReceivedMessage import net.corda.node.services.messaging.send import net.corda.testing.core.ALICE_NAME -import net.corda.testing.core.singleIdentity import net.corda.testing.driver.DriverDSL import net.corda.testing.driver.DriverParameters import net.corda.testing.driver.InProcess diff --git a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt index 491654812f..e5b4835aeb 100644 --- a/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt +++ b/node/src/main/kotlin/net/corda/node/internal/AbstractNode.kt @@ -269,7 +269,7 @@ abstract class AbstractNode(val configuration: NodeConfiguration, } } - makeVaultObservers(schedulerService, database.hibernateConfig, smm, schemaService, flowLogicRefFactory) + makeVaultObservers(schedulerService, database.hibernateConfig, schemaService, flowLogicRefFactory) val rpcOps = makeRPCOps(flowStarter, database, smm) startMessagingService(rpcOps) installCoreFlows() @@ -637,16 +637,15 @@ abstract class AbstractNode(val configuration: NodeConfiguration, networkParameters, servicesForResolution) network = makeMessagingService(database, nodeInfo, nodeProperties, networkParameters) - val tokenizableServices = mutableListOf(attachments, network, services.vaultService, + return mutableListOf(attachments, network, services.vaultService, services.keyManagementService, services.identityService, platformClock, services.auditService, services.monitoringService, services.networkMapCache, services.schemaService, services.transactionVerifierService, services.validatedTransactions, services.contractUpgradeService, services, cordappProvider, this) - return tokenizableServices } protected open fun makeTransactionStorage(database: CordaPersistence, transactionCacheSizeBytes: Long): WritableTransactionStorage = DBTransactionStorage(transactionCacheSizeBytes) - private fun makeVaultObservers(schedulerService: SchedulerService, hibernateConfig: HibernateConfiguration, smm: StateMachineManager, schemaService: SchemaService, flowLogicRefFactory: FlowLogicRefFactory) { + private fun makeVaultObservers(schedulerService: SchedulerService, hibernateConfig: HibernateConfiguration, schemaService: SchemaService, flowLogicRefFactory: FlowLogicRefFactory) { ScheduledActivityObserver.install(services.vaultService, schedulerService, flowLogicRefFactory) HibernateObserver.install(services.vaultService.rawUpdates, hibernateConfig, schemaService) } @@ -688,7 +687,7 @@ abstract class AbstractNode(val configuration: NodeConfiguration, protected open fun initialiseDatabasePersistence(schemaService: SchemaService, identityService: IdentityService): CordaPersistence { val props = configuration.dataSourceProperties - if (props.isEmpty()) throw DatabaseConfigurationException("There must be a database configured.") + if (props.isEmpty) throw DatabaseConfigurationException("There must be a database configured.") val database = configureDatabase(props, configuration.database, identityService, schemaService) // Now log the vendor string as this will also cause a connection to be tested eagerly. logVendorString(database, log) @@ -708,7 +707,7 @@ abstract class AbstractNode(val configuration: NodeConfiguration, } } - open protected fun checkNetworkMapIsInitialized() { + protected open fun checkNetworkMapIsInitialized() { if (!services.networkMapCache.loadDBSuccess) { // TODO: There should be a consistent approach to configuration error exceptions. throw NetworkMapCacheEmptyException() @@ -722,14 +721,16 @@ abstract class AbstractNode(val configuration: NodeConfiguration, private fun makeCoreNotaryService(notaryConfig: NotaryConfig, database: CordaPersistence): NotaryService { val notaryKey = myNotaryIdentity?.owningKey ?: throw IllegalArgumentException("No notary identity initialized when creating a notary service") return notaryConfig.run { - if (raft != null) { - val uniquenessProvider = RaftUniquenessProvider(configuration, database, services.clock, services.monitoringService.metrics, raft) - (if (validating) ::RaftValidatingNotaryService else ::RaftNonValidatingNotaryService)(services, notaryKey, uniquenessProvider) - } else if (bftSMaRt != null) { - if (validating) throw IllegalArgumentException("Validating BFTSMaRt notary not supported") - BFTNonValidatingNotaryService(services, notaryKey, bftSMaRt, makeBFTCluster(notaryKey, bftSMaRt)) - } else { - (if (validating) ::ValidatingNotaryService else ::SimpleNotaryService)(services, notaryKey) + when { + raft != null -> { + val uniquenessProvider = RaftUniquenessProvider(configuration, database, services.clock, services.monitoringService.metrics, raft) + (if (validating) ::RaftValidatingNotaryService else ::RaftNonValidatingNotaryService)(services, notaryKey, uniquenessProvider) + } + bftSMaRt != null -> { + if (validating) throw IllegalArgumentException("Validating BFTSMaRt notary not supported") + BFTNonValidatingNotaryService(services, notaryKey, bftSMaRt, makeBFTCluster(notaryKey, bftSMaRt)) + } + else -> (if (validating) ::ValidatingNotaryService else ::SimpleNotaryService)(services, notaryKey) } } } @@ -887,8 +888,8 @@ abstract class AbstractNode(val configuration: NodeConfiguration, override fun jdbcSession(): Connection = database.createSession() // allows services to register handlers to be informed when the node stop method is called - override fun registerUnloadHandler(handler: () -> Unit) { - runOnStop += handler + override fun registerUnloadHandler(runOnStop: () -> Unit) { + this@AbstractNode.runOnStop += runOnStop } } } diff --git a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt index 7a4a8a94e5..34be9c412b 100644 --- a/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt +++ b/node/src/main/kotlin/net/corda/node/internal/CordaRPCOpsImpl.kt @@ -91,12 +91,14 @@ internal class CordaRPCOpsImpl( } } + @Suppress("OverridingDeprecatedMember") override fun internalVerifiedTransactionsSnapshot(): List { - val (snapshot, updates) = internalVerifiedTransactionsFeed() + val (snapshot, updates) = @Suppress("DEPRECATION") internalVerifiedTransactionsFeed() updates.notUsed() return snapshot } + @Suppress("OverridingDeprecatedMember") override fun internalVerifiedTransactionsFeed(): DataFeed, SignedTransaction> { return database.transaction { services.validatedTransactions.track() diff --git a/node/src/main/kotlin/net/corda/node/internal/Node.kt b/node/src/main/kotlin/net/corda/node/internal/Node.kt index c06f241c65..b75419615e 100644 --- a/node/src/main/kotlin/net/corda/node/internal/Node.kt +++ b/node/src/main/kotlin/net/corda/node/internal/Node.kt @@ -182,7 +182,7 @@ open class Node(configuration: NodeConfiguration, val rpcServerAddresses = if (configuration.rpcOptions.standAloneBroker) { BrokerAddresses(configuration.rpcOptions.address!!, configuration.rpcOptions.adminAddress) } else { - startLocalRpcBroker(networkParameters) + startLocalRpcBroker() } val advertisedAddress = info.addresses[0] bridgeControlListener = BridgeControlListener(configuration, serverAddress, /*networkParameters.maxMessageSize*/MAX_FILE_SIZE) @@ -214,7 +214,7 @@ open class Node(configuration: NodeConfiguration, drainingModeWasChangedEvents = nodeProperties.flowsDrainingMode.values) } - private fun startLocalRpcBroker(networkParameters: NetworkParameters): BrokerAddresses? { + private fun startLocalRpcBroker(): BrokerAddresses? { with(configuration) { return rpcOptions.address?.let { require(rpcOptions.address != null) { "RPC address needs to be specified for local RPC broker." } diff --git a/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt b/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt index c1624d87cc..eb2ef03ea8 100644 --- a/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt +++ b/node/src/main/kotlin/net/corda/node/internal/NodeStartup.kt @@ -140,11 +140,11 @@ open class NodeStartup(val args: Array) { return true } - open protected fun preNetworkRegistration(conf: NodeConfiguration) = Unit + protected open fun preNetworkRegistration(conf: NodeConfiguration) = Unit - open protected fun createNode(conf: NodeConfiguration, versionInfo: VersionInfo): Node = Node(conf, versionInfo) + protected open fun createNode(conf: NodeConfiguration, versionInfo: VersionInfo): Node = Node(conf, versionInfo) - open protected fun startNode(conf: NodeConfiguration, versionInfo: VersionInfo, startTime: Long, cmdlineOptions: CmdLineOptions) { + protected open fun startNode(conf: NodeConfiguration, versionInfo: VersionInfo, startTime: Long, cmdlineOptions: CmdLineOptions) { val node = createNode(conf, versionInfo) if (cmdlineOptions.justGenerateNodeInfo) { // Perform the minimum required start-up logic to be able to write a nodeInfo to disk @@ -178,7 +178,7 @@ open class NodeStartup(val args: Array) { startedNode.internals.run() } - open protected fun logStartupInfo(versionInfo: VersionInfo, cmdlineOptions: CmdLineOptions, conf: NodeConfiguration) { + protected open fun logStartupInfo(versionInfo: VersionInfo, cmdlineOptions: CmdLineOptions, conf: NodeConfiguration) { logger.info("Vendor: ${versionInfo.vendor}") logger.info("Release: ${versionInfo.releaseVersion}") logger.info("Platform Version: ${versionInfo.platformVersion}") @@ -200,7 +200,7 @@ open class NodeStartup(val args: Array) { logger.info("Starting as node on ${conf.p2pAddress}") } - open protected fun registerWithNetwork(conf: NodeConfiguration, nodeRegistrationConfig: NodeRegistrationOption) { + protected open fun registerWithNetwork(conf: NodeConfiguration, nodeRegistrationConfig: NodeRegistrationOption) { val compatibilityZoneURL = conf.compatibilityZoneURL!! println() println("******************************************************************") @@ -211,13 +211,13 @@ open class NodeStartup(val args: Array) { NodeRegistrationHelper(conf, HTTPNetworkRegistrationService(compatibilityZoneURL), nodeRegistrationConfig).buildKeystore() } - open protected fun loadConfigFile(cmdlineOptions: CmdLineOptions): NodeConfiguration = cmdlineOptions.loadConfig() + protected open fun loadConfigFile(cmdlineOptions: CmdLineOptions): NodeConfiguration = cmdlineOptions.loadConfig() - open protected fun banJavaSerialisation(conf: NodeConfiguration) { + protected open fun banJavaSerialisation(conf: NodeConfiguration) { SerialFilter.install(if (conf.notary?.bftSMaRt != null) ::bftSMaRtSerialFilter else ::defaultSerialFilter) } - open protected fun getVersionInfo(): VersionInfo { + protected open fun getVersionInfo(): VersionInfo { // Manifest properties are only available if running from the corda jar fun manifestValue(name: String): String? = if (Manifests.exists(name)) Manifests.read(name) else null @@ -254,7 +254,7 @@ open class NodeStartup(val args: Array) { pidFileRw.write(ourProcessID.toByteArray()) } - open protected fun initLogging(cmdlineOptions: CmdLineOptions) { + protected open fun initLogging(cmdlineOptions: CmdLineOptions) { val loggingLevel = cmdlineOptions.loggingLevel.name.toLowerCase(Locale.ENGLISH) System.setProperty("defaultLogLevel", loggingLevel) // These properties are referenced from the XML config file. if (cmdlineOptions.logToConsole) { diff --git a/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt b/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt index ece6c31561..cc487b3dec 100644 --- a/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt +++ b/node/src/main/kotlin/net/corda/node/internal/RpcAuthorisationProxy.kt @@ -53,8 +53,10 @@ class RpcAuthorisationProxy(private val implementation: CordaRPCOps, private val implementation.vaultTrackBy(criteria, paging, sorting, contractStateType) } + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsSnapshot() = guard("internalVerifiedTransactionsSnapshot", implementation::internalVerifiedTransactionsSnapshot) + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsFeed() = guard("internalVerifiedTransactionsFeed", implementation::internalVerifiedTransactionsFeed) override fun stateMachineRecordedTransactionMappingSnapshot() = guard("stateMachineRecordedTransactionMappingSnapshot", implementation::stateMachineRecordedTransactionMappingSnapshot) diff --git a/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt b/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt index f8434b9b52..95332c2d68 100644 --- a/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt +++ b/node/src/main/kotlin/net/corda/node/internal/RpcExceptionHandlingProxy.kt @@ -66,6 +66,7 @@ class RpcExceptionHandlingProxy(private val delegate: SecureCordaRPCOps) : Corda override fun networkParametersFeed() = wrapFeed(delegate::networkParametersFeed) + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsFeed() = wrapFeed(delegate::internalVerifiedTransactionsFeed) override fun stateMachinesSnapshot() = wrap(delegate::stateMachinesSnapshot) @@ -80,6 +81,7 @@ class RpcExceptionHandlingProxy(private val delegate: SecureCordaRPCOps) : Corda override fun vaultQueryByWithSorting(contractStateType: Class, criteria: QueryCriteria, sorting: Sort) = wrap { delegate.vaultQueryByWithSorting(contractStateType, criteria, sorting) } + @Suppress("DEPRECATION", "OverridingDeprecatedMember") override fun internalVerifiedTransactionsSnapshot() = wrap(delegate::internalVerifiedTransactionsSnapshot) override fun stateMachineRecordedTransactionMappingSnapshot() = wrap(delegate::stateMachineRecordedTransactionMappingSnapshot) diff --git a/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt b/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt index ca8f4bab74..f7adb54ca7 100644 --- a/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt +++ b/node/src/main/kotlin/net/corda/node/internal/artemis/ReactiveArtemisConsumer.kt @@ -48,7 +48,7 @@ private class MultiplexingReactiveArtemisConsumer(private val queueNames: Set = cordapps.filter { !it.contractClassNames.isEmpty() }.map { diff --git a/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt b/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt index 3e0386b149..6769b35ff9 100644 --- a/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt +++ b/node/src/main/kotlin/net/corda/node/internal/schemas/NodeInfoSchema.kt @@ -28,19 +28,19 @@ object NodeInfoSchemaV1 : MappedSchema( @Column(name = "node_info_id") var id: Int, - @Column(name="node_info_hash", length = 64) + @Column(name = "node_info_hash", length = 64) val hash: String, @Column(name = "addresses") - @OneToMany(cascade = arrayOf(CascadeType.ALL), orphanRemoval = true) + @OneToMany(cascade = [(CascadeType.ALL)], orphanRemoval = true) @JoinColumn(name = "node_info_id", foreignKey = ForeignKey(name = "FK__info_hosts__infos")) val addresses: List, @Column(name = "legal_identities_certs") - @ManyToMany(cascade = arrayOf(CascadeType.ALL)) + @ManyToMany(cascade = [(CascadeType.ALL)]) @JoinTable(name = "node_link_nodeinfo_party", - joinColumns = arrayOf(JoinColumn(name = "node_info_id", foreignKey = ForeignKey(name = "FK__link_nodeinfo_party__infos"))), - inverseJoinColumns = arrayOf(JoinColumn(name = "party_name", foreignKey = ForeignKey(name = "FK__link_ni_p__info_p_cert")))) + joinColumns = [(JoinColumn(name = "node_info_id", foreignKey = ForeignKey(name = "FK__link_nodeinfo_party__infos")))], + inverseJoinColumns = [(JoinColumn(name = "party_name", foreignKey = ForeignKey(name = "FK__link_ni_p__info_p_cert")))]) val legalIdentitiesAndCerts: List, @Column(name = "platform_version") @@ -102,16 +102,15 @@ object NodeInfoSchemaV1 : MappedSchema( @Column(name = "party_cert_binary") val partyCertBinary: ByteArray, - val isMain: Boolean, - @ManyToMany(mappedBy = "legalIdentitiesAndCerts", cascade = arrayOf(CascadeType.ALL)) // ManyToMany because of distributed services. + @ManyToMany(mappedBy = "legalIdentitiesAndCerts", cascade = [(CascadeType.ALL)]) // ManyToMany because of distributed services. private val persistentNodeInfos: Set = emptySet() ) : Serializable { constructor(partyAndCert: PartyAndCertificate, isMain: Boolean = false) : this(partyAndCert.name.toString(), - partyAndCert.party.owningKey.toStringShort(), - partyAndCert.serialize(context = SerializationDefaults.STORAGE_CONTEXT).bytes, isMain) + partyAndCert.party.owningKey.toStringShort(), + partyAndCert.serialize(context = SerializationDefaults.STORAGE_CONTEXT).bytes, isMain) fun toLegalIdentityAndCert(): PartyAndCertificate { return partyCertBinary.deserialize() diff --git a/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt b/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt index d831582747..7c9af4030b 100644 --- a/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt +++ b/node/src/main/kotlin/net/corda/node/internal/security/AuthorizingSubject.kt @@ -15,14 +15,13 @@ interface AuthorizingSubject { * (e.g. an RPC invocation) represented by an [action] string followed by an * optional list of arguments. */ - fun isPermitted(action : String, vararg arguments : String) : Boolean + fun isPermitted(action: String, vararg arguments: String): Boolean } /** * An implementation of [AuthorizingSubject] permitting all actions */ -class AdminSubject(override val principal : String) : AuthorizingSubject { +class AdminSubject(override val principal: String) : AuthorizingSubject { override fun isPermitted(action: String, vararg arguments: String) = true - } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt index 4307df44e0..b00032f423 100644 --- a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt +++ b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManager.kt @@ -1,7 +1,6 @@ package net.corda.node.internal.security import net.corda.core.context.AuthServiceId -import org.apache.shiro.authc.AuthenticationException import javax.security.auth.login.FailedLoginException /** diff --git a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt index 4b9af66259..a3e788721a 100644 --- a/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt +++ b/node/src/main/kotlin/net/corda/node/internal/security/RPCSecurityManagerImpl.kt @@ -5,6 +5,7 @@ import com.github.benmanes.caffeine.cache.Cache import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.primitives.Ints import net.corda.core.context.AuthServiceId +import net.corda.core.internal.uncheckedCast import net.corda.core.utilities.loggerFor import net.corda.node.internal.DataSourceFactory import net.corda.node.services.config.PasswordEncryption @@ -144,10 +145,10 @@ private class RPCPermission : DomainPermission { */ private object RPCPermissionResolver : PermissionResolver { - private val SEPARATOR = '.' - private val ACTION_START_FLOW = "startflow" - private val ACTION_INVOKE_RPC = "invokerpc" - private val ACTION_ALL = "all" + private const val SEPARATOR = '.' + private const val ACTION_START_FLOW = "startflow" + private const val ACTION_INVOKE_RPC = "invokerpc" + private const val ACTION_ALL = "all" private val FLOW_RPC_CALLS = setOf( "startFlowDynamic", "startTrackedFlowDynamic", @@ -259,9 +260,8 @@ private typealias ShiroCache = org.apache.shiro.cache.Cache /* * Adapts a [com.github.benmanes.caffeine.cache.Cache] to a [org.apache.shiro.cache.Cache] implementation. */ -private fun Cache.toShiroCache(name: String) = object : ShiroCache { +private fun Cache.toShiroCache() = object : ShiroCache { - val name = name private val impl = this@toShiroCache override operator fun get(key: K) = impl.getIfPresent(key) @@ -300,7 +300,7 @@ private class CaffeineCacheManager(val maxSize: Long, override fun getCache(name: String): ShiroCache { val result = instances[name] ?: buildCache(name) instances.putIfAbsent(name, result) - return result as ShiroCache + return uncheckedCast(result) } private fun buildCache(name: String): ShiroCache { @@ -309,7 +309,7 @@ private class CaffeineCacheManager(val maxSize: Long, .expireAfterWrite(timeToLiveSeconds, TimeUnit.SECONDS) .maximumSize(maxSize) .build() - .toShiroCache(name) + .toShiroCache() } companion object { diff --git a/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt b/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt index bb388eea30..c350b81849 100644 --- a/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt +++ b/node/src/main/kotlin/net/corda/node/services/CoreFlowHandlers.kt @@ -55,8 +55,7 @@ class ContractUpgradeHandler(otherSide: FlowSession) : AbstractStateReplacementF val ourSTX = serviceHub.validatedTransactions.getTransaction(proposal.stateRef.txhash) requireNotNull(ourSTX) { "We don't have a copy of the referenced state" } val oldStateAndRef = ourSTX!!.tx.outRef(proposal.stateRef.index) - val authorisedUpgrade = serviceHub.contractUpgradeService.getAuthorisedContractUpgrade(oldStateAndRef.ref) ?: - throw IllegalStateException("Contract state upgrade is unauthorised. State hash : ${oldStateAndRef.ref}") + val authorisedUpgrade = serviceHub.contractUpgradeService.getAuthorisedContractUpgrade(oldStateAndRef.ref) ?: throw IllegalStateException("Contract state upgrade is unauthorised. State hash : ${oldStateAndRef.ref}") val proposedTx = stx.coreTransaction as ContractUpgradeWireTransaction val expectedTx = ContractUpgradeUtils.assembleUpgradeTx(oldStateAndRef, proposal.modification, proposedTx.privacySalt, serviceHub) requireThat { diff --git a/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt b/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt index 3e5bf3414d..43d3ec1d27 100644 --- a/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt +++ b/node/src/main/kotlin/net/corda/node/services/api/MonitoringService.kt @@ -3,7 +3,6 @@ package net.corda.node.services.api import com.codahale.metrics.MetricRegistry import net.corda.core.serialization.SingletonSerializeAsToken - /** * Provides access to various metrics and ways to notify monitoring services of things, for sysadmin purposes. * This is not an interface because it is too lightweight to bother mocking out. diff --git a/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt b/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt index 245f4a3042..3c45410f1f 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/ConfigUtilities.kt @@ -46,9 +46,8 @@ object ConfigHelper { log.info("Config:\n${finalConfig.root().render(ConfigRenderOptions.defaults())}") val entrySet = finalConfig.entrySet().filter { entry -> entry.key.contains("\"") } - for (mutableEntry in entrySet) { - val key = mutableEntry.key - log.error("Config files should not contain \" in property names. Please fix: ${key}") + for ((key) in entrySet) { + log.error("Config files should not contain \" in property names. Please fix: $key") } return finalConfig diff --git a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt index e65abf04c8..5eccaa8b39 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/NodeConfiguration.kt @@ -65,7 +65,7 @@ interface NodeConfiguration : NodeSSLConfiguration { } val defaultAttachmentContentCacheSize: Long = 10.MB - val defaultAttachmentCacheBound = 1024L + const val defaultAttachmentCacheBound = 1024L } } diff --git a/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt b/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt index 453a9c7dbd..1ff4ad66df 100644 --- a/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt +++ b/node/src/main/kotlin/net/corda/node/services/config/shell/ShellConfig.kt @@ -12,7 +12,6 @@ import net.corda.tools.shell.ShellConfiguration.Companion.SSHD_HOSTKEY_DIR import net.corda.tools.shell.ShellConfiguration.Companion.SSH_PORT import net.corda.tools.shell.ShellSslOptions - //re-packs data to Shell specific classes fun NodeConfiguration.toShellConfig(): ShellConfiguration { diff --git a/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt b/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt index 21a796d841..d5cb3a94d8 100644 --- a/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt +++ b/node/src/main/kotlin/net/corda/node/services/events/PersistentScheduledFlowRepository.kt @@ -9,10 +9,10 @@ import net.corda.nodeapi.internal.persistence.CordaPersistence interface ScheduledFlowRepository { fun delete(key: StateRef): Boolean fun merge(value: ScheduledStateRef): Boolean - fun getLatest(lookahead: Int) : List> + fun getLatest(lookahead: Int): List> } -class PersistentScheduledFlowRepository(val database: CordaPersistence): ScheduledFlowRepository { +class PersistentScheduledFlowRepository(val database: CordaPersistence) : ScheduledFlowRepository { private fun toPersistentEntityKey(stateRef: StateRef): PersistentStateRef { return PersistentStateRef(stateRef.txhash.toString(), stateRef.index) } @@ -32,7 +32,7 @@ class PersistentScheduledFlowRepository(val database: CordaPersistence): Schedul override fun delete(key: StateRef): Boolean { return database.transaction { - val elem = session.find(NodeSchedulerService.PersistentScheduledState::class.java, toPersistentEntityKey(key!!)) + val elem = session.find(NodeSchedulerService.PersistentScheduledState::class.java, toPersistentEntityKey(key)) if (elem != null) { session.remove(elem) true @@ -55,7 +55,7 @@ class PersistentScheduledFlowRepository(val database: CordaPersistence): Schedul } } - override fun getLatest(lookahead: Int) : List> { + override fun getLatest(lookahead: Int): List> { return database.transaction { val criteriaQuery = session.criteriaBuilder.createQuery(NodeSchedulerService.PersistentScheduledState::class.java) val shed = criteriaQuery.from(NodeSchedulerService.PersistentScheduledState::class.java) diff --git a/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt b/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt index 6cef78b051..5bf1a3d043 100644 --- a/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt +++ b/node/src/main/kotlin/net/corda/node/services/keys/KMSUtils.kt @@ -25,7 +25,6 @@ import java.time.Duration * @param subjectPublicKey public key of new identity. * @param issuer issuer to generate a key and certificate for. Must be an identity this node has the private key for. * @param issuerSigner a content signer for the issuer. - * @param revocationEnabled whether to check revocation status of certificates in the certificate path. * @return X.509 certificate and path to the trust root. */ fun freshCertificate(identityService: IdentityService, diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt index 08e040fbea..f559b92c22 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/ArtemisMessagingServer.kt @@ -158,7 +158,7 @@ class ArtemisMessagingServer(private val config: NodeConfiguration, * 4. Verifiers. These are given read access to the verification request queue and write access to the response queue. */ private fun ConfigurationImpl.configureAddressSecurity(): Configuration { - val nodeInternalRole = Role(NODE_ROLE, true, true, true, true, true, true, true, true) + val nodeInternalRole = Role(NODE_ROLE, true, true, true, true, true, true, true, true, true, true) securityRoles["$INTERNAL_PREFIX#"] = setOf(nodeInternalRole) // Do not add any other roles here as it's only for the node securityRoles["$P2P_PREFIX#"] = setOf(nodeInternalRole, restrictedRole(PEER_ROLE, send = true)) securityRoles[VerifierApi.VERIFICATION_REQUESTS_QUEUE_NAME] = setOf(nodeInternalRole, restrictedRole(VERIFIER_ROLE, consume = true)) @@ -170,7 +170,7 @@ class ArtemisMessagingServer(private val config: NodeConfiguration, deleteDurableQueue: Boolean = false, createNonDurableQueue: Boolean = false, deleteNonDurableQueue: Boolean = false, manage: Boolean = false, browse: Boolean = false): Role { return Role(name, send, consume, createDurableQueue, deleteDurableQueue, createNonDurableQueue, - deleteNonDurableQueue, manage, browse) + deleteNonDurableQueue, manage, browse, createDurableQueue || createNonDurableQueue, deleteDurableQueue || deleteNonDurableQueue) } @Throws(IOException::class, KeyStoreException::class) diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt b/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt index fce17e32f3..4d13f0df12 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/Messaging.kt @@ -106,8 +106,7 @@ interface MessagingService { val myAddress: SingleMessageRecipient } -fun MessagingService.send(topicSession: String, payload: Any, to: MessageRecipients, deduplicationId: DeduplicationId = DeduplicationId.createRandom(newSecureRandom()), retryId: Long? = null, additionalHeaders: Map = emptyMap()) - = send(createMessage(topicSession, payload.serialize().bytes, deduplicationId, additionalHeaders), to, retryId) +fun MessagingService.send(topicSession: String, payload: Any, to: MessageRecipients, deduplicationId: DeduplicationId = DeduplicationId.createRandom(newSecureRandom()), retryId: Long? = null, additionalHeaders: Map = emptyMap()) = send(createMessage(topicSession, payload.serialize().bytes, deduplicationId, additionalHeaders), to, retryId) interface MessageHandlerRegistration diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/MessagingExecutor.kt b/node/src/main/kotlin/net/corda/node/services/messaging/MessagingExecutor.kt index 9c2e124556..931e50e980 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/MessagingExecutor.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/MessagingExecutor.kt @@ -1,23 +1,16 @@ package net.corda.node.services.messaging -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.strands.SettableFuture -import com.codahale.metrics.MetricRegistry import net.corda.core.messaging.MessageRecipients import net.corda.core.utilities.contextLogger import net.corda.core.utilities.trace import net.corda.node.VersionInfo import net.corda.node.services.statemachine.FlowMessagingImpl import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.P2PMessagingHeaders -import org.apache.activemq.artemis.api.core.ActiveMQDuplicateIdException import org.apache.activemq.artemis.api.core.SimpleString import org.apache.activemq.artemis.api.core.client.ClientMessage import org.apache.activemq.artemis.api.core.client.ClientProducer import org.apache.activemq.artemis.api.core.client.ClientSession -import java.util.concurrent.ArrayBlockingQueue -import java.util.concurrent.ExecutionException import java.util.concurrent.atomic.AtomicLong -import kotlin.concurrent.thread interface AddressToArtemisQueueResolver { /** @@ -60,7 +53,7 @@ class MessagingExecutor( fun acknowledge(message: ClientMessage) { message.individualAcknowledge() - } + } internal fun cordaToArtemisMessage(message: Message): ClientMessage? { return session.createMessage(true).apply { diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt b/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt index a020c10055..3acae7898b 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/P2PMessagingClient.kt @@ -1,7 +1,6 @@ package net.corda.node.services.messaging import co.paralleluniverse.fibers.Suspendable -import com.codahale.metrics.MetricRegistry import net.corda.core.crypto.toStringShort import net.corda.core.identity.CordaX500Name import net.corda.core.internal.ThreadBox @@ -16,7 +15,11 @@ import net.corda.core.serialization.SingletonSerializeAsToken import net.corda.core.serialization.deserialize import net.corda.core.serialization.internal.nodeSerializationEnv import net.corda.core.serialization.serialize -import net.corda.core.utilities.* +import net.corda.core.utilities.ByteSequence +import net.corda.core.utilities.NetworkHostAndPort +import net.corda.core.utilities.OpaqueBytes +import net.corda.core.utilities.contextLogger +import net.corda.core.utilities.trace import net.corda.node.VersionInfo import net.corda.node.internal.LifecycleSupport import net.corda.node.internal.artemis.ReactiveArtemisConsumer @@ -29,11 +32,14 @@ import net.corda.node.utilities.PersistentMap import net.corda.nodeapi.ArtemisTcpTransport import net.corda.nodeapi.ConnectionDirection import net.corda.nodeapi.internal.ArtemisMessagingComponent -import net.corda.nodeapi.internal.ArtemisMessagingComponent.* +import net.corda.nodeapi.internal.ArtemisMessagingComponent.ArtemisAddress import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.BRIDGE_CONTROL import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.BRIDGE_NOTIFY import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.P2PMessagingHeaders import net.corda.nodeapi.internal.ArtemisMessagingComponent.Companion.PEERS_PREFIX +import net.corda.nodeapi.internal.ArtemisMessagingComponent.NodeAddress +import net.corda.nodeapi.internal.ArtemisMessagingComponent.RemoteInboxAddress +import net.corda.nodeapi.internal.ArtemisMessagingComponent.ServiceAddress import net.corda.nodeapi.internal.bridging.BridgeControl import net.corda.nodeapi.internal.bridging.BridgeEntry import net.corda.nodeapi.internal.persistence.CordaPersistence @@ -43,7 +49,12 @@ import org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID import org.apache.activemq.artemis.api.core.Message.HDR_VALIDATED_USER import org.apache.activemq.artemis.api.core.RoutingType import org.apache.activemq.artemis.api.core.SimpleString -import org.apache.activemq.artemis.api.core.client.* +import org.apache.activemq.artemis.api.core.client.ActiveMQClient +import org.apache.activemq.artemis.api.core.client.ClientConsumer +import org.apache.activemq.artemis.api.core.client.ClientMessage +import org.apache.activemq.artemis.api.core.client.ClientProducer +import org.apache.activemq.artemis.api.core.client.ClientSession +import org.apache.activemq.artemis.api.core.client.ServerLocator import org.apache.commons.lang.ArrayUtils.EMPTY_BYTE_ARRAY import rx.Observable import rx.Subscription diff --git a/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt b/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt index 5f7d193582..7c9ed1cf86 100644 --- a/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt +++ b/node/src/main/kotlin/net/corda/node/services/messaging/RPCServer.kt @@ -137,7 +137,7 @@ class RPCServer( private fun createObservableSubscriptionMap(): ObservableSubscriptionMap { val onObservableRemove = RemovalListener { key, value, cause -> - log.debug { "Unsubscribing from Observable with id ${key} because of ${cause}" } + log.debug { "Unsubscribing from Observable with id $key because of $cause" } value!!.subscription.unsubscribe() } return Caffeine.newBuilder().removalListener(onObservableRemove).executor(SameThreadExecutor.getExecutor()).build() @@ -374,7 +374,7 @@ class RPCServer( private fun bufferIfQueueNotBound(clientAddress: SimpleString, message: RPCApi.ServerToClient.RpcReply, context: ObservableContext): Boolean { val clientBuffer = responseMessageBuffer.compute(clientAddress, { _, value -> when (value) { - null -> BufferOrNone.Buffer(ArrayList()).apply { + null -> BufferOrNone.Buffer(ArrayList()).apply { container.add(MessageAndContext(message, context)) } is BufferOrNone.Buffer -> value.apply { diff --git a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt index 622aeff573..648488537f 100644 --- a/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt +++ b/node/src/main/kotlin/net/corda/node/services/network/NetworkMapUpdater.kt @@ -15,10 +15,14 @@ import net.corda.core.utilities.minutes import net.corda.node.services.api.NetworkMapCacheInternal import net.corda.node.utilities.NamedThreadFactory import net.corda.nodeapi.exceptions.OutdatedNetworkParameterHashException -import net.corda.nodeapi.internal.network.* +import net.corda.nodeapi.internal.network.NETWORK_PARAMS_FILE_NAME +import net.corda.nodeapi.internal.network.NETWORK_PARAMS_UPDATE_FILE_NAME +import net.corda.nodeapi.internal.network.NetworkMap +import net.corda.nodeapi.internal.network.ParametersUpdate +import net.corda.nodeapi.internal.network.SignedNetworkParameters +import net.corda.nodeapi.internal.network.verifiedNetworkMapCert import rx.Subscription import rx.subjects.PublishSubject -import java.net.URL import java.nio.file.Path import java.nio.file.StandardCopyOption import java.time.Duration diff --git a/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt b/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt index caefa2d3d6..6ca2a10009 100644 --- a/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt +++ b/node/src/main/kotlin/net/corda/node/services/network/PersistentNetworkMapCache.kt @@ -305,7 +305,7 @@ open class PersistentNetworkMapCache( NodeInfoSchemaV1.PersistentNodeInfo::class.java) query.setParameter("host", hostAndPort.host) query.setParameter("port", hostAndPort.port) - query.setMaxResults(1) + query.maxResults = 1 val result = query.resultList return result.map { it.toNodeInfo() }.singleOrNull() } diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt index d4d6384719..8fa0d04cbd 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyDescriptor.kt @@ -2,6 +2,7 @@ package net.corda.node.services.persistence import net.corda.core.identity.AbstractParty import net.corda.core.identity.CordaX500Name +import net.corda.core.internal.uncheckedCast import net.corda.core.node.services.IdentityService import net.corda.core.utilities.contextLogger import org.hibernate.type.descriptor.WrapperOptions @@ -53,10 +54,10 @@ class AbstractPartyDescriptor(private val identityService: IdentityService) : Ab override fun unwrap(value: AbstractParty?, type: Class, options: WrapperOptions): X? { return if (value != null) { if (AbstractParty::class.java.isAssignableFrom(type)) { - return value as X + return uncheckedCast(value) } if (String::class.java.isAssignableFrom(type)) { - return toString(value) as X + return uncheckedCast(toString(value)) } throw unknownUnwrap(type) } else { diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt index cf813a25d9..75c8c5548d 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/AbstractPartyToX500NameAsStringConverter.kt @@ -21,7 +21,7 @@ class AbstractPartyToX500NameAsStringConverter(private val identityService: Iden if (party != null) { val partyName = identityService.wellKnownPartyFromAnonymous(party)?.toString() if (partyName != null) return partyName - log.warn("Identity service unable to resolve AbstractParty: $party") + log.warn("Identity service unable to resolve AbstractParty: $party") } return null // non resolvable anonymous parties } diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt b/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt index 608c5f35d6..be1e01b1a5 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/DBCheckpointStorage.kt @@ -8,6 +8,7 @@ import net.corda.node.services.statemachine.Checkpoint import net.corda.nodeapi.internal.persistence.NODE_DATABASE_PREFIX import net.corda.nodeapi.internal.persistence.currentDBSession import org.apache.commons.lang.ArrayUtils.EMPTY_BYTE_ARRAY +import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* import java.util.stream.Stream @@ -21,7 +22,7 @@ import javax.persistence.Lob * Simple checkpoint key value storage in DB. */ class DBCheckpointStorage : CheckpointStorage { - val log = LoggerFactory.getLogger(this::class.java) + val log: Logger = LoggerFactory.getLogger(this::class.java) @Entity @javax.persistence.Table(name = "${NODE_DATABASE_PREFIX}checkpoints") diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt b/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt index 9e9137cf03..96e8520607 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/DBTransactionMappingStorage.kt @@ -41,10 +41,10 @@ class DBTransactionMappingStorage : StateMachineRecordedTransactionMappingStorag return AppendOnlyPersistentMap( toPersistentEntityKey = { it.toString() }, fromPersistentEntity = { Pair(SecureHash.parse(it.txId), StateMachineRunId(UUID.fromString(it.stateMachineRunId))) }, - toPersistentEntity = { key: SecureHash, value: StateMachineRunId -> + toPersistentEntity = { key: SecureHash, (uuid) -> DBTransactionMapping().apply { txId = key.toString() - stateMachineRunId = value.uuid.toString() + stateMachineRunId = uuid.toString() } }, persistentEntityClass = DBTransactionMapping::class.java @@ -63,5 +63,4 @@ class DBTransactionMappingStorage : StateMachineRecordedTransactionMappingStorag override fun track(): DataFeed, StateMachineTransactionMapping> = DataFeed(stateMachineTransactionMap.allPersisted().map { StateMachineTransactionMapping(it.second, it.first) }.toList(), updates.bufferUntilSubscribed().wrapWithDatabaseTransaction()) - } diff --git a/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt b/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt index caecf4f299..24c0d4973f 100644 --- a/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt +++ b/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt @@ -96,8 +96,7 @@ class NodeAttachmentService( @ElementCollection @Column(name = "contract_class_name") - @CollectionTable(name = "node_attchments_contracts", joinColumns = arrayOf( - JoinColumn(name = "att_id", referencedColumnName = "att_id")), + @CollectionTable(name = "node_attchments_contracts", joinColumns = [(JoinColumn(name = "att_id", referencedColumnName = "att_id"))], foreignKey = ForeignKey(name = "FK__ctr_class__attachments")) var contractClassNames: List? = null ) : Serializable @@ -210,13 +209,9 @@ class NodeAttachmentService( // If repeatedly looking for non-existing attachments becomes a performance issue, this is either indicating a // a problem somewhere else or this needs to be revisited. - private val attachmentContentCache = NonInvalidatingWeightBasedCache>>( + private val attachmentContentCache = NonInvalidatingWeightBasedCache( maxWeight = attachmentContentCacheSize, - weigher = object : Weigher>> { - override fun weigh(key: SecureHash, value: Optional>): Int { - return key.size + if (value.isPresent) value.get().second.size else 0 - } - }, + weigher = Weigher>> { key, value -> key.size + if (value.isPresent) value.get().second.size else 0 }, loadFunction = { Optional.ofNullable(loadAttachmentContent(it)) } ) @@ -258,6 +253,7 @@ class NodeAttachmentService( return null } + @Suppress("OverridingDeprecatedMember") override fun importAttachment(jar: InputStream): AttachmentId { return import(jar, UNKNOWN_UPLOADER, null) } @@ -296,8 +292,9 @@ class NodeAttachmentService( } } + @Suppress("OverridingDeprecatedMember") override fun importOrGetAttachment(jar: InputStream): AttachmentId = try { - importAttachment(jar) + import(jar, UNKNOWN_UPLOADER, null) } catch (faee: java.nio.file.FileAlreadyExistsException) { AttachmentId.parse(faee.message!!) } diff --git a/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt b/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt index eaf87efd24..bc2dce612c 100644 --- a/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt +++ b/node/src/main/kotlin/net/corda/node/services/rpc/NodeLoginModule.kt @@ -42,8 +42,8 @@ internal class NodeLoginModule : LoginModule { internal const val CERT_CHAIN_CHECKS_ARG = "CertChainChecks" internal const val USE_SSL_ARG = "useSsl" - internal val SECURITY_MANAGER_ARG = "RpcSecurityManager" - internal val LOGIN_LISTENER_ARG = "LoginListener" + internal const val SECURITY_MANAGER_ARG = "RpcSecurityManager" + internal const val LOGIN_LISTENER_ARG = "LoginListener" private val log = loggerFor() } diff --git a/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt b/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt index e8d819df0a..93a2afd2e0 100644 --- a/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt +++ b/node/src/main/kotlin/net/corda/node/services/rpc/RpcBrokerConfiguration.kt @@ -41,7 +41,7 @@ internal class RpcBrokerConfiguration(baseDirectory: Path, maxMessageSize: Int, initialiseSettings(maxMessageSize) - val nodeInternalRole = Role(NodeLoginModule.NODE_ROLE, true, true, true, true, true, true, true, true) + val nodeInternalRole = Role(NodeLoginModule.NODE_ROLE, true, true, true, true, true, true, true, true, true, true) val rolesAdderOnLogin = RolesAdderOnLogin { username -> "${RPCApi.RPC_CLIENT_QUEUE_NAME_PREFIX}.$username.#" to setOf(nodeInternalRole, restrictedRole( @@ -126,6 +126,6 @@ internal class RpcBrokerConfiguration(baseDirectory: Path, maxMessageSize: Int, private fun restrictedRole(name: String, send: Boolean = false, consume: Boolean = false, createDurableQueue: Boolean = false, deleteDurableQueue: Boolean = false, createNonDurableQueue: Boolean = false, deleteNonDurableQueue: Boolean = false, manage: Boolean = false, browse: Boolean = false): Role { - return Role(name, send, consume, createDurableQueue, deleteDurableQueue, createNonDurableQueue, deleteNonDurableQueue, manage, browse) + return Role(name, send, consume, createDurableQueue, deleteDurableQueue, createNonDurableQueue, deleteNonDurableQueue, manage, browse, createDurableQueue || createNonDurableQueue, deleteDurableQueue || deleteNonDurableQueue) } } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt b/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt index 62d5cee4d8..e5c181bf6a 100644 --- a/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt +++ b/node/src/main/kotlin/net/corda/node/services/schema/HibernateObserver.kt @@ -15,7 +15,6 @@ import net.corda.nodeapi.internal.persistence.contextTransaction import org.hibernate.FlushMode import rx.Observable - /** * Small data class bundling together a ContractState and a StateRef (as opposed to a TransactionState and StateRef * in StateAndRef) @@ -53,10 +52,7 @@ class HibernateObserver private constructor(private val config: HibernateConfigu @VisibleForTesting internal fun persistStatesWithSchema(statesAndRefs: List, schema: MappedSchema) { val sessionFactory = config.sessionFactoryForSchemas(setOf(schema)) - val session = sessionFactory.withOptions(). - connection(contextTransaction.connection). - flushMode(FlushMode.MANUAL). - openSession() + val session = sessionFactory.withOptions().connection(contextTransaction.connection).flushMode(FlushMode.MANUAL).openSession() session.use { thisSession -> statesAndRefs.forEach { val mappedObject = schemaService.generateMappedObject(it.state, schema) diff --git a/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt b/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt index 80a8499495..1b507d898b 100644 --- a/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt +++ b/node/src/main/kotlin/net/corda/node/services/schema/NodeSchemaService.kt @@ -87,9 +87,9 @@ class NodeSchemaService(extraSchemas: Set = emptySet(), includeNot // Because schema is always one supported by the state, just delegate. override fun generateMappedObject(state: ContractState, schema: MappedSchema): PersistentState { - if ((schema is VaultSchemaV1) && (state is LinearState)) + if ((schema === VaultSchemaV1) && (state is LinearState)) return VaultSchemaV1.VaultLinearStates(state.linearId, state.participants) - if ((schema is VaultSchemaV1) && (state is FungibleAsset<*>)) + if ((schema === VaultSchemaV1) && (state is FungibleAsset<*>)) return VaultSchemaV1.VaultFungibleStates(state.owner, state.amount.quantity, state.amount.token.issuer.party, state.amount.token.issuer.reference, state.participants) return (state as QueryableState).generateMappedObject(schema) } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt index 46332f0362..07d4ceb866 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/Action.kt @@ -102,17 +102,23 @@ sealed class Action { /** * Create a new database transaction. */ - object CreateTransaction : Action() { override fun toString() = "CreateTransaction" } + object CreateTransaction : Action() { + override fun toString() = "CreateTransaction" + } /** * Roll back the current database transaction. */ - object RollbackTransaction : Action() { override fun toString() = "RollbackTransaction" } + object RollbackTransaction : Action() { + override fun toString() = "RollbackTransaction" + } /** * Commit the current database transaction. */ - object CommitTransaction : Action() { override fun toString() = "CommitTransaction" } + object CommitTransaction : Action() { + override fun toString() = "CommitTransaction" + } /** * Execute the specified [operation]. @@ -131,7 +137,9 @@ sealed class Action { sealed class FlowRemovalReason { data class OrderlyFinish(val flowReturnValue: Any?) : FlowRemovalReason() data class ErrorFinish(val flowErrors: List) : FlowRemovalReason() - object SoftShutdown : FlowRemovalReason() { override fun toString() = "SoftShutdown" } + object SoftShutdown : FlowRemovalReason() { + override fun toString() = "SoftShutdown" + } // TODO Should we remove errored flows? How will the flow hospital work? Perhaps keep them in memory for a while, flush // them after a timeout, reload them on flow hospital request. In any case if we ever want to remove them // (e.g. temporarily) then add a case for that here. diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt index 36e968cf4b..683cd720e3 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/ActionExecutorImpl.kt @@ -124,8 +124,7 @@ class ActionExecutorImpl( @Suspendable private fun executePropagateErrors(action: Action.PropagateErrors) { - action.errorMessages.forEach { error -> - val exception = error.flowException + action.errorMessages.forEach { (exception) -> log.debug("Propagating error", exception) } for (sessionState in action.sessions) { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt index 5fe085496e..995ee4b2df 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/CountUpDownLatch.kt @@ -15,10 +15,10 @@ class CountUpDownLatch(initialValue: Int) { } override fun tryAcquireShared(arg: Int): Int { - if (arg >= 0) { - return if (state == arg) 1 else -1 + return if (arg >= 0) { + if (state == arg) 1 else -1 } else { - return if (state <= -arg) 1 else -1 + if (state <= -arg) 1 else -1 } } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt index 9694e64a09..921795038c 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/Event.kt @@ -19,7 +19,9 @@ sealed class Event { * should be idempotent in the [DoRemainingWork] event, meaning a second subsequent event shouldn't modify the state * or produce [Action]s. */ - object DoRemainingWork : Event() { override fun toString() = "DoRemainingWork" } + object DoRemainingWork : Event() { + override fun toString() = "DoRemainingWork" + } /** * Deliver a session message. @@ -50,12 +52,16 @@ sealed class Event { * Trigger a soft shutdown, removing the flow as soon as possible. This causes the flow to be removed as soon as * this event is processed. Note that on restart the flow will resume as normal. */ - object SoftShutdown : Event() { override fun toString() = "SoftShutdown" } + object SoftShutdown : Event() { + override fun toString() = "SoftShutdown" + } /** * Start error propagation on a errored flow. This may be triggered by e.g. a [FlowHospital]. */ - object StartErrorPropagation : Event() { override fun toString() = "StartErrorPropagation" } + object StartErrorPropagation : Event() { + override fun toString() = "StartErrorPropagation" + } /** * @@ -82,7 +88,9 @@ sealed class Event { * Scheduled by the flow. * */ - object LeaveSubFlow : Event() { override fun toString() = "LeaveSubFlow" } + object LeaveSubFlow : Event() { + override fun toString() = "LeaveSubFlow" + } /** * Signal a flow suspension. This causes the flow's stack and the state machine's state together with the suspending diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt index b04c59040a..bf493a45b9 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImpl.kt @@ -144,16 +144,16 @@ class FlowLogicRefFactoryImpl(private val classloader: ClassLoader) : SingletonS } private fun parameterAssignableFrom(type: Type, value: Any): Boolean { - if (type is Class<*>) { + return if (type is Class<*>) { if (type.isPrimitive) { - return Primitives.unwrap(value.javaClass) == type + Primitives.unwrap(value.javaClass) == type } else { - return type.isAssignableFrom(value.javaClass) + type.isAssignableFrom(value.javaClass) } } else if (type is ParameterizedType) { - return parameterAssignableFrom(type.rawType, value) + parameterAssignableFrom(type.rawType, value) } else { - return false + false } } } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt index 3ee44d3803..0f47417eb8 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/FlowMessaging.kt @@ -39,7 +39,7 @@ class FlowMessagingImpl(val serviceHub: ServiceHubInternal): FlowMessaging { companion object { val log = contextLogger() - val sessionTopic = "platform.session" + const val sessionTopic = "platform.session" } override fun start(onMessage: (ReceivedMessage, deduplicationHandler: DeduplicationHandler) -> Unit) { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt index 5481275f05..97fd21a3c0 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/SessionMessage.kt @@ -1,6 +1,5 @@ package net.corda.node.services.statemachine -import net.corda.core.crypto.random63BitValue import net.corda.core.flows.FlowException import net.corda.core.flows.FlowInfo import net.corda.core.serialization.CordaSerializable @@ -21,7 +20,6 @@ import java.security.SecureRandom @CordaSerializable sealed class SessionMessage - @CordaSerializable data class SessionId(val toLong: Long) { companion object { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt index f7460f4bab..f0613cbc87 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/SingleThreadedStateMachineManager.kt @@ -336,7 +336,7 @@ class SingleThreadedStateMachineManager( val flowId = sessionToFlow[recipientId] if (flowId == null) { deduplicationHandler.afterDatabaseTransaction() - if (sessionMessage.payload is EndSessionMessage) { + if (sessionMessage.payload === EndSessionMessage) { logger.debug { "Got ${EndSessionMessage::class.java.simpleName} for " + "unknown session $recipientId, discarding..." @@ -559,7 +559,7 @@ class SingleThreadedStateMachineManager( private fun addAndStartFlow(id: StateMachineRunId, flow: Flow) { val checkpoint = flow.fiber.snapshot().checkpoint for (sessionId in getFlowSessionIds(checkpoint)) { - sessionToFlow.put(sessionId, id) + sessionToFlow[sessionId] = id } mutex.locked { if (stopping) { @@ -568,7 +568,7 @@ class SingleThreadedStateMachineManager( } else { incrementLiveFibers() unfinishedFibers.countUp() - flows.put(id, flow) + flows[id] = flow flow.fiber.scheduleEvent(Event.DoRemainingWork) when (checkpoint.flowState) { is FlowState.Unstarted -> { diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt index 96edb248b0..087408c265 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/StateMachineManager.kt @@ -33,6 +33,7 @@ interface StateMachineManager { * Starts the state machine manager, loading and starting the state machines in storage. */ fun start(tokenizableServices: List) + /** * Stops the state machine manager gracefully, waiting until all but [allowedUnsuspendedFiberCount] flows reach the * next checkpoint. @@ -59,6 +60,7 @@ interface StateMachineManager { */ sealed class Change { abstract val logic: FlowLogic<*> + data class Add(override val logic: FlowLogic<*>) : Change() data class Removed(override val logic: FlowLogic<*>, val result: Try<*>) : Change() } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt index 86f8e239f0..23ee4a2d9f 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/DumpHistoryOnErrorInterceptor.kt @@ -47,5 +47,4 @@ class DumpHistoryOnErrorInterceptor(val delegate: TransitionExecutor) : Transiti return Pair(continuation, nextState) } - } diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt index f5e298fed8..4f7f140673 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/interceptors/MetricInterceptor.kt @@ -6,7 +6,7 @@ import net.corda.node.services.statemachine.* import net.corda.node.services.statemachine.transitions.FlowContinuation import net.corda.node.services.statemachine.transitions.TransitionResult -class MetricInterceptor(val metrics: MetricRegistry, val delegate: TransitionExecutor): TransitionExecutor { +class MetricInterceptor(val metrics: MetricRegistry, val delegate: TransitionExecutor) : TransitionExecutor { @Suspendable override fun executeTransition(fiber: FlowFiber, previousState: StateMachineState, event: Event, transition: TransitionResult, actionExecutor: ActionExecutor): Pair { val metricActionInterceptor = MetricActionInterceptor(metrics, actionExecutor) @@ -14,7 +14,7 @@ class MetricInterceptor(val metrics: MetricRegistry, val delegate: TransitionExe } } -class MetricActionInterceptor(val metrics: MetricRegistry, val delegate: ActionExecutor): ActionExecutor { +class MetricActionInterceptor(val metrics: MetricRegistry, val delegate: ActionExecutor) : ActionExecutor { @Suspendable override fun executeAction(fiber: FlowFiber, action: Action) { val context = metrics.timer("Flows.Actions.${action.javaClass.simpleName}").time() diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt index 074700e3f7..87fcb49ca6 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/DeliverSessionMessageTransition.kt @@ -38,7 +38,7 @@ class DeliverSessionMessageTransition( } else { val payload = event.sessionMessage.payload // Dispatch based on what kind of message it is. - val _exhaustive = when (payload) { + when (payload) { is ConfirmSessionMessage -> confirmMessageTransition(existingSession, payload) is DataSessionMessage -> dataMessageTransition(existingSession, payload) is ErrorSessionMessage -> errorMessageTransition(existingSession, payload) diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt index 55c7458d00..28d1d04486 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/StartedFlowTransition.kt @@ -250,7 +250,7 @@ class StartedFlowTransition( } else { val sessionMessage = DataSessionMessage(message) val deduplicationId = DeduplicationId.createForNormal(checkpoint, index++) - val _exhaustive = when (existingSessionState) { + when (existingSessionState) { is SessionState.Uninitiated -> { val initialMessage = createInitialSessionMessage(existingSessionState.initiatingSubFlow, sourceSessionId, message) actions.add(Action.SendInitial(existingSessionState.party, initialMessage, deduplicationId)) @@ -317,7 +317,7 @@ class StartedFlowTransition( val sessionState = checkpoint.sessions[sessionId]!! when (sessionState) { is SessionState.Initiated -> { - if (sessionState.initiatedState is InitiatedSessionState.Ended) { + if (sessionState.initiatedState === InitiatedSessionState.Ended) { UnexpectedFlowEndException( "Tried to access ended session $sessionId", cause = null, @@ -337,7 +337,7 @@ class StartedFlowTransition( val sessionState = checkpoint.sessions[sessionId]!! when (sessionState) { is SessionState.Initiated -> { - if (sessionState.initiatedState is InitiatedSessionState.Ended && + if (sessionState.initiatedState === InitiatedSessionState.Ended && sessionState.receivedMessages.isEmpty()) { UnexpectedFlowEndException( "Tried to access ended session $sessionId with empty buffer", diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt index 20441dbab3..a68407adc2 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/Transition.kt @@ -12,6 +12,7 @@ interface Transition { val context: TransitionContext /** The state the transition is starting in. */ val startingState: StateMachineState + /** The (almost) pure transition function. The only side-effect we allow is random number generation. */ fun transition(): TransitionResult diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt index 01715adde6..155cdb80bf 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionBuilder.kt @@ -68,7 +68,5 @@ class TransitionBuilder(val context: TransitionContext, initialState: StateMachi } } - - class CannotFindSessionException(sessionId: SessionId) : IllegalStateException("Couldn't find session with id $sessionId") class UnexpectedEventInState : IllegalStateException("Unexpected event") diff --git a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt index 43e934634b..979463368b 100644 --- a/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt +++ b/node/src/main/kotlin/net/corda/node/services/statemachine/transitions/TransitionResult.kt @@ -37,10 +37,14 @@ sealed class FlowContinuation { /** * Keep processing pending events. */ - object ProcessEvents : FlowContinuation() { override fun toString() = "ProcessEvents" } + object ProcessEvents : FlowContinuation() { + override fun toString() = "ProcessEvents" + } /** * Immediately abort the flow. Note that this does not imply an error condition. */ - object Abort : FlowContinuation() { override fun toString() = "Abort" } + object Abort : FlowContinuation() { + override fun toString() = "Abort" + } } diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt index 368502fb5f..e642dc858f 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/BFTSMaRtConfig.kt @@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit.MILLISECONDS class BFTSMaRtConfig(private val replicaAddresses: List, debug: Boolean, val exposeRaces: Boolean) : PathManager(Files.createTempDirectory("bft-smart-config")) { companion object { private val log = contextLogger() - internal val portIsClaimedFormat = "Port %s is claimed by another replica: %s" + internal const val portIsClaimedFormat = "Port %s is claimed by another replica: %s" } val clusterSize get() = replicaAddresses.size @@ -35,9 +35,9 @@ class BFTSMaRtConfig(private val replicaAddresses: List, deb } } configWriter("hosts.config") { - replicaAddresses.forEachIndexed { index, address -> + replicaAddresses.forEachIndexed { index, (host, port) -> // The documentation strongly recommends IP addresses: - println("$index ${InetAddress.getByName(address.host).hostAddress} ${address.port}") + println("$index ${InetAddress.getByName(host).hostAddress} $port") } } val systemConfig = String.format(javaClass.getResource("system.config.printf").readText(), n, maxFaultyReplicas(n), if (debug) 1 else 0, (0 until n).joinToString(",")) diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt b/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt index fbd7db4f93..1a3350ae48 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/OutOfProcessTransactionVerifierService.kt @@ -47,8 +47,7 @@ class OutOfProcessTransactionVerifierService( metrics.register(metric("VerificationsInFlight"), Gauge { verificationHandles.size }) responseConsumer.setMessageHandler { message -> val response = VerifierApi.VerificationResponse.fromClientMessage(message) - val handle = verificationHandles.remove(response.verificationId) ?: - throw VerificationResultForUnknownTransaction(response.verificationId) + val handle = verificationHandles.remove(response.verificationId) ?: throw VerificationResultForUnknownTransaction(response.verificationId) handle.durationTimerContext.stop() val exception = response.exception if (exception == null) { diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt b/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt index f54b442b9e..63988a1c8d 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/PersistentUniquenessProvider.kt @@ -33,7 +33,7 @@ import javax.persistence.* @ThreadSafe class PersistentUniquenessProvider(val clock: Clock) : UniquenessProvider, SingletonSerializeAsToken() { @MappedSuperclass - open class BaseComittedState( + class BaseComittedState( @EmbeddedId val id: PersistentStateRef, diff --git a/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt b/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt index 03fa2f3b73..71d5cf9e4e 100644 --- a/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt +++ b/node/src/main/kotlin/net/corda/node/services/transactions/RaftUniquenessProvider.kt @@ -72,11 +72,11 @@ class RaftUniquenessProvider( Pair(it.index, SecureHash.parse(it.value) as SecureHash)) }, - toPersistentEntity = { k: StateRef, v: Pair -> + toPersistentEntity = { k: StateRef, (first, second) -> CommittedState( PersistentStateRef(k), - v.second.toString(), - v.first) + second.toString(), + first) }, persistentEntityClass = CommittedState::class.java diff --git a/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt b/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt index 68f0854770..e5a6d29f25 100644 --- a/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt +++ b/node/src/main/kotlin/net/corda/node/services/upgrade/ContractUpgradeServiceImpl.kt @@ -47,7 +47,7 @@ class ContractUpgradeServiceImpl : ContractUpgradeService, SingletonSerializeAsT override fun getAuthorisedContractUpgrade(ref: StateRef) = authorisedUpgrade[ref.toString()] override fun storeAuthorisedContractUpgrade(ref: StateRef, upgradedContractClass: Class>) { - authorisedUpgrade.put(ref.toString(), upgradedContractClass.name) + authorisedUpgrade[ref.toString()] = upgradedContractClass.name } override fun removeAuthorisedContractUpgrade(ref: StateRef) { diff --git a/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt b/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt index 4f398608d5..e8a75c4ab5 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/HibernateQueryCriteriaParser.kt @@ -464,7 +464,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status)) } } else { - commonPredicates.put(predicateID, criteriaBuilder.equal(vaultStates.get(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status)) + commonPredicates[predicateID] = criteriaBuilder.equal(vaultStates.get(VaultSchemaV1.VaultStates::stateStatus.name), criteria.status) } } @@ -479,7 +479,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class(VaultSchemaV1.VaultStates::contractStateClassName.name).`in`(contractStateTypes.plus(existingTypes)))) } } else { - commonPredicates.put(predicateID, criteriaBuilder.and(vaultStates.get(VaultSchemaV1.VaultStates::contractStateClassName.name).`in`(contractStateTypes))) + commonPredicates[predicateID] = criteriaBuilder.and(vaultStates.get(VaultSchemaV1.VaultStates::contractStateClassName.name).`in`(contractStateTypes)) } } @@ -501,7 +501,7 @@ class HibernateQueryCriteriaParser(val contractStateType: Class("stateRef"), entityRoot.get("stateRef")) joinPredicates.add(joinPredicate) entityRoot @@ -527,22 +527,20 @@ class HibernateQueryCriteriaParser(val contractStateType: Class, String, String?> { - val entityClassAndColumnName: Triple, String, String?> = - when (sortAttribute) { - is Sort.CommonStateAttribute -> { - Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeParent, sortAttribute.attributeChild) - } - is Sort.VaultStateAttribute -> { - Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeName, null) - } - is Sort.LinearStateAttribute -> { - Triple(VaultSchemaV1.VaultLinearStates::class.java, sortAttribute.attributeName, null) - } - is Sort.FungibleStateAttribute -> { - Triple(VaultSchemaV1.VaultFungibleStates::class.java, sortAttribute.attributeName, null) - } - else -> throw VaultQueryException("Invalid sort attribute: $sortAttribute") - } - return entityClassAndColumnName + return when (sortAttribute) { + is Sort.CommonStateAttribute -> { + Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeParent, sortAttribute.attributeChild) + } + is Sort.VaultStateAttribute -> { + Triple(VaultSchemaV1.VaultStates::class.java, sortAttribute.attributeName, null) + } + is Sort.LinearStateAttribute -> { + Triple(VaultSchemaV1.VaultLinearStates::class.java, sortAttribute.attributeName, null) + } + is Sort.FungibleStateAttribute -> { + Triple(VaultSchemaV1.VaultFungibleStates::class.java, sortAttribute.attributeName, null) + } + else -> throw VaultQueryException("Invalid sort attribute: $sortAttribute") + } } } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt index 817d0d7a40..84957f4230 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/NodeVaultService.kt @@ -466,7 +466,7 @@ class NodeVaultService( } } if (stateRefs.isNotEmpty()) - statesAndRefs.addAll(servicesForResolution.loadStates(stateRefs) as Collection>) + statesAndRefs.addAll(uncheckedCast(servicesForResolution.loadStates(stateRefs))) return Vault.Page(states = statesAndRefs, statesMetadata = statesMeta, stateTypes = criteriaParser.stateTypes, totalStatesAvailable = totalStates, otherResults = otherResults) } diff --git a/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt b/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt index 576a2b2f5f..35f3867bbe 100644 --- a/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt +++ b/node/src/main/kotlin/net/corda/node/services/vault/VaultSchema.kt @@ -71,9 +71,7 @@ object VaultSchemaV1 : MappedSchema(schemaFamily = VaultSchema.javaClass, versio /** X500Name of participant parties **/ @ElementCollection @CollectionTable(name = "vault_linear_states_parts", - joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")), + joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))], foreignKey = ForeignKey(name = "FK__lin_stat_parts__lin_stat")) @Column(name = "participants") var participants: MutableSet? = null, @@ -104,9 +102,7 @@ object VaultSchemaV1 : MappedSchema(schemaFamily = VaultSchema.javaClass, versio /** X500Name of participant parties **/ @ElementCollection @CollectionTable(name = "vault_fungible_states_parts", - joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id")), + joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))], foreignKey = ForeignKey(name = "FK__fung_st_parts__fung_st")) @Column(name = "participants") var participants: MutableSet? = null, diff --git a/node/src/main/kotlin/net/corda/node/utilities/AddOrRemove.kt b/node/src/main/kotlin/net/corda/node/utilities/AddOrRemove.kt deleted file mode 100644 index 155e7853d2..0000000000 --- a/node/src/main/kotlin/net/corda/node/utilities/AddOrRemove.kt +++ /dev/null @@ -1,12 +0,0 @@ -package net.corda.node.utilities - -import net.corda.core.serialization.CordaSerializable - -/** - * Enum for when adding/removing something, for example adding or removing an entry in a directory. - */ -@CordaSerializable -enum class AddOrRemove { - ADD, - REMOVE -} diff --git a/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt b/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt index a65963289a..f707267dc2 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/AddressUtils.kt @@ -4,7 +4,7 @@ import java.net.InetAddress import java.net.NetworkInterface object AddressUtils { - private val REACHABLE_TIMEOUT_MS = 1000 + private const val REACHABLE_TIMEOUT_MS = 1000 /** Returns the first public IP address found on any of the network interfaces, or `null` if none found. */ fun tryDetectPublicIP(): InetAddress? { diff --git a/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt b/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt index 1523e24444..6cc14d7c5d 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/AffinityExecutor.kt @@ -36,10 +36,10 @@ interface AffinityExecutor : Executor { * way! Make sure the executor can't possibly be waiting for the calling thread. */ fun fetchFrom(fetcher: () -> T): T { - if (isOnThread) - return fetcher() + return if (isOnThread) + fetcher() else - return CompletableFuture.supplyAsync(Supplier { fetcher() }, this).get() + CompletableFuture.supplyAsync(Supplier { fetcher() }, this).get() } /** diff --git a/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt b/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt index ad3df17747..f7065c9807 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/AppendOnlyPersistentMap.kt @@ -23,7 +23,7 @@ abstract class AppendOnlyPersistentMapBase( private val log = contextLogger() } - abstract protected val cache: LoadingCache> + protected abstract val cache: LoadingCache> /** * Returns the value associated with the key, first loading that value from the storage if necessary. @@ -163,13 +163,9 @@ class WeightBasedAppendOnlyPersistentMap( fromPersistentEntity, toPersistentEntity, persistentEntityClass) { - override val cache = NonInvalidatingWeightBasedCache>( + override val cache = NonInvalidatingWeightBasedCache( maxWeight = maxWeight, - weigher = object : Weigher> { - override fun weigh(key: K, value: Optional): Int { - return weighingFunc(key, value) - } - }, + weigher = Weigher> { key, value -> weighingFunc(key, value) }, loadFunction = { key -> Optional.ofNullable(loadValue(key)) } ) } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt b/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt index 0c9e83dc60..8530fd769d 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/JVMAgentRegistry.kt @@ -44,9 +44,9 @@ object JVMAgentRegistry { path } else { (this::class.java.classLoader as? URLClassLoader) - ?.urLs - ?.map(URL::toPath) - ?.firstOrNull { it.fileName.toString() == jarFileName } + ?.urLs + ?.map(URL::toPath) + ?.firstOrNull { it.fileName.toString() == jarFileName } } } } \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt b/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt index c7fd6c0186..9d3734776d 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/NamedThreadFactory.kt @@ -5,13 +5,12 @@ import java.util.concurrent.Executors import java.util.concurrent.ThreadFactory import java.util.concurrent.atomic.AtomicInteger - /** * Utility class that allows to give threads arbitrary name prefixes when they are created * via an executor. It will use an underlying thread factory to create the actual thread * and then override the thread name with the prefix and an ever increasing number */ -class NamedThreadFactory(private val name:String, private val underlyingFactory: ThreadFactory) : ThreadFactory{ +class NamedThreadFactory(private val name: String, private val underlyingFactory: ThreadFactory) : ThreadFactory { val threadNumber = AtomicInteger(1) override fun newThread(runnable: Runnable?): Thread { val thread = underlyingFactory.newThread(runnable) diff --git a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt index d8840bacc2..5de030ddf8 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingCache.kt @@ -5,7 +5,6 @@ import com.github.benmanes.caffeine.cache.Caffeine import com.github.benmanes.caffeine.cache.LoadingCache import com.github.benmanes.caffeine.cache.Weigher - class NonInvalidatingCache private constructor( val cache: LoadingCache ) : LoadingCache by cache { @@ -36,7 +35,6 @@ class NonInvalidatingWeightBasedCache private constructor( constructor (maxWeight: Long, weigher: Weigher, loadFunction: (K) -> V) : this(buildCache(maxWeight, weigher, loadFunction)) - private companion object { private fun buildCache(maxWeight: Long, weigher: Weigher, loadFunction: (K) -> V): LoadingCache { val builder = Caffeine.newBuilder().maximumWeight(maxWeight).weigher(weigher) diff --git a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt index b1fef1d2e6..601825feaf 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/NonInvalidatingUnboundCache.kt @@ -10,7 +10,7 @@ class NonInvalidatingUnboundCache private constructor( val cache: LoadingCache ) : LoadingCache by cache { - constructor(loadFunction: (K) -> V, removalListener: RemovalListener = RemovalListener { key, value, cause -> }, + constructor(loadFunction: (K) -> V, removalListener: RemovalListener = RemovalListener { _, _, _ -> }, keysToPreload: () -> Iterable = { emptyList() }) : this(buildCache(loadFunction, removalListener, keysToPreload)) diff --git a/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt b/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt index 3f0d73d2ed..d26aaeca06 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/ObjectDiffer.kt @@ -59,10 +59,10 @@ data class DiffPath( object ObjectDiffer { fun diff(a: Any?, b: Any?): DiffTree? { if (a == null || b == null) { - if (a == b) { - return null + return if (a == b) { + null } else { - return DiffTree.Last(a, b) + DiffTree.Last(a, b) } } if (a != b) { @@ -72,34 +72,36 @@ object ObjectDiffer { // TODO deduplicate this code if (a is Map<*, *> && b is Map<*, *>) { val allKeys = a.keys + b.keys - val branches = allKeys.mapNotNull { key -> diff(a.get(key), b.get(key))?.let { key.toString() to it } } - if (branches.isEmpty()) { - return null + val branches = allKeys.mapNotNull { key -> diff(a[key], b[key])?.let { key.toString() to it } } + return if (branches.isEmpty()) { + null } else { - return DiffTree.Step(branches) + DiffTree.Step(branches) } } + // Apparently this is not always caught by the above as one might think. + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") if (a is java.util.Map<*, *> && b is java.util.Map<*, *>) { val allKeys = a.keySet() + b.keySet() val branches = allKeys.mapNotNull { key -> diff(a.get(key), b.get(key))?.let { key.toString() to it } } - if (branches.isEmpty()) { - return null + return if (branches.isEmpty()) { + null } else { - return DiffTree.Step(branches) + DiffTree.Step(branches) } } val aFields = getFieldFoci(a) val bFields = getFieldFoci(b) try { - if (aFields != bFields) { - return DiffTree.Last(a, b) + return if (aFields != bFields) { + DiffTree.Last(a, b) } else { // TODO need to account for cases where the fields don't match up (different subclasses) - val branches = aFields.map { field -> diff(field.get(a), field.get(b))?.let { field.name to it } }.filterNotNull() + val branches = aFields.mapNotNull { field -> diff(field.get(a), field.get(b))?.let { field.name to it } } if (branches.isEmpty()) { - return DiffTree.Last(a, b) + DiffTree.Last(a, b) } else { - return DiffTree.Step(branches) + DiffTree.Step(branches) } } } catch (throwable: Exception) { @@ -141,4 +143,4 @@ object ObjectDiffer { } return foci } -} +} \ No newline at end of file diff --git a/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt b/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt index 6cf4b0e369..7af94f617d 100644 --- a/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt +++ b/node/src/main/kotlin/net/corda/node/utilities/registration/HTTPNetworkRegistrationService.kt @@ -54,6 +54,7 @@ class HTTPNetworkRegistrationService(compatibilityZoneURL: URL) : NetworkRegistr } } -val HttpURLConnection.cacheControl: CacheControl get() { - return CacheControl.parse(Headers.of(headerFields.filterKeys { it != null }.mapValues { it.value[0] })) -} +val HttpURLConnection.cacheControl: CacheControl + get() { + return CacheControl.parse(Headers.of(headerFields.filterKeys { it != null }.mapValues { it.value[0] })) + } diff --git a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt index ef83ab852c..926eaa5d03 100644 --- a/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/CordaRPCOpsImplTest.kt @@ -13,7 +13,11 @@ import net.corda.core.flows.FlowLogic import net.corda.core.flows.StartableByRPC import net.corda.core.flows.StateMachineRunId import net.corda.core.identity.Party -import net.corda.core.messaging.* +import net.corda.core.messaging.CordaRPCOps +import net.corda.core.messaging.StateMachineUpdate +import net.corda.core.messaging.startFlow +import net.corda.core.messaging.vaultQueryBy +import net.corda.core.messaging.vaultTrackBy import net.corda.core.node.services.Vault import net.corda.core.node.services.queryBy import net.corda.core.transactions.SignedTransaction @@ -37,7 +41,6 @@ import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.expect import net.corda.testing.core.expectEvents import net.corda.testing.core.sequence -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.InternalMockNetwork.MockNode import net.corda.testing.node.internal.InternalMockNodeParameters @@ -66,7 +69,7 @@ private fun buildSubject(principal: String, permissionStrings: Set) = class CordaRPCOpsImplTest { private companion object { - val testJar = "net/corda/node/testing/test.jar" + const val testJar = "net/corda/node/testing/test.jar" } private lateinit var mockNet: InternalMockNetwork diff --git a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt index 39ca9a3727..d5787acec9 100644 --- a/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/events/NodeSchedulerServiceTest.kt @@ -108,7 +108,7 @@ class MockScheduledFlowRepository : ScheduledFlowRepository { if (map.containsKey(value.ref)) { result = true } - map.put(value.ref, value) + map[value.ref] = value return result } diff --git a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt index 031945431f..7ca6477ebc 100644 --- a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt @@ -43,7 +43,7 @@ class NetworkMapCacheTest { } @Test - fun `getNodeByLegalIdentity`() { + fun getNodeByLegalIdentity() { val aliceNode = mockNet.createPartyNode(ALICE_NAME) val alice = aliceNode.info.singleIdentity() val bobNode = mockNet.createPartyNode(BOB_NAME) @@ -57,7 +57,7 @@ class NetworkMapCacheTest { } @Test - fun `getPeerByLegalName`() { + fun getPeerByLegalName() { val aliceNode = mockNet.createPartyNode(ALICE_NAME) val bobNode = mockNet.createPartyNode(BOB_NAME) val bobCache: NetworkMapCache = bobNode.services.networkMapCache diff --git a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt index 94129616fb..27a79cb308 100644 --- a/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/network/NetworkMapClientTest.kt @@ -2,13 +2,13 @@ package net.corda.node.services.network import net.corda.core.crypto.Crypto import net.corda.core.crypto.sha256 -import net.corda.core.internal.* +import net.corda.core.internal.sign import net.corda.core.serialization.serialize import net.corda.core.utilities.seconds +import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.ALICE_NAME import net.corda.testing.core.BOB_NAME import net.corda.testing.core.SerializationEnvironmentRule -import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.driver.PortAllocation import net.corda.testing.internal.DEV_ROOT_CA import net.corda.testing.internal.TestNodeInfoBuilder @@ -25,7 +25,6 @@ import java.io.IOException import java.net.URL import java.time.Instant import java.time.temporal.ChronoUnit -import java.util.* import kotlin.test.assertEquals class NetworkMapClientTest { diff --git a/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt b/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt index 794262e6fd..975b2e077d 100644 --- a/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/network/NetworkParametersReaderTest.kt @@ -20,6 +20,7 @@ import org.junit.Before import org.junit.Rule import org.junit.Test import java.net.URL +import java.nio.file.FileSystem import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -28,7 +29,7 @@ class NetworkParametersReaderTest { @JvmField val testSerialization = SerializationEnvironmentRule(true) - val fs = Jimfs.newFileSystem(Configuration.unix()) + val fs: FileSystem = Jimfs.newFileSystem(Configuration.unix()) private val cacheTimeout = 100000.seconds private lateinit var server: NetworkMapServer diff --git a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt index 6aa94f993a..3570a6d5dd 100644 --- a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowFrameworkTests.kt @@ -156,7 +156,7 @@ class FlowFrameworkTests { bobNode.registerFlowFactory(WaitForOtherSideEndBeforeSendAndReceive::class) { NoOpFlow() } val sessionEndReceived = Semaphore(0) receivedSessionMessagesObservable().filter { - it.message is ExistingSessionMessage && it.message.payload is EndSessionMessage + it.message is ExistingSessionMessage && it.message.payload === EndSessionMessage }.subscribe { sessionEndReceived.release() } val resultFuture = aliceNode.services.startFlow( WaitForOtherSideEndBeforeSendAndReceive(bob, sessionEndReceived)).resultFuture diff --git a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt index b0953afdc3..d6e0dd7d06 100644 --- a/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt +++ b/node/src/test/kotlin/net/corda/node/services/statemachine/FlowLogicRefFactoryImplTest.kt @@ -6,7 +6,6 @@ import net.corda.core.flows.SchedulableFlow import org.junit.Test import java.time.Duration import kotlin.reflect.jvm.jvmName -import kotlin.test.assertEquals class FlowLogicRefFactoryImplTest { diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt index 9b016ea8ec..59338d5f06 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryExceptionsTests.kt @@ -17,7 +17,8 @@ import org.junit.rules.ExpectedException class VaultQueryExceptionsTests : VaultQueryParties by rule { companion object { - @ClassRule @JvmField + @ClassRule + @JvmField val rule = object : VaultQueryTestRule() { override val cordappPackages = listOf( "net.corda.testing.contracts", diff --git a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt index 328c92b717..4c021b48c2 100644 --- a/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt +++ b/node/src/test/kotlin/net/corda/node/services/vault/VaultQueryTests.kt @@ -2201,7 +2201,7 @@ abstract class VaultQueryTestsBase : VaultQueryParties { } @Test - fun `unconsumedCashStatesForSpending_single_issuer_reference`() { + fun unconsumedCashStatesForSpending_single_issuer_reference() { database.transaction { vaultFiller.fillWithSomeTestCash(1000.DOLLARS, notaryServices, 1, DUMMY_CASH_ISSUER) this.session.flush() diff --git a/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt b/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt index b1994a3d0c..28423baed6 100644 --- a/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt +++ b/node/src/test/kotlin/net/corda/node/utilities/AffinityExecutorTests.kt @@ -8,8 +8,8 @@ import java.util.concurrent.atomic.AtomicReference import kotlin.test.* class AffinityExecutorTests { - var _executor: AffinityExecutor.ServiceAffinityExecutor? = null - val executor: AffinityExecutor.ServiceAffinityExecutor get() = _executor!! + private var _executor: AffinityExecutor.ServiceAffinityExecutor? = null + private val executor: AffinityExecutor.ServiceAffinityExecutor get() = _executor!! @After fun shutdown() { diff --git a/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt b/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt index 7745f1a63b..c5add42c8a 100644 --- a/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt +++ b/node/src/test/kotlin/net/corda/node/utilities/PersistentMapTests.kt @@ -35,7 +35,7 @@ class PersistentMapTests { database.transaction { val map = createTestMap() - map.put(testHash, "test") + map[testHash] = "test" assertEquals(map[testHash], "test") } @@ -67,9 +67,9 @@ class PersistentMapTests { database.transaction { val map = createTestMap() - map.put(testHash, "test") + map[testHash] = "test" - map.put(testHash, "updated") + map[testHash] = "updated" assertEquals("updated", map[testHash]) } @@ -129,7 +129,7 @@ class PersistentMapTests { database.transaction { val map = createTestMap() - map.put(testHash, "test") + map[testHash] = "test" assertEquals(map[testHash], "test") } diff --git a/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt b/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt index dfaf92f775..04f157429c 100644 --- a/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt +++ b/samples/attachment-demo/src/integration-test/kotlin/net/corda/attachmentdemo/AttachmentDemoTest.kt @@ -8,10 +8,9 @@ import net.corda.node.services.Permissions.Companion.startFlow import net.corda.testing.core.DUMMY_BANK_A_NAME import net.corda.testing.core.DUMMY_BANK_B_NAME import net.corda.testing.driver.DriverParameters -import net.corda.testing.node.User import net.corda.testing.driver.PortAllocation import net.corda.testing.driver.driver -import net.corda.testing.driver.internal.NodeHandleInternal +import net.corda.testing.node.User import org.junit.Test import java.util.concurrent.CompletableFuture.supplyAsync diff --git a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt index a6a49cc01a..ebbfdab4b6 100644 --- a/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt +++ b/samples/attachment-demo/src/main/kotlin/net/corda/attachmentdemo/AttachmentDemo.kt @@ -183,7 +183,7 @@ private fun printHelp(parser: OptionParser) { parser.printHelpOn(System.out) } -val ATTACHMENT_PROGRAM_ID = "net.corda.attachmentdemo.AttachmentContract" +const val ATTACHMENT_PROGRAM_ID = "net.corda.attachmentdemo.AttachmentContract" class AttachmentContract : Contract { override fun verify(tx: LedgerTransaction) { diff --git a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt index ef020df6ef..231e6781d9 100644 --- a/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt +++ b/samples/bank-of-corda-demo/src/main/kotlin/net/corda/bank/api/BankOfCordaClientApi.kt @@ -38,8 +38,7 @@ object BankOfCordaClientApi { // Resolve parties via RPC val issueToParty = rpc.wellKnownPartyFromX500Name(params.issueToPartyName) ?: throw IllegalStateException("Unable to locate ${params.issueToPartyName} in Network Map Service") - val notaryLegalIdentity = rpc.notaryIdentities().firstOrNull { it.name == params.notaryName } ?: - throw IllegalStateException("Couldn't locate notary ${params.notaryName} in NetworkMapCache") + val notaryLegalIdentity = rpc.notaryIdentities().firstOrNull { it.name == params.notaryName } ?: throw IllegalStateException("Couldn't locate notary ${params.notaryName} in NetworkMapCache") val anonymous = true val issuerBankPartyRef = OpaqueBytes.of(params.issuerBankPartyRef.toByte()) diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt index a24edcff31..1f4a23d437 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/api/NodeInterestRates.kt @@ -234,7 +234,7 @@ object NodeInterestRates { fun getRate(tenor: Tenor): BigDecimal? { return rates.getOrElse(tenor) { val rate = interpolate(tenor) - if (rate != null) rates.put(tenor, rate) + if (rate != null) rates[tenor] = rate return rate } } diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt index 735c265ed6..ba307993e3 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRS.kt @@ -1,15 +1,40 @@ package net.corda.irs.contract import com.fasterxml.jackson.annotation.JsonIgnoreProperties -import net.corda.core.contracts.* +import net.corda.core.contracts.Amount +import net.corda.core.contracts.Command +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.CommandWithParties +import net.corda.core.contracts.Contract +import net.corda.core.contracts.SchedulableState +import net.corda.core.contracts.ScheduledActivity +import net.corda.core.contracts.StateAndContract +import net.corda.core.contracts.StateAndRef +import net.corda.core.contracts.StateRef +import net.corda.core.contracts.TransactionState +import net.corda.core.contracts.TypeOnlyCommandData +import net.corda.core.contracts.UniqueIdentifier +import net.corda.core.contracts.requireThat +import net.corda.core.contracts.select import net.corda.core.flows.FlowLogicRefFactory import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party import net.corda.core.serialization.CordaSerializable import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder -import net.corda.finance.contracts.* -import net.corda.irs.flows.FixingFlow +import net.corda.finance.contracts.AccrualAdjustment +import net.corda.finance.contracts.BusinessCalendar +import net.corda.finance.contracts.DateRollConvention +import net.corda.finance.contracts.DateRollDirection +import net.corda.finance.contracts.DayCountBasisDay +import net.corda.finance.contracts.DayCountBasisYear +import net.corda.finance.contracts.Expression +import net.corda.finance.contracts.Fix +import net.corda.finance.contracts.FixOf +import net.corda.finance.contracts.FixableDealState +import net.corda.finance.contracts.Frequency +import net.corda.finance.contracts.PaymentRule +import net.corda.finance.contracts.Tenor import net.corda.irs.utilities.suggestInterestRateAnnouncementTimeWindow import org.apache.commons.jexl3.JexlBuilder import org.apache.commons.jexl3.MapContext @@ -65,7 +90,7 @@ abstract class RatePaymentEvent(date: LocalDate, val notional: Amount, val rate: Rate) : PaymentEvent(date) { companion object { - val CSVHeader = "AccrualStartDate,AccrualEndDate,DayCountFactor,Days,Date,Ccy,Notional,Rate,Flow" + const val CSVHeader = "AccrualStartDate,AccrualEndDate,DayCountFactor,Days,Date,Ccy,Notional,Rate,Flow" } override fun calculate(): Amount = flow @@ -489,7 +514,7 @@ class InterestRateSwap : Contract { } private fun verifyAgreeCommand(inputs: List, outputs: List) { - val irs = outputs.filterIsInstance().single() + val irs = outputs.single() requireThat { "There are no in states for an agreement" using inputs.isEmpty() "There are events in the fix schedule" using (irs.calculation.fixedLegPaymentSchedule.isNotEmpty()) @@ -511,8 +536,8 @@ class InterestRateSwap : Contract { } private fun verifyFixCommand(inputs: List, outputs: List, command: CommandWithParties) { - val irs = outputs.filterIsInstance().single() - val prevIrs = inputs.filterIsInstance().single() + val irs = outputs.single() + val prevIrs = inputs.single() val paymentDifferences = getFloatingLegPaymentsDifferences(prevIrs.calculation.floatingLegPaymentSchedule, irs.calculation.floatingLegPaymentSchedule) // Having both of these tests are "redundant" as far as verify() goes, however, by performing both @@ -550,7 +575,7 @@ class InterestRateSwap : Contract { } private fun verifyMatureCommand(inputs: List, outputs: List) { - val irs = inputs.filterIsInstance().single() + val irs = inputs.single() requireThat { "No more fixings to be applied" using (irs.calculation.nextFixingDate() == null) "The irs is fully consumed and there is no id matched output state" using outputs.isEmpty() diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt index 3caa9e21c2..42447c7abc 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSExport.kt @@ -2,6 +2,6 @@ package net.corda.irs.contract fun InterestRateSwap.State.exportIRSToCSV(): String = "Fixed Leg\n" + FixedRatePaymentEvent.CSVHeader + "\n" + - this.calculation.fixedLegPaymentSchedule.toSortedMap().values.map { it.asCSV() }.joinToString("\n") + "\n" + + this.calculation.fixedLegPaymentSchedule.toSortedMap().values.joinToString("\n") { it.asCSV() } + "\n" + "Floating Leg\n" + FloatingRatePaymentEvent.CSVHeader + "\n" + - this.calculation.floatingLegPaymentSchedule.toSortedMap().values.map { it.asCSV() }.joinToString("\n") + "\n" + this.calculation.floatingLegPaymentSchedule.toSortedMap().values.joinToString("\n") { it.asCSV() } + "\n" diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt index c362e602a5..44b77fcba2 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/contract/IRSUtils.kt @@ -8,7 +8,6 @@ import net.corda.finance.contracts.Tenor import java.math.BigDecimal import java.util.* - // Things in here will move to the general utils class when we've hammered out various discussions regarding amounts, dates, oracle etc. /** diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt index 9da48655a9..89823e2d4c 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/AutoOfferFlow.kt @@ -75,7 +75,6 @@ object AutoOfferFlow { subFlow(ReportToRegulatorFlow(regulator, finalTx)) return finalTx } - } @InitiatingFlow diff --git a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt index 3c9471f76a..2ac6cb1bcf 100644 --- a/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt +++ b/samples/irs-demo/cordapp/src/main/kotlin/net/corda/irs/flows/FixingFlow.kt @@ -69,8 +69,8 @@ object FixingFlow { @Suspendable override fun filtering(elem: Any): Boolean { return when (elem) { - // Only expose Fix commands in which the oracle is on the list of requested signers - // to the oracle node, to avoid leaking privacy + // Only expose Fix commands in which the oracle is on the list of requested signers + // to the oracle node, to avoid leaking privacy is Command<*> -> handshake.payload.oracle.owningKey in elem.signers && elem.value is Fix else -> false } @@ -99,12 +99,12 @@ object FixingFlow { override val notaryParty: Party get() = dealToFix.state.notary - @Suspendable override fun checkProposal(stx: SignedTransaction) = requireThat { + @Suspendable + override fun checkProposal(stx: SignedTransaction) = requireThat { // Add some constraints here. } } - /** Used to set up the session between [Floater] and [Fixer] */ @CordaSerializable data class FixingSession(val ref: StateRef, val oracle: Party) diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt index 4c27556e87..e77a092913 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/api/OracleNodeTearOffTests.kt @@ -1,6 +1,5 @@ package net.corda.irs.api -import com.google.common.collect.testing.Helpers import com.google.common.collect.testing.Helpers.assertContains import net.corda.core.contracts.Command import net.corda.core.contracts.TransactionState @@ -16,7 +15,11 @@ 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.* +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.internal.LogHelper import net.corda.testing.node.MockNetwork import net.corda.testing.node.MockNodeParameters diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt index 490f587303..6b7eca03e0 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/contract/IRSTests.kt @@ -262,7 +262,7 @@ class IRSTests { */ private fun generateIRSTxn(irsSelect: Int): SignedTransaction { val dummyIRS = createDummyIRS(irsSelect) - val genTX: SignedTransaction = run { + return run { val gtx = InterestRateSwap().generateAgreement( fixedLeg = dummyIRS.fixedLeg, floatingLeg = dummyIRS.floatingLeg, @@ -276,7 +276,6 @@ class IRSTests { val ptx2 = miniCorpServices.addSignature(ptx1) notaryServices.addSignature(ptx2) } - return genTX } /** diff --git a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt index ae2dadab5e..428641f238 100644 --- a/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt +++ b/samples/irs-demo/cordapp/src/test/kotlin/net/corda/irs/flows/UpdateBusinessDayFlow.kt @@ -42,7 +42,7 @@ object UpdateBusinessDayFlow { } @Suspendable - override fun call(): Unit { + override fun call() { progressTracker.currentStep = NOTIFYING for (recipient in getRecipients()) { doNextRecipient(recipient) diff --git a/samples/irs-demo/src/system-test/kotlin/IRSDemoDockerTest.kt b/samples/irs-demo/src/system-test/kotlin/net/corda/irs/IRSDemoDockerTest.kt similarity index 85% rename from samples/irs-demo/src/system-test/kotlin/IRSDemoDockerTest.kt rename to samples/irs-demo/src/system-test/kotlin/net/corda/irs/IRSDemoDockerTest.kt index cce25fa4f3..1b3f6c3ece 100644 --- a/samples/irs-demo/src/system-test/kotlin/IRSDemoDockerTest.kt +++ b/samples/irs-demo/src/system-test/kotlin/net/corda/irs/IRSDemoDockerTest.kt @@ -1,18 +1,15 @@ package net.corda.irs import com.palantir.docker.compose.DockerComposeRule +import com.palantir.docker.compose.ImmutableDockerComposeRule import com.palantir.docker.compose.configuration.DockerComposeFiles import com.palantir.docker.compose.connection.waiting.HealthChecks import org.junit.ClassRule import org.junit.Test import org.openqa.selenium.By -import org.openqa.selenium.OutputType import org.openqa.selenium.WebElement import org.openqa.selenium.phantomjs.PhantomJSDriver import org.openqa.selenium.support.ui.WebDriverWait -import java.nio.file.Files -import java.nio.file.Paths -import java.nio.file.StandardCopyOption import kotlin.test.assertNotNull import kotlin.test.assertTrue @@ -33,26 +30,22 @@ class IRSDemoDockerTest { @ClassRule @JvmField - var docker = DockerComposeRule.builder() + var docker: ImmutableDockerComposeRule = DockerComposeRule.builder() .files(DockerComposeFiles.from( System.getProperty("CORDAPP_DOCKER_COMPOSE"), System.getProperty("WEB_DOCKER_COMPOSE"))) - .waitingForService("web-a", HealthChecks.toRespondOverHttp(8080, { port -> port.inFormat("http://\$HOST:\$EXTERNAL_PORT") })) + .waitingForService("web-a", HealthChecks.toRespondOverHttp(8080, { port -> port.inFormat("http://\$HOST:\$EXTERNAL_PORT") })) .build() } @Test fun `runs IRS demo selenium phantomjs`() { - val driver = PhantomJSDriver() - val webAPort = docker.containers() - .container("web-a") - .port(8080) + val webAPort = docker.containers().container("web-a").port(8080) - - driver.get("http://${webAPort.ip}:${webAPort.externalPort}"); + driver.get("http://${webAPort.ip}:${webAPort.externalPort}") //no deals on fresh interface val dealRows = driver.findElementsByCssSelector("table#deal-list tbody tr") diff --git a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt index 77d5c31368..76065ac5dd 100644 --- a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt +++ b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/IrsDemoWebApplication.kt @@ -23,19 +23,19 @@ import org.springframework.context.annotation.Bean @SpringBootApplication class IrsDemoWebApplication { @Value("\${corda.host}") - lateinit var cordaHost:String + lateinit var cordaHost: String @Value("\${corda.user}") - lateinit var cordaUser:String + lateinit var cordaUser: String @Value("\${corda.password}") - lateinit var cordaPassword:String + lateinit var cordaPassword: String @Bean fun rpcClient(): CordaRPCOps { log.info("Connecting to Corda on $cordaHost using username $cordaUser and password $cordaPassword") // TODO remove this when CordaRPC gets proper connection retry, please - var maxRetries = 100; + var maxRetries = 100 do { try { return CordaRPCClient(NetworkHostAndPort.parse(cordaHost)).start(cordaUser, cordaPassword).proxy @@ -60,7 +60,8 @@ class IrsDemoWebApplication { companion object { private val log = LoggerFactory.getLogger(this::class.java) - @JvmStatic fun main(args: Array) { + @JvmStatic + fun main(args: Array) { SpringApplication.run(IrsDemoWebApplication::class.java, *args) } } diff --git a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt index f242edace4..09cba2437c 100644 --- a/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt +++ b/samples/irs-demo/web/src/main/kotlin/net/corda/irs/web/api/InterestSwapRestAPI.kt @@ -48,15 +48,13 @@ class InterestRateSwapAPI { } } - @Autowired lateinit var rpc: CordaRPCOps private fun getAllDeals(): Array { val vault = rpc.vaultQueryBy().states val states = vault.filterStatesOfType() - val swaps = states.map { it.state.data }.toTypedArray() - return swaps + return states.map { it.state.data }.toTypedArray() } @GetMapping("/deals") diff --git a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt index cbddd8a4b3..c1d336eba8 100644 --- a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt +++ b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/IrsDemoWebApplicationTests.kt @@ -8,12 +8,12 @@ import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) -@SpringBootTest(properties = arrayOf("corda.host=localhost:12345", "corda.user=user", "corda.password=password")) +@SpringBootTest(properties = ["corda.host=localhost:12345", "corda.user=user", "corda.password=password"]) class IrsDemoWebApplicationTests { - @MockBean - lateinit var rpc: CordaRPCOps + @MockBean + lateinit var rpc: CordaRPCOps - @Test - fun contextLoads() { - } + @Test + fun contextLoads() { + } } diff --git a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt index eb51e47470..93a2b25214 100644 --- a/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt +++ b/samples/irs-demo/web/src/test/kotlin/net/corda/irs/web/demo/IrsDemoClientApi.kt @@ -29,6 +29,6 @@ class IRSDemoClientApi(hostAndPort: NetworkHostAndPort) { } private companion object { - private val apiRoot = "api/irs" + private const val apiRoot = "api/irs" } } diff --git a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt index 0a465ca3c8..c1b3fa532a 100644 --- a/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt +++ b/samples/network-visualiser/src/main/kotlin/net/corda/netmap/simulation/Simulation.kt @@ -11,7 +11,6 @@ import net.corda.node.internal.StartedNode import net.corda.node.services.statemachine.StateMachineManager import net.corda.testing.core.TestIdentity import net.corda.testing.node.InMemoryMessagingNetwork -import net.corda.testing.node.MockNodeParameters import net.corda.testing.node.MockServices.Companion.makeTestDataSourceProperties import net.corda.testing.node.TestClock import net.corda.testing.node.internal.InternalMockNetwork @@ -188,7 +187,7 @@ abstract class Simulation(val networkSendManuallyPumped: Boolean, } } - val networkInitialisationFinished = allOf(*mockNet.nodes.map { it.nodeReadyFuture.toCompletableFuture() }.toTypedArray()) + val networkInitialisationFinished: CompletableFuture = allOf(*mockNet.nodes.map { it.nodeReadyFuture.toCompletableFuture() }.toTypedArray()) fun start(): Future { mockNet.startNodes() diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt index c696730bb5..0a90853a70 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/BFTNotaryCordform.kt @@ -16,7 +16,7 @@ import java.nio.file.Paths fun main(args: Array) = BFTNotaryCordform().nodeRunner().deployAndRunNodes() -private val clusterSize = 4 // Minimum size that tolerates a faulty replica. +private const val clusterSize = 4 // Minimum size that tolerates a faulty replica. private val notaryNames = createNotaryNames(clusterSize) // This is not the intended final design for how to use CordformDefinition, please treat this as experimental and DO diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt index 746be5db2f..d914d8b3c4 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/RaftNotaryCordform.kt @@ -47,7 +47,7 @@ class RaftNotaryCordform : CordformDefinition() { } fun notaryNode(index: Int, nodePort: Int, clusterPort: Int? = null, configure: CordformNode.() -> Unit) = node { name(notaryNames[index]) - val clusterAddresses = if (clusterPort != null ) listOf(NetworkHostAndPort("localhost", clusterPort)) else emptyList() + val clusterAddresses = if (clusterPort != null) listOf(NetworkHostAndPort("localhost", clusterPort)) else emptyList() notary(NotaryConfig(validating = true, raft = RaftConfig(NetworkHostAndPort("localhost", nodePort), clusterAddresses))) configure() devMode(true) diff --git a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt index c3337e61e8..5ea916d51e 100644 --- a/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt +++ b/samples/notary-demo/src/main/kotlin/net/corda/notarydemo/flows/DummyIssueAndMove.kt @@ -15,7 +15,7 @@ import net.corda.core.transactions.TransactionBuilder @StartableByRPC class DummyIssueAndMove(private val notary: Party, private val counterpartyNode: Party, private val discriminator: Int) : FlowLogic() { companion object { - private val DO_NOTHING_PROGRAM_ID = "net.corda.notarydemo.flows.DummyIssueAndMove\$DoNothingContract" + private const val DO_NOTHING_PROGRAM_ID = "net.corda.notarydemo.flows.DummyIssueAndMove\$DoNothingContract" } class DoNothingContract : Contract { diff --git a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt index 98e490e68d..ac96e95d38 100644 --- a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt +++ b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioState.kt @@ -11,7 +11,7 @@ import java.time.LocalDate import java.time.ZoneOffset import java.time.temporal.ChronoUnit -val PORTFOLIO_SWAP_PROGRAM_ID = "net.corda.vega.contracts.PortfolioSwap" +const val PORTFOLIO_SWAP_PROGRAM_ID = "net.corda.vega.contracts.PortfolioSwap" /** * Represents an aggregate set of trades agreed between two parties and a possible valuation of that portfolio at a diff --git a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt index e0c3ba4b9a..588f855c62 100644 --- a/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt +++ b/samples/simm-valuation-demo/contracts-states/src/main/kotlin/net/corda/vega/contracts/PortfolioSwap.kt @@ -29,7 +29,6 @@ data class PortfolioSwap(private val blank: Void? = null) : Contract { "the valuer hasn't changed" using (inputs[0].valuer == outputs[0].valuer) "the linear id hasn't changed" using (inputs[0].linearId == outputs[0].linearId) } - } } } diff --git a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java index 1f81eb3015..3b25e8f0f2 100644 --- a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java +++ b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/ExampleMarketDataBuilder.java @@ -131,7 +131,7 @@ public abstract class ExampleMarketDataBuilder { } if (url.getProtocol() != null && "jar".equals(url.getProtocol().toLowerCase(Locale.ENGLISH))) { // Inside a JAR - int classSeparatorIdx = url.getFile().indexOf("!"); + int classSeparatorIdx = url.getFile().indexOf('!'); if (classSeparatorIdx == -1) { throw new IllegalArgumentException(Messages.format("Unexpected JAR file URL: {}", url)); } @@ -340,9 +340,9 @@ public abstract class ExampleMarketDataBuilder { CharSource inputSource = cdsYieldCurvesResource.getCharSource(); Map yieldCuves = MarkitYieldCurveDataParser.parse(inputSource); - for (IsdaYieldCurveInputsId id : yieldCuves.keySet()) { - IsdaYieldCurveInputs curveInputs = yieldCuves.get(id); - builder.addValue(id, curveInputs); + for (Map.Entry isdaYieldCurveInputsIdIsdaYieldCurveInputsEntry : yieldCuves.entrySet()) { + IsdaYieldCurveInputs curveInputs = isdaYieldCurveInputsIdIsdaYieldCurveInputsEntry.getValue(); + builder.addValue(isdaYieldCurveInputsIdIsdaYieldCurveInputsEntry.getKey(), curveInputs); } } diff --git a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java index 9f220e2e58..798aa23592 100644 --- a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java +++ b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitIndexCreditCurveDataParser.java @@ -120,16 +120,12 @@ public class MarkitIndexCreditCurveDataParser { spread = parseRate(compositeSpreadText); } - List points = curveData.get(id); - if (points == null) { - points = Lists.newArrayList(); - curveData.put(id, points); - } + List points = curveData.computeIfAbsent(id, k -> Lists.newArrayList()); points.add(new Point(term, maturity, spread)); } - for (IsdaIndexCreditCurveInputsId curveId : curveData.keySet()) { - MarkitRedCode redCode = MarkitRedCode.from(curveId.getReferenceInformation().getIndexId()); + for (Map.Entry> isdaIndexCreditCurveInputsIdListEntry : curveData.entrySet()) { + MarkitRedCode redCode = MarkitRedCode.from((isdaIndexCreditCurveInputsIdListEntry.getKey()).getReferenceInformation().getIndexId()); StaticData staticData = staticDataMap.get(redCode); ArgChecker.notNull(staticData, "Did not find a static data record for " + redCode); CdsConvention convention = staticData.getConvention(); @@ -137,9 +133,9 @@ public class MarkitIndexCreditCurveDataParser { double indexFactor = staticData.getIndexFactor(); // TODO add fromDate handling - String creditCurveName = curveId.toString(); + String creditCurveName = (isdaIndexCreditCurveInputsIdListEntry.getKey()).toString(); - List points = curveData.get(curveId); + List points = isdaIndexCreditCurveInputsIdListEntry.getValue(); Period[] periods = points.stream().map(s -> s.getTenor().getPeriod()).toArray(Period[]::new); LocalDate[] endDates = points.stream().map(s -> s.getDate()).toArray(LocalDate[]::new); @@ -153,9 +149,9 @@ public class MarkitIndexCreditCurveDataParser { convention, indexFactor); - builder.addValue(curveId, curveInputs); + builder.addValue(isdaIndexCreditCurveInputsIdListEntry.getKey(), curveInputs); - IsdaIndexRecoveryRateId recoveryRateId = IsdaIndexRecoveryRateId.of(curveId.getReferenceInformation()); + IsdaIndexRecoveryRateId recoveryRateId = IsdaIndexRecoveryRateId.of((isdaIndexCreditCurveInputsIdListEntry.getKey()).getReferenceInformation()); CdsRecoveryRate cdsRecoveryRate = CdsRecoveryRate.of(recoveryRate); builder.addValue(recoveryRateId, cdsRecoveryRate); diff --git a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java index c47caacf54..c030c83e7b 100644 --- a/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java +++ b/samples/simm-valuation-demo/flows/src/main/java/com/opengamma/strata/examples/marketdata/credit/markit/MarkitYieldCurveDataParser.java @@ -61,26 +61,22 @@ public class MarkitYieldCurveDataParser { Double.parseDouble(rateText)); IsdaYieldCurveConvention convention = IsdaYieldCurveConvention.of(conventionText); - List points = curveData.get(convention); - if (points == null) { - points = Lists.newArrayList(); - curveData.put(convention, points); - } + List points = curveData.computeIfAbsent(convention, k -> Lists.newArrayList()); points.add(point); } // convert the curve data into the result map Map result = Maps.newHashMap(); - for (IsdaYieldCurveConvention convention : curveData.keySet()) { - List points = curveData.get(convention); - result.put(IsdaYieldCurveInputsId.of(convention.getCurrency()), + for (Map.Entry> isdaYieldCurveConventionListEntry : curveData.entrySet()) { + List points = isdaYieldCurveConventionListEntry.getValue(); + result.put(IsdaYieldCurveInputsId.of((isdaYieldCurveConventionListEntry.getKey()).getCurrency()), IsdaYieldCurveInputs.of( - CurveName.of(convention.getName()), + CurveName.of((isdaYieldCurveConventionListEntry.getKey()).getName()), points.stream().map(s -> s.getTenor().getPeriod()).toArray(Period[]::new), points.stream().map(s -> s.getDate()).toArray(LocalDate[]::new), points.stream().map(s -> s.getInstrumentType()).toArray(IsdaYieldCurveUnderlyingType[]::new), points.stream().mapToDouble(s -> s.getRate()).toArray(), - convention)); + isdaYieldCurveConventionListEntry.getKey())); } return result; } diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt index 0647e8da8d..e55814e4e4 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/OGStub.kt @@ -36,7 +36,7 @@ object BimmAnalysisUtils { first: CurrencyParameterSensitivities, second: MultiCurrencyAmount): Triple { val amount = second.amounts.map { it.amount }.sum() - return Triple(amount, 0.0, amount) + return Triple(amount, 0.0, amount) } } diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt index d07207111b..60169d26a9 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/analytics/example/OGSwapPricingCcpExample.kt @@ -198,5 +198,4 @@ class SwapPricingCcpExample { 100000000.0, // the notional amount 0.015) // the fixed interest rate } - } diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt index 0856383a0d..3cb7471132 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/IRSTradeFlow.kt @@ -38,7 +38,6 @@ object IRSTradeFlow { session, TwoPartyDealFlow.AutoOffer(notary, offer))) } - } @InitiatedBy(Requester::class) diff --git a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt index ca6271ed98..cf2ba3744d 100644 --- a/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt +++ b/samples/simm-valuation-demo/flows/src/main/kotlin/net/corda/vega/flows/OpenGammaCordaUtils.kt @@ -45,7 +45,6 @@ fun MarketData.toCordaCompatible(): CordaMarketData { return CordaMarketData(valuationDate = this.valuationDate, values = values) } - /** * A very basic modifier of InitialMarginTriple in order to ignore everything past the 2nd decimal place. */ diff --git a/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt b/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt index 22944e7553..c2fec1b800 100644 --- a/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt +++ b/samples/simm-valuation-demo/src/integration-test/kotlin/net/corda/vega/SimmValuationTest.kt @@ -28,7 +28,7 @@ class SimmValuationTest { val valuationDate: LocalDate = LocalDate.parse("2016-06-06") val nodeALegalName = DUMMY_BANK_A_NAME val nodeBLegalName = DUMMY_BANK_B_NAME - val testTradeId = "trade1" + const val testTradeId = "trade1" } @Before diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt index f2a6b791f6..c4248284fb 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/api/PortfolioApiUtils.kt @@ -46,7 +46,7 @@ class PortfolioApiUtils(private val ownParty: Party) { val yieldCurves = mapOf( "name" to "EUR", - "values" to completeSubgroups.get("EUR")!!.filter { !it.key.contains("Fixing") }.map { + "values" to completeSubgroups["EUR"]!!.filter { !it.key.contains("Fixing") }.map { mapOf( "tenor" to it.key, "rate" to it.value @@ -56,7 +56,7 @@ class PortfolioApiUtils(private val ownParty: Party) { val fixings = mapOf( "name" to "EUR", - "values" to completeSubgroups.get("EUR")!!.filter { it.key.contains("Fixing") }.map { + "values" to completeSubgroups["EUR"]!!.filter { it.key.contains("Fixing") }.map { mapOf( "tenor" to it.key, "rate" to it.value diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt index e5f2e3b496..41ec27de02 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitiesSerializer.kt @@ -9,6 +9,6 @@ class CurrencyParameterSensitivitiesSerializer : SerializationCustomSerializer { data class Proxy(val sensitivities: List) - override fun fromProxy(proxy: Proxy) = CurrencyParameterSensitivities.of(proxy.sensitivities) + override fun fromProxy(proxy: Proxy): CurrencyParameterSensitivities = CurrencyParameterSensitivities.of(proxy.sensitivities) override fun toProxy(obj: CurrencyParameterSensitivities) = Proxy(obj.sensitivities) } \ No newline at end of file diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt index f0762ec9be..904eef031e 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencyParameterSensitivitySerialiser.kt @@ -14,13 +14,12 @@ class CurrencyParameterSensitivitySerializer : val parameterMetadata: List, val sensitivity: DoubleArray) - override fun fromProxy(proxy: CurrencyParameterSensitivitySerializer.Proxy) = + override fun fromProxy(proxy: CurrencyParameterSensitivitySerializer.Proxy): CurrencyParameterSensitivity = CurrencyParameterSensitivity.of( proxy.marketDataName, proxy.parameterMetadata, proxy.currency, proxy.sensitivity) - override fun toProxy(obj: CurrencyParameterSensitivity) = Proxy((obj as CurrencyParameterSensitivity).currency, - obj.marketDataName, obj.parameterMetadata, obj.sensitivity) + override fun toProxy(obj: CurrencyParameterSensitivity) = Proxy(obj.currency, obj.marketDataName, obj.parameterMetadata, obj.sensitivity) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt index 2d93977323..45bffc8ae2 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/CurrencySerializer.kt @@ -7,6 +7,6 @@ import net.corda.core.serialization.SerializationCustomSerializer class CurrencySerializer : SerializationCustomSerializer { data class Proxy(val currency: String) - override fun fromProxy(proxy: Proxy) = Currency.parse(proxy.currency) + override fun fromProxy(proxy: Proxy): Currency = Currency.parse(proxy.currency) override fun toProxy(obj: Currency) = Proxy(obj.toString()) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt index 0b105726c9..8fe31b7dbf 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/DoubleArraySerializer.kt @@ -2,11 +2,28 @@ package net.corda.vega.plugin.customserializers import net.corda.core.serialization.SerializationCustomSerializer import com.opengamma.strata.collect.array.DoubleArray +import java.util.* @Suppress("UNUSED") class DoubleArraySerializer : SerializationCustomSerializer { - data class Proxy(val amount: kotlin.DoubleArray) + data class Proxy(val amount: kotlin.DoubleArray) { - override fun fromProxy(proxy: Proxy) = DoubleArray.copyOf(proxy.amount) + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Proxy + + if (!Arrays.equals(amount, other.amount)) return false + + return true + } + + override fun hashCode(): Int { + return Arrays.hashCode(amount) + } + } + + override fun fromProxy(proxy: Proxy): DoubleArray = DoubleArray.copyOf(proxy.amount) override fun toProxy(obj: DoubleArray) = Proxy(obj.toArray()) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt index a651aff9a1..82317ffb05 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/MultiCurrencyAmountSerializer.kt @@ -7,10 +7,10 @@ import net.corda.core.serialization.* @Suppress("UNUSED") class MultiCurrencyAmountSerializer : SerializationCustomSerializer { - data class Proxy(val curencies : Map) + data class Proxy(val curencies: Map) override fun toProxy(obj: MultiCurrencyAmount) = Proxy(obj.toMap()) - override fun fromProxy(proxy: Proxy) = MultiCurrencyAmount.of(proxy.curencies) + override fun fromProxy(proxy: Proxy): MultiCurrencyAmount = MultiCurrencyAmount.of(proxy.curencies) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt index dbcbc2b6fd..89777b1b11 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorDateParameterMetadataSerializer.kt @@ -11,5 +11,5 @@ class TenorDateParameterMetadataSerializer : data class Proxy(val tenor: Tenor, val date: LocalDate, val identifier: Tenor, val label: String) override fun toProxy(obj: TenorDateParameterMetadata) = Proxy(obj.tenor, obj.date, obj.identifier, obj.label) - override fun fromProxy(proxy: Proxy) = TenorDateParameterMetadata.of(proxy.date, proxy.tenor, proxy.label) + override fun fromProxy(proxy: Proxy): TenorDateParameterMetadata = TenorDateParameterMetadata.of(proxy.date, proxy.tenor, proxy.label) } diff --git a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt index 12e2dee1a5..c04b75730a 100644 --- a/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt +++ b/samples/simm-valuation-demo/src/main/kotlin/net/corda/vega/plugin/customserializers/TenorSerializer.kt @@ -9,5 +9,5 @@ class TenorSerializer : SerializationCustomSerializer) { diff --git a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt index 97ef776656..684cd1724e 100644 --- a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt +++ b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/TransactionGraphSearch.kt @@ -62,7 +62,7 @@ class TransactionGraphSearch(private val transactions: TransactionStorage, results += tx val inputsLeadingToUnvisitedTx: Iterable = tx.inputs.filter { it.txhash !in alreadyVisited } - val unvisitedInputTxs: Map = inputsLeadingToUnvisitedTx.map { it.txhash }.toHashSet().map { transactions.getTransaction(it) }.filterNotNull().associateBy { it.id } + val unvisitedInputTxs: Map = inputsLeadingToUnvisitedTx.map { it.txhash }.toHashSet().mapNotNull { transactions.getTransaction(it) }.associateBy { it.id } val unvisitedInputTxsWithInputIndex: Iterable> = inputsLeadingToUnvisitedTx.filter { it.txhash in unvisitedInputTxs.keys }.map { Pair(unvisitedInputTxs[it.txhash]!!, it.index) } next += (unvisitedInputTxsWithInputIndex.filter { (stx, idx) -> query.followInputsOfType == null || stx.tx.outputs[idx].data.javaClass == query.followInputsOfType diff --git a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt index cd1e7fed4b..847e48e8b2 100644 --- a/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt +++ b/samples/trader-demo/src/main/kotlin/net/corda/traderdemo/flow/CommercialPaperIssueFlow.kt @@ -60,13 +60,12 @@ class CommercialPaperIssueFlow(private val amount: Amount, } // Now make a dummy transaction that moves it to a new key, just to show that resolving dependencies works. - val move: SignedTransaction = run { + + return run { val builder = TransactionBuilder(notary) CommercialPaper().generateMove(builder, issuance.tx.outRef(0), recipient) val stx = serviceHub.signInitialTransaction(builder) subFlow(FinalityFlow(stx)) } - - return move } } diff --git a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt index 309a298844..4ca5c81980 100644 --- a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt +++ b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/FlowStackSnapshotTest.kt @@ -56,8 +56,7 @@ class SideEffectFlow : FlowLogic>() { // Expected to be on stack @Suppress("UNUSED_VARIABLE") val unusedVar = Constants.IN_CALL_VALUE - val numberOfFullFrames = retrieveStackSnapshot() - return numberOfFullFrames + return retrieveStackSnapshot() } @Suspendable @@ -84,8 +83,7 @@ class NoSideEffectFlow : FlowLogic>() { // Using the [Constants] object here is considered by Quasar as a side effect. Thus explicit initialization @Suppress("UNUSED_VARIABLE") val unusedVar = "inCall" - val numberOfFullFrames = retrieveStackSnapshot() - return numberOfFullFrames + return retrieveStackSnapshot() } @Suspendable @@ -99,11 +97,11 @@ class NoSideEffectFlow : FlowLogic>() { } object Constants { - val IN_PERSIST_VALUE = "inPersist" - val IN_CALL_VALUE = "inCall" - val IN_RETRIEVE_STACK_SNAPSHOT_VALUE = "inRetrieveStackSnapshot" - val USER = "User" - val PASSWORD = "Password" + const val IN_PERSIST_VALUE = "inPersist" + const val IN_CALL_VALUE = "inCall" + const val IN_RETRIEVE_STACK_SNAPSHOT_VALUE = "inRetrieveStackSnapshot" + const val USER = "User" + const val PASSWORD = "Password" } @@ -186,7 +184,7 @@ class FlowStackSnapshotSerializationTestingFlow : FlowLogic() { @Suspendable override fun call() { - val flowStackSnapshot = flowStackSnapshot() + flowStackSnapshot() val mySession = initiateFlow(ourIdentity) mySession.sendAndReceive("Ping") } diff --git a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt index eee030d580..cf82aec871 100644 --- a/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt +++ b/testing/node-driver/src/integration-test/kotlin/net/corda/testing/node/MockNetworkIntegrationTests.kt @@ -2,7 +2,6 @@ package net.corda.testing.node import net.corda.core.internal.div import net.corda.testing.common.internal.ProjectStructure.projectRootDir -import net.corda.testing.node.internal.InternalMockNetwork import net.corda.testing.node.internal.ProcessUtilities.startJavaProcess import org.junit.Test import kotlin.test.assertEquals diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt index 3330930fda..97cd2ef116 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/Driver.kt @@ -2,7 +2,6 @@ package net.corda.testing.driver -import net.corda.core.CordaInternal import net.corda.core.DoNotImplement import net.corda.core.concurrent.CordaFuture import net.corda.core.flows.FlowLogic @@ -17,6 +16,7 @@ import net.corda.core.utilities.getOrThrow import net.corda.node.internal.Node import net.corda.testing.common.internal.testNetworkParameters import net.corda.testing.core.DUMMY_NOTARY_NAME +import net.corda.testing.driver.PortAllocation.Incremental import net.corda.testing.driver.internal.internalServices import net.corda.testing.node.NotarySpec import net.corda.testing.node.User @@ -25,8 +25,6 @@ import net.corda.testing.node.internal.genericDriver import net.corda.testing.node.internal.getTimestampAsDirectoryName import net.corda.testing.node.internal.newContext import rx.Observable -import java.net.InetSocketAddress -import java.net.ServerSocket import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.atomic.AtomicInteger diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt index 6f8e3c6dbf..9606dcb96c 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/driver/DriverDSL.kt @@ -90,6 +90,7 @@ interface DriverDSL { fun startNode(parameters: NodeParameters): CordaFuture = startNode(defaultParameters = parameters) /** Call [startWebserver] with a default maximumHeapSize. */ + @Suppress("DEPRECATION") fun startWebserver(handle: NodeHandle): CordaFuture = startWebserver(handle, "200m") /** @@ -97,6 +98,7 @@ interface DriverDSL { * @param handle The handle for the node that this webserver connects to via RPC. * @param maximumHeapSize Argument for JVM -Xmx option e.g. "200m". */ + @Suppress("DEPRECATION") fun startWebserver(handle: NodeHandle, maximumHeapSize: String): CordaFuture /** diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt index 5264ceba92..82048f1d19 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/NodeTestUtils.kt @@ -2,22 +2,23 @@ package net.corda.testing.node -import net.corda.core.concurrent.CordaFuture import net.corda.core.context.Actor import net.corda.core.context.AuthServiceId import net.corda.core.context.InvocationContext -import net.corda.core.flows.FlowLogic import net.corda.core.identity.CordaX500Name import net.corda.core.identity.Party import net.corda.core.node.ServiceHub import net.corda.core.serialization.internal.effectiveSerializationEnv import net.corda.core.transactions.TransactionBuilder -import net.corda.core.utilities.getOrThrow -import net.corda.node.services.api.StartedNodeServices import net.corda.testing.core.SerializationEnvironmentRule import net.corda.testing.core.TestIdentity -import net.corda.testing.dsl.* -import net.corda.testing.internal.chooseIdentity +import net.corda.testing.dsl.EnforceVerifyOrFail +import net.corda.testing.dsl.LedgerDSL +import net.corda.testing.dsl.LedgerDSLInterpreter +import net.corda.testing.dsl.TestLedgerDSLInterpreter +import net.corda.testing.dsl.TestTransactionDSLInterpreter +import net.corda.testing.dsl.TransactionDSL +import net.corda.testing.dsl.TransactionDSLInterpreter /** * Creates and tests a ledger built by the passed in dsl. diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt index 228d62ca63..8276e21e27 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/DriverDSLImpl.kt @@ -111,7 +111,7 @@ class DriverDSLImpl( interface Waitable { @Throws(InterruptedException::class) - fun waitFor(): Unit + fun waitFor() } class State { @@ -293,15 +293,17 @@ class DriverDSLImpl( val notaryConfig = ConfigFactory.parseMap(cordform.notary).parseAs() // We need to first group the nodes that form part of a cluster. We assume for simplicity that nodes of the // same cluster type and validating flag are part of the same cluster. - if (notaryConfig.raft != null) { - val key = if (notaryConfig.validating) VALIDATING_RAFT else NON_VALIDATING_RAFT - clusterNodes.put(key, name) - } else if (notaryConfig.bftSMaRt != null) { - clusterNodes.put(ClusterType.NON_VALIDATING_BFT, name) - } else { - // We have all we need here to generate the identity for single node notaries - val identity = DevIdentityGenerator.installKeyStoreWithNodeIdentity(baseDirectory(name), legalName = name) - notaryInfos += NotaryInfo(identity, notaryConfig.validating) + when { + notaryConfig.raft != null -> { + val key = if (notaryConfig.validating) VALIDATING_RAFT else NON_VALIDATING_RAFT + clusterNodes.put(key, name) + } + notaryConfig.bftSMaRt != null -> clusterNodes.put(ClusterType.NON_VALIDATING_BFT, name) + else -> { + // We have all we need here to generate the identity for single node notaries + val identity = DevIdentityGenerator.installKeyStoreWithNodeIdentity(baseDirectory(name), legalName = name) + notaryInfos += NotaryInfo(identity, notaryConfig.validating) + } } } @@ -370,6 +372,7 @@ class DriverDSLImpl( return startNodeInternal(config, webAddress, null, "512m", localNetworkMap) } + @Suppress("DEPRECATION") private fun queryWebserver(handle: NodeHandle, process: Process): WebserverHandle { val protocol = if ((handle as NodeHandleInternal).useHTTPS) "https://" else "http://" val url = URL("$protocol${handle.webAddress}/api/status") @@ -387,6 +390,7 @@ class DriverDSLImpl( throw IllegalStateException("Webserver at ${handle.webAddress} has died") } + @Suppress("DEPRECATION") override fun startWebserver(handle: NodeHandle, maximumHeapSize: String): CordaFuture { val debugPort = if (isDebug) debugPortAllocation.nextPort() else null val process = startWebserver(handle as NodeHandleInternal, debugPort, maximumHeapSize) @@ -715,6 +719,7 @@ class DriverDSLImpl( * A sub-set of permissions that grant most of the essential operations used in the unit/integration tests as well as * in demo application like NodeExplorer. */ + @Suppress("DEPRECATION") private val DRIVER_REQUIRED_PERMISSIONS = setOf( Permissions.invokeRpc(CordaRPCOps::nodeInfo), Permissions.invokeRpc(CordaRPCOps::networkMapFeed), @@ -927,6 +932,9 @@ private class NetworkVisibilityController { visibleNodeCount-- checkIfAllVisible() } + is NetworkMapCache.MapChange.Modified -> { + // Nothing to do here but better being exhaustive. + } } } return future diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt index a465cb3b65..bb8203dc08 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalMockNetwork.kt @@ -266,7 +266,7 @@ open class InternalMockNetwork(private val cordappPackages: List, // We only need to override the messaging service here, as currently everything that hits disk does so // through the java.nio API which we are already mocking via Jimfs. override fun makeMessagingService(database: CordaPersistence, info: NodeInfo, nodeProperties: NodePropertiesStore, networkParameters: NetworkParameters): MessagingService { - require(id >= 0) { "Node ID must be zero or positive, was passed: " + id } + require(id >= 0) { "Node ID must be zero or positive, was passed: $id" } return mockNet.messagingNetwork.createNodeWithID( !mockNet.threadPerNode, id, diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt index 2d07005d83..1d04d8ff61 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/InternalTestUtils.kt @@ -1,7 +1,6 @@ package net.corda.testing.node.internal import net.corda.client.rpc.CordaRPCClient -import net.corda.client.rpc.CordaRPCClientConfiguration import net.corda.core.CordaException import net.corda.core.concurrent.CordaFuture import net.corda.core.context.InvocationContext @@ -16,7 +15,6 @@ import net.corda.core.utilities.seconds import net.corda.node.services.api.StartedNodeServices import net.corda.node.services.messaging.Message import net.corda.node.services.messaging.MessagingService -import net.corda.testing.driver.NodeHandle import net.corda.testing.internal.chooseIdentity import net.corda.testing.node.InMemoryMessagingNetwork import net.corda.testing.node.User diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt index 42f6902cc4..20d2bd31c1 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/ProcessUtilities.kt @@ -47,7 +47,7 @@ object ProcessUtilities { } return ProcessBuilder(command).apply { inheritIO() - environment().put("CLASSPATH", classpath) + environment()["CLASSPATH"] = classpath if (workingDirectory != null) { redirectError((workingDirectory / "$className.stderr.log").toFile()) redirectOutput((workingDirectory / "$className.stdout.log").toFile()) diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt index a2789b03c1..5b3f1a964b 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/RPCDriver.kt @@ -75,7 +75,7 @@ inline fun RPCDriverDSL.startRpcClient( configuration: CordaRPCClientConfigurationImpl = CordaRPCClientConfigurationImpl.default ) = startRpcClient(I::class.java, rpcAddress, username, password, configuration) -inline fun RPCDriverDSL.startRpcClient( +inline fun RPCDriverDSL.startRpcClient( haAddressPool: List, username: String = rpcTestUser.username, password: String = rpcTestUser.password, diff --git a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt index 00efdb38bf..a0a9e48a0f 100644 --- a/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt +++ b/testing/node-driver/src/main/kotlin/net/corda/testing/node/internal/performance/Reporter.kt @@ -10,20 +10,15 @@ import kotlin.concurrent.thread fun startReporter(shutdownManager: ShutdownManager, metricRegistry: MetricRegistry = MetricRegistry()): MetricRegistry { val jmxReporter = thread { - JmxReporter. - forRegistry(metricRegistry). - inDomain("net.corda"). - createsObjectNamesWith { _, domain, name -> - // Make the JMX hierarchy a bit better organised. - val category = name.substringBefore('.') - val subName = name.substringAfter('.', "") - if (subName == "") - ObjectName("$domain:name=$category") - else - ObjectName("$domain:type=$category,name=$subName") - }. - build(). - start() + JmxReporter.forRegistry(metricRegistry).inDomain("net.corda").createsObjectNamesWith { _, domain, name -> + // Make the JMX hierarchy a bit better organised. + val category = name.substringBefore('.') + val subName = name.substringAfter('.', "") + if (subName == "") + ObjectName("$domain:name=$category") + else + ObjectName("$domain:type=$category,name=$subName") + }.build().start() } shutdownManager.registerShutdown { jmxReporter.interrupt() } val consoleReporter = thread { diff --git a/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java b/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java index 739e5dcf27..1491c39d28 100644 --- a/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java +++ b/testing/node-driver/src/test/java/net/corda/testing/node/MockNodeFactoryInJavaTest.java @@ -1,7 +1,5 @@ package net.corda.testing.node; -import org.jetbrains.annotations.NotNull; - import static java.util.Collections.emptyList; @SuppressWarnings("unused") diff --git a/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt b/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt index 34310c78eb..145846962b 100644 --- a/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt +++ b/testing/smoke-test-utils/src/main/kotlin/net/corda/smoketesting/NodeConfig.kt @@ -7,6 +7,7 @@ import com.typesafe.config.ConfigValue import com.typesafe.config.ConfigValueFactory import net.corda.core.identity.CordaX500Name import net.corda.nodeapi.internal.config.User +import net.corda.nodeapi.internal.config.toConfig class NodeConfig( val legalName: CordaX500Name, @@ -35,7 +36,7 @@ class NodeConfig( .withValue("address", addressValueFor(rpcPort)) .withValue("adminAddress", addressValueFor(rpcAdminPort)) .root()) - .withValue("rpcUsers", valueFor(users.map(User::toMap).toList())) + .withValue("rpcUsers", valueFor(users.map { it.toConfig().root().unwrapped() }.toList())) .withValue("useTestClock", valueFor(true)) return if (isNotary) { config.withValue("notary", ConfigValueFactory.fromMap(mapOf("validating" to true))) diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt index 36472ac17d..fa079f0e43 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/contracts/DummyContractV2.kt @@ -1,7 +1,12 @@ package net.corda.testing.contracts -import net.corda.core.contracts.* -import net.corda.core.crypto.SecureHash +import net.corda.core.contracts.AlwaysAcceptAttachmentConstraint +import net.corda.core.contracts.AttachmentConstraint +import net.corda.core.contracts.CommandData +import net.corda.core.contracts.ContractClassName +import net.corda.core.contracts.ContractState +import net.corda.core.contracts.TypeOnlyCommandData +import net.corda.core.contracts.UpgradedContractWithLegacyConstraint import net.corda.core.identity.AbstractParty import net.corda.core.transactions.LedgerTransaction diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt index 2d1ea449c8..af961ba1a2 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/Expect.kt @@ -243,7 +243,7 @@ private sealed class ExpectComposeState { null } else if (next.second is Finished) { if (index == sequential.sequence.size - 1) { - Pair(next.first, Finished()) + Pair(next.first, Finished()) } else { val nextState = fromExpectCompose(sequential.sequence[index + 1]) if (nextState is Finished) { @@ -271,10 +271,10 @@ private sealed class ExpectComposeState { val nextStates = states.mapIndexed { i, expectComposeState -> if (i == stateIndex) next.second else expectComposeState } - if (nextStates.all { it is Finished }) { - return Pair(next.first, Finished()) + return if (nextStates.all { it is Finished }) { + Pair(next.first, Finished()) } else { - return Pair(next.first, Parallel(parallel, nextStates)) + Pair(next.first, Parallel(parallel, nextStates)) } } } @@ -293,14 +293,14 @@ private sealed class ExpectComposeState { Single(uncheckedCast(expectCompose)) } is ExpectCompose.Sequential -> { - if (expectCompose.sequence.size > 0) { + if (expectCompose.sequence.isNotEmpty()) { Sequential(expectCompose, 0, fromExpectCompose(expectCompose.sequence[0])) } else { Finished() } } is ExpectCompose.Parallel -> { - if (expectCompose.parallel.size > 0) { + if (expectCompose.parallel.isNotEmpty()) { Parallel(expectCompose, expectCompose.parallel.map { fromExpectCompose(it) }) } else { Finished() diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt index e11c081e59..f308d9abfc 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/core/TestConstants.kt @@ -6,9 +6,7 @@ import net.corda.core.contracts.Command import net.corda.core.contracts.TypeOnlyCommandData import net.corda.core.crypto.generateKeyPair import net.corda.core.identity.CordaX500Name -import net.corda.nodeapi.internal.crypto.CertificateAndKeyPair import java.security.PublicKey -import java.time.Instant /** A test notary name **/ @JvmField diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt index 24ba8921c8..7b19ea21a8 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/dsl/TestDSL.kt @@ -7,6 +7,7 @@ import net.corda.core.crypto.* import net.corda.core.crypto.NullKeys.NULL_SIGNATURE import net.corda.core.flows.FlowException import net.corda.core.identity.Party +import net.corda.core.internal.UNKNOWN_UPLOADER import net.corda.core.internal.uncheckedCast import net.corda.core.node.ServiceHub import net.corda.core.node.ServicesForResolution @@ -281,7 +282,7 @@ data class TestLedgerDSLInterpreter private constructor( copy().dsl() override fun attachment(attachment: InputStream): SecureHash { - return services.attachments.importAttachment(attachment) + return services.attachments.importAttachment(attachment, UNKNOWN_UPLOADER, null) } override fun verifies(): EnforceVerifyOrFail { diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt index 6491d7e452..9bb806d7d5 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/FlowStackSnapshot.kt @@ -175,7 +175,7 @@ private fun getFrameOffsets(stack: Stack): List> { return offsets } -private val MASK_FULL: Long = -1L +private const val MASK_FULL: Long = -1L private fun getNumSlots(record: Long): Int { return getUnsignedBits(record, 14, 16).toInt() diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt index 418bce072b..664cbce7ab 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/InternalTestConstants.kt @@ -9,4 +9,4 @@ val DEV_ROOT_CA: CertificateAndKeyPair by lazy { net.corda.nodeapi.internal.DEV_ /** A dummy time at which we will be pretending test transactions are created. **/ @JvmField -val TEST_TX_TIME = Instant.parse("2015-04-17T12:00:00.00Z") \ No newline at end of file +val TEST_TX_TIME: Instant = Instant.parse("2015-04-17T12:00:00.00Z") \ No newline at end of file diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt index 2a8a575bdd..a0bf8c1d58 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/LogHelper.kt @@ -62,5 +62,4 @@ object LogHelper { Configurator.setLevel(logName, oldLevel) } } - } diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt index 50f2ae24aa..61f65937b3 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/MockCordappConfigProvider.kt @@ -5,11 +5,11 @@ import com.typesafe.config.ConfigFactory import net.corda.node.internal.cordapp.CordappConfigProvider class MockCordappConfigProvider : CordappConfigProvider { - val cordappConfigs = mutableMapOf () + val cordappConfigs = mutableMapOf() override fun getConfigByName(name: String): Config { - return if(cordappConfigs.containsKey(name)) { - cordappConfigs[name]!! + return if (cordappConfigs.containsKey(name)) { + cordappConfigs[name]!! } else { ConfigFactory.empty() } diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt index 1cd75a83b0..c22e97e52c 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealContract.kt @@ -11,7 +11,7 @@ import net.corda.core.transactions.LedgerTransaction import net.corda.core.transactions.TransactionBuilder import net.corda.finance.contracts.DealState -val DUMMY_DEAL_PROGRAM_ID = "net.corda.testing.internal.vault.DummyDealContract" +const val DUMMY_DEAL_PROGRAM_ID = "net.corda.testing.internal.vault.DummyDealContract" class DummyDealContract : Contract { override fun verify(tx: LedgerTransaction) {} diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt index f562ec4e71..ed7f337565 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyDealStateSchemaV1.kt @@ -22,9 +22,7 @@ object DummyDealStateSchemaV1 : MappedSchema(schemaFamily = DummyDealStateSchema /** parent attributes */ @ElementCollection @Column(name = "participants") - @CollectionTable(name = "dummy_deal_states_parts", joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))) + @CollectionTable(name = "dummy_deal_states_parts", joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))]) override var participants: MutableSet? = null, @Transient diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt index ea0feb4f63..ec57afb309 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/internal/vault/DummyLinearStateSchemaV2.kt @@ -18,9 +18,7 @@ object DummyLinearStateSchemaV2 : MappedSchema(schemaFamily = DummyLinearStateSc @ElementCollection @Column(name = "participants") - @CollectionTable(name = "dummy_linear_states_v2_parts", joinColumns = arrayOf( - JoinColumn(name = "output_index", referencedColumnName = "output_index"), - JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))) + @CollectionTable(name = "dummy_linear_states_v2_parts", joinColumns = [(JoinColumn(name = "output_index", referencedColumnName = "output_index")), (JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"))]) override var participants: MutableSet? = null, @Column(name = "linear_string") var linearString: String, diff --git a/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt b/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt index e4fb2f5716..b113dda1b8 100644 --- a/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt +++ b/testing/test-utils/src/main/kotlin/net/corda/testing/services/MockAttachmentStorage.kt @@ -27,11 +27,12 @@ class MockAttachmentStorage : AttachmentStorage, SingletonSerializeAsToken() { /** A map of the currently stored files by their [SecureHash] */ val files: Map> get() = _files + @Suppress("OverridingDeprecatedMember") override fun importAttachment(jar: InputStream): AttachmentId = importAttachment(jar, UNKNOWN_UPLOADER, null) override fun importAttachment(jar: InputStream, uploader: String, filename: String?): AttachmentId { return withContractsInJar(jar) { contractClassNames, inputStream -> - importAttachmentInternal(inputStream, uploader, filename, contractClassNames) + importAttachmentInternal(inputStream, uploader, contractClassNames) } } @@ -43,21 +44,22 @@ class MockAttachmentStorage : AttachmentStorage, SingletonSerializeAsToken() { override fun hasAttachment(attachmentId: AttachmentId) = files.containsKey(attachmentId) + @Suppress("OverridingDeprecatedMember") override fun importOrGetAttachment(jar: InputStream): AttachmentId { - try { - return importAttachment(jar) - } catch (faee: java.nio.file.FileAlreadyExistsException) { - return AttachmentId.parse(faee.message!!) + return try { + importAttachment(jar, UNKNOWN_UPLOADER, null) + } catch (e: java.nio.file.FileAlreadyExistsException) { + AttachmentId.parse(e.message!!) } } - fun importContractAttachment(contractClassNames: List, uploader: String, jar: InputStream): AttachmentId = importAttachmentInternal(jar, uploader, null, contractClassNames) + fun importContractAttachment(contractClassNames: List, uploader: String, jar: InputStream): AttachmentId = importAttachmentInternal(jar, uploader, contractClassNames) fun getAttachmentIdAndBytes(jar: InputStream): Pair = jar.readFully().let { bytes -> Pair(bytes.sha256(), bytes) } private class MockAttachment(dataLoader: () -> ByteArray, override val id: SecureHash) : AbstractAttachment(dataLoader) - private fun importAttachmentInternal(jar: InputStream, uploader: String, filename: String?, contractClassNames: List? = null): AttachmentId { + private fun importAttachmentInternal(jar: InputStream, uploader: String, contractClassNames: List? = null): AttachmentId { // JIS makes read()/readBytes() return bytes of the current file, but we want to hash the entire container here. require(jar !is JarInputStream) diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt index a3d8586d26..8138ca6118 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/model/DemoBenchNodeInfoFilesCopier.kt @@ -11,7 +11,7 @@ import tornadofx.* * This class will create paths that it needs to poll and to where it needs to copy files in case those * don't exist yet. */ -class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()): Controller() { +class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()) : Controller() { private val nodeInfoFilesCopier = NodeInfoFilesCopier(scheduler) @@ -21,7 +21,7 @@ class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()): Cont * Its nodeInfo file will be copied to other nodes' additional-node-infos directory, and conversely, * other nodes' nodeInfo files will be copied to this node additional-node-infos directory. */ - fun addConfig(nodeConfig: NodeConfigWrapper) : Unit = nodeInfoFilesCopier.addConfig(nodeConfig.nodeDir) + fun addConfig(nodeConfig: NodeConfigWrapper): Unit = nodeInfoFilesCopier.addConfig(nodeConfig.nodeDir) /** * @param nodeConfig the configuration to be removed. @@ -29,7 +29,7 @@ class DemoBenchNodeInfoFilesCopier(scheduler: Scheduler = Schedulers.io()): Cont * No files written by that node will be copied to other nodes, nor files from other nodes will be copied to this * one. */ - fun removeConfig(nodeConfig: NodeConfigWrapper) : Unit = nodeInfoFilesCopier.removeConfig(nodeConfig.nodeDir) + fun removeConfig(nodeConfig: NodeConfigWrapper): Unit = nodeInfoFilesCopier.removeConfig(nodeConfig.nodeDir) - fun reset() : Unit = nodeInfoFilesCopier.reset() + fun reset(): Unit = nodeInfoFilesCopier.reset() } \ No newline at end of file diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt index d8553818e3..37cdc76263 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/model/NodeConfig.kt @@ -38,7 +38,7 @@ data class NodeConfig( companion object { val renderOptions: ConfigRenderOptions = ConfigRenderOptions.defaults().setOriginComments(false) val defaultUser = user("guest") - val cordappDirName = "cordapps" + const val cordappDirName = "cordapps" } @Suppress("unused") diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt index 566159ac5a..6b398a85ef 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/plugin/CordappController.kt @@ -43,11 +43,12 @@ class CordappController : Controller() { @Throws(IOException::class) fun useCordappsFor(config: HasCordapps): List { if (!config.cordappsDir.isDirectory()) return emptyList() - return config.cordappsDir.walk(1) { paths -> paths - .filter(Path::isCordapp) - .filter { !bankOfCorda.endsWith(it.fileName) } - .filter { !finance.endsWith(it.fileName) } - .toList() + return config.cordappsDir.walk(1) { paths -> + paths + .filter(Path::isCordapp) + .filter { !bankOfCorda.endsWith(it.fileName) } + .filter { !finance.endsWith(it.fileName) } + .toList() } } } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt index 0294ff170c..52c8d22032 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/PtyProcessTtyConnector.kt @@ -30,5 +30,4 @@ class PtyProcessTtyConnector( ) } } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt index fff015a4f2..3bd1b0c6ec 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/R3Pty.kt @@ -66,5 +66,4 @@ class R3Pty(val name: CordaX500Name, settings: SettingsProvider, dimension: Dime @Suppress("unused") @Throws(InterruptedException::class) fun waitFor(): Int? = terminal.ttyConnector?.waitFor() - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt index 7e1ab0c0fa..619b698a8f 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/pty/ZeroFilter.kt @@ -38,7 +38,6 @@ private class ZeroFilter(output: OutputStream) : FilterOutputStream(output) { super.write(filtered, 0, count) } - } /** @@ -63,7 +62,6 @@ private class ZeroFilteringProcess(private val process: Process) : Process() { override fun destroy() = process.destroy() override fun exitValue() = process.exitValue() - } /** diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt index c07dd6cef6..62cb035c16 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/rpc/NodeRPC.kt @@ -58,5 +58,4 @@ class NodeRPC(config: NodeConfigWrapper, start: (NodeConfigWrapper, CordaRPCOps) log.error("Failed to close RPC connection (Error: {})", e.message) } } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt index 95c83f9a92..f28cb0b2e6 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/CloseableTab.kt @@ -21,5 +21,4 @@ class CloseableTab(text: String, content: Node) : Tab(text, content) { behaviour.closeTab(this) } } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt index 8d870315b4..c591ea9f77 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/ui/PropertyLabel.kt @@ -27,5 +27,4 @@ class PropertyLabel : HBox() { children.addAll(nameLabel, valueLabel) styleClass.add("property-label") } - } diff --git a/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt b/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt index 94908d6a31..2d41fa1585 100644 --- a/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt +++ b/tools/demobench/src/main/kotlin/net/corda/demobench/web/DBViewer.kt @@ -53,5 +53,4 @@ class DBViewer : AutoCloseable { Server.openBrowser(url) } } - } diff --git a/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt b/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt index a1cda62688..17f26e5586 100644 --- a/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt +++ b/tools/demobench/src/main/kotlin/org/h2/server/web/LocalWebServer.kt @@ -15,7 +15,6 @@ class LocalWebServer : WebServer() { session.connection = conn session.put("url", conn.metaData.url) val s = session.get("sessionId") as String - return url + "/frame.jsp?jsessionid=" + s + return "$url/frame.jsp?jsessionid=$s" } - } diff --git a/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt b/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt index 33e9d4169b..a4fb73d871 100644 --- a/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt +++ b/tools/demobench/src/test/kotlin/net/corda/demobench/LoggingTestSuite.kt @@ -28,5 +28,4 @@ class LoggingTestSuite { LoggingConfig() } } - } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt index 7cf77e1472..9b80d26add 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/Main.kt @@ -69,10 +69,10 @@ class Main : App(MainView::class) { } private fun asInteger(s: String?): Int? { - try { - return s?.toInt() + return try { + s?.toInt() } catch (e: NumberFormatException) { - return null + null } } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt index 4e0bcbe7f1..46750630c6 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/formatters/Formatter.kt @@ -1,6 +1,5 @@ package net.corda.explorer.formatters - interface Formatter { fun format(value: T): String } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt index 5ec79549e8..97a8549688 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/identicon/IdenticonRenderer.kt @@ -66,17 +66,17 @@ object IdenticonRenderer { byteArrayOf(0, 2, 10, 0), byteArrayOf(0, 4, 24, 20, 0)).map(::Patch) - private val PATCH_CELLS = 4 + private const val PATCH_CELLS = 4 private val PATCH_GRIDS = PATCH_CELLS + 1 - private val PATCH_SYMMETRIC: Byte = 1 - private val PATCH_INVERTED: Byte = 2 + private const val PATCH_SYMMETRIC: Byte = 1 + private const val PATCH_INVERTED: Byte = 2 private val patchFlags = byteArrayOf(PATCH_SYMMETRIC, 0, 0, 0, PATCH_SYMMETRIC, 0, 0, 0, PATCH_SYMMETRIC, 0, 0, 0, 0, 0, 0, (PATCH_SYMMETRIC + PATCH_INVERTED).toByte()) - private val renderingSize = 30.0 + private const val renderingSize = 30.0 private val cache = Caffeine.newBuilder().build(CacheLoader { key -> - key?.let { render(key.hashCode(), renderingSize) } + key.let { render(key.hashCode(), renderingSize) } }) private class Patch(private val byteArray: ByteArray) { diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt index 365b6abf6a..81737eb50d 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/model/ReportingCurrencyModel.kt @@ -5,13 +5,8 @@ import net.corda.client.jfx.model.ExchangeRate import net.corda.client.jfx.model.ExchangeRateModel import net.corda.client.jfx.model.observableValue import net.corda.client.jfx.utils.AmountBindings -import net.corda.core.contracts.* -import net.corda.finance.CHF -import net.corda.finance.EUR -import net.corda.finance.GBP -import net.corda.finance.USD +import net.corda.core.contracts.Amount import org.fxmisc.easybind.EasyBind -import tornadofx.* import java.util.* class ReportingCurrencyModel { diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt index 453a1f9741..879b620a93 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TableViewUtilities.kt @@ -1,6 +1,7 @@ package net.corda.explorer.ui import javafx.beans.binding.Bindings +import javafx.beans.binding.ObjectBinding import javafx.beans.value.ObservableValue import javafx.scene.Node import javafx.scene.control.TableCell @@ -48,7 +49,7 @@ fun Formatter.toTableCellFactory() = Callback, Tabl } } -fun TableView.singleRowSelection() = Bindings.createObjectBinding({ +fun TableView.singleRowSelection(): ObjectBinding> = Bindings.createObjectBinding({ if (selectionModel.selectedItems.size == 0) { SingleRowSelection.None() } else { diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt index 8d5b0ccb4e..92e0d46a46 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/ui/TreeTableViewUtilities.kt @@ -9,7 +9,6 @@ import javafx.util.Callback import net.corda.explorer.formatters.Formatter import org.fxmisc.easybind.EasyBind - fun TreeTableView.setColumnPrefWidthPolicy( getColumnWidth: (tableWidthWithoutPaddingAndBorder: Number, column: TreeTableColumn) -> Number ) { diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt index 7079a9ad3a..59609fe2bf 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Dashboard.kt @@ -51,5 +51,4 @@ class Dashboard : CordaView() { } } } - } \ No newline at end of file diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt index e61163b24b..5ee391b80c 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/GuiUtilities.kt @@ -25,7 +25,7 @@ const val WINDOW_TITLE = "Corda Node Explorer" * Helper method to reduce boiler plate code */ fun stringConverter(fromStringFunction: ((String?) -> T)? = null, toStringFunction: (T) -> String): StringConverter { - val converter = object : StringConverter() { + return object : StringConverter() { override fun fromString(string: String?): T { return fromStringFunction?.invoke(string) ?: throw UnsupportedOperationException("not implemented") } @@ -34,7 +34,6 @@ fun stringConverter(fromStringFunction: ((String?) -> T)? = null, toStringFu return toStringFunction(o) } } - return converter } /** diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt index 925b05e107..a76e051f68 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Network.kt @@ -72,7 +72,7 @@ class Network : CordaView() { private val peerButtons = peerComponents.filtered { myIdentity.value !in it.nodeInfo.legalIdentitiesAndCerts.map { it.party } }.map { it.button } private val allComponents = FXCollections.observableArrayList(notaryComponents, peerComponents).concatenate().apply { addListener(ListChangeListener { - if(it.next()){ + if (it.next()) { it.removed.forEach { mapPane.children.remove(it.label) } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt index d9192633b2..83a200abb4 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/SearchField.kt @@ -67,7 +67,7 @@ class SearchField(private val data: ObservableList, vararg filterCriteria: }) textField.promptTextProperty().bind(searchCategory.valueProperty().map { val category = if (it == ALL) { - filterCriteria.map { it.first.toLowerCase() }.joinToString(", ") + filterCriteria.joinToString(", ") { it.first.toLowerCase() } } else { it.toLowerCase() } diff --git a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt index 503ff7e1be..6a596b44bd 100644 --- a/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt +++ b/tools/explorer/src/main/kotlin/net/corda/explorer/views/Settings.kt @@ -13,7 +13,6 @@ import net.corda.client.jfx.model.observableList import net.corda.client.jfx.utils.map import net.corda.explorer.model.CordaView import net.corda.explorer.model.IssuerModel -import net.corda.explorer.model.ReportingCurrencyModel import net.corda.explorer.model.SettingsModel import java.util.* diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt index 8e8cd14e0f..e28f95fc83 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/ConnectionManager.kt @@ -30,10 +30,10 @@ fun setupJSchWithSshAgent(): JSch { return JSch().apply { identityRepository = object : IdentityRepository { override fun getStatus(): Int { - if (connector.isAvailable) { - return IdentityRepository.RUNNING + return if (connector.isAvailable) { + IdentityRepository.RUNNING } else { - return IdentityRepository.UNAVAILABLE + IdentityRepository.UNAVAILABLE } } diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt index e70a1f6621..f1809879ed 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/Disruption.kt @@ -1,8 +1,7 @@ package net.corda.loadtest -import net.corda.client.mock.* +import net.corda.client.mock.Generator import net.corda.core.utilities.loggerFor -import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.Callable import java.util.concurrent.Executors diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt index 62fd304866..0f4fade46c 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/LoadTest.kt @@ -178,15 +178,15 @@ fun runLoadTests(configuration: LoadTestConfiguration, tests: List acc + "\n" + elem.name + ": " + elem.owningKey.toBase58String() } - }.joinToString("\n") + } log.info("${connection.remoteNode.hostname} waiting for network map") connection.proxy.waitUntilNetworkReady().get() log.info("${connection.remoteNode.hostname} sees\n$pubKeysString") - hostNodeMap.put(connection.remoteNode.hostname, connection) + hostNodeMap[connection.remoteNode.hostname] = connection } val notaryIdentity = hostNodeMap.values.first().proxy.notaryIdentities().single() diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt index f375eae55c..ea4b03d9ca 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/CrossCashTest.kt @@ -148,13 +148,13 @@ val crossCashTest = LoadTest( } }, - interpret = { state, command -> - when (command.request) { + interpret = { state, (request, node) -> + when (request) { is IssueAndPaymentRequest -> { val newDiffQueues = state.copyQueues() - val originators = newDiffQueues.getOrPut(command.request.recipient, { HashMap() }) - val issuer = command.node.mainIdentity - val quantity = command.request.amount.quantity + val originators = newDiffQueues.getOrPut(request.recipient, { HashMap() }) + val issuer = node.mainIdentity + val quantity = request.amount.quantity val queue = originators.getOrPut(issuer, { ArrayList() }) queue.add(Pair(issuer, quantity)) CrossCashState(state.nodeVaults, newDiffQueues) @@ -162,25 +162,25 @@ val crossCashTest = LoadTest( is PaymentRequest -> { val newNodeVaults = state.copyVaults() val newDiffQueues = state.copyQueues() - val recipientOriginators = newDiffQueues.getOrPut(command.request.recipient, { HashMap() }) - val senderQuantities = newNodeVaults[command.node.mainIdentity]!! - val amount = command.request.amount - val issuer = command.request.issuerConstraint.single() - val originator = command.node.mainIdentity + val recipientOriginators = newDiffQueues.getOrPut(request.recipient, { HashMap() }) + val senderQuantities = newNodeVaults[node.mainIdentity]!! + val amount = request.amount + val issuer = request.issuerConstraint.single() + val originator = node.mainIdentity val senderQuantity = senderQuantities[issuer] ?: throw Exception( - "Generated payment of ${command.request.amount} from ${command.node.mainIdentity}, " + + "Generated payment of ${request.amount} from ${node.mainIdentity}, " + "however there is no cash from $issuer!" ) if (senderQuantity < amount.quantity) { throw Exception( - "Generated payment of ${command.request.amount} from ${command.node.mainIdentity}, " + + "Generated payment of ${request.amount} from ${node.mainIdentity}, " + "however they only have $senderQuantity!" ) } if (senderQuantity == amount.quantity) { senderQuantities.remove(issuer) } else { - senderQuantities.put(issuer, senderQuantity - amount.quantity) + senderQuantities[issuer] = senderQuantity - amount.quantity } val recipientQueue = recipientOriginators.getOrPut(originator, { ArrayList() }) recipientQueue.add(Pair(issuer, amount.quantity)) @@ -188,26 +188,26 @@ val crossCashTest = LoadTest( } is ExitRequest -> { val newNodeVaults = state.copyVaults() - val issuer = command.node.mainIdentity - val quantity = command.request.amount.quantity + val issuer = node.mainIdentity + val quantity = request.amount.quantity val issuerQuantities = newNodeVaults[issuer]!! val issuerQuantity = issuerQuantities[issuer] ?: throw Exception( - "Generated exit of ${command.request.amount} from $issuer, however there is no cash to exit!" + "Generated exit of ${request.amount} from $issuer, however there is no cash to exit!" ) if (issuerQuantity < quantity) { throw Exception( - "Generated payment of ${command.request.amount} from $issuer, " + + "Generated payment of ${request.amount} from $issuer, " + "however they only have $issuerQuantity!" ) } if (issuerQuantity == quantity) { issuerQuantities.remove(issuer) } else { - issuerQuantities.put(issuer, issuerQuantity - quantity) + issuerQuantities[issuer] = issuerQuantity - quantity } CrossCashState(newNodeVaults, state.diffQueues) } - else -> throw IllegalArgumentException("Unexpected request type: ${command.request}") + else -> throw IllegalArgumentException("Unexpected request type: ${request}") } }, @@ -235,9 +235,9 @@ val crossCashTest = LoadTest( vault.forEach { val state = it.state.data val issuer = state.amount.token.issuer.party - quantities.put(issuer, (quantities[issuer] ?: 0L) + state.amount.quantity) + quantities[issuer] = (quantities[issuer] ?: 0L) + state.amount.quantity } - currentNodeVaults.put(it.mainIdentity, quantities) + currentNodeVaults[it.mainIdentity] = quantities } val (consistentVaults, diffQueues) = if (previousState == null) { Pair(currentNodeVaults, mapOf>>>()) @@ -258,7 +258,7 @@ val crossCashTest = LoadTest( "\nActual gathered state:\n${CrossCashState(currentNodeVaults, mapOf())}" ) // TODO We should terminate here with an exception, we cannot carry on as we have an inconsistent model. We carry on currently because we always diverge due to notarisation failures - return@LoadTest CrossCashState(currentNodeVaults, mapOf>>>()) + return@LoadTest CrossCashState(currentNodeVaults, mapOf()) } if (matches.size > 1) { log.warn("Multiple predicted states match the remote state") @@ -279,7 +279,7 @@ val crossCashTest = LoadTest( newNodeDiffQueues!! for (i in 0 until consumedTxs) { val (issuer, quantity) = newNodeDiffQueues[originator]!!.removeAt(0) - newNodeVault.put(issuer, (newNodeVault[issuer] ?: 0L) + quantity) + newNodeVault[issuer] = (newNodeVault[issuer] ?: 0L) + quantity } } } @@ -347,6 +347,6 @@ private fun applyDiff( if (searchedQuantity == null || newQuantity > searchedQuantity) { return null } - newState.put(issuer, newQuantity) + newState[issuer] = newQuantity return newState } diff --git a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt index 9cbdbcc462..cf5a7c1951 100644 --- a/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt +++ b/tools/loadtest/src/main/kotlin/net/corda/loadtest/tests/SelfIssueTest.kt @@ -55,7 +55,7 @@ val selfIssueTest = LoadTest( interpret = { state, (request, node) -> val vaults = state.copyVaults() val issuer = node.mainIdentity - vaults.put(issuer, (vaults[issuer] ?: 0L) + request.amount.quantity) + vaults[issuer] = (vaults[issuer] ?: 0L) + request.amount.quantity SelfIssueState(vaults) }, @@ -76,7 +76,7 @@ val selfIssueTest = LoadTest( val state = it.state.data val issuer = state.amount.token.issuer.party if (issuer == connection.mainIdentity as AbstractParty) { - selfIssueVaults.put(issuer, (selfIssueVaults[issuer] ?: 0L) + state.amount.quantity) + selfIssueVaults[issuer] = (selfIssueVaults[issuer] ?: 0L) + state.amount.quantity } } } diff --git a/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java b/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java index 9b98d176af..497a855a68 100644 --- a/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java +++ b/tools/shell/src/main/java/net/corda/tools/shell/RunShellCommand.java @@ -11,7 +11,10 @@ import org.crsh.cli.Usage; import org.crsh.command.InvocationContext; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; import static java.util.Comparator.comparing; @@ -44,7 +47,7 @@ public class RunShellCommand extends InteractiveShellCommand { // Sends data down the pipeline about what commands are available. CRaSH will render it nicely. // Each element we emit is a map of column -> content. Set> entries = parser.getAvailableCommands().entrySet(); - ArrayList> entryList = new ArrayList<>(entries); + List> entryList = new ArrayList<>(entries); entryList.sort(comparing(Map.Entry::getKey)); for (Map.Entry entry : entryList) { // Skip these entries as they aren't really interesting for the user. diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt index 4ee877b3af..9063494d12 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt @@ -7,7 +7,7 @@ import org.crsh.auth.AuthInfo import org.crsh.auth.AuthenticationPlugin import org.crsh.plugin.CRaSHPlugin -class CordaAuthenticationPlugin(private val rpcOps: (username: String, credential: String) -> CordaRPCOps): CRaSHPlugin>(), AuthenticationPlugin { +class CordaAuthenticationPlugin(private val rpcOps: (username: String, credential: String) -> CordaRPCOps) : CRaSHPlugin>(), AuthenticationPlugin { companion object { private val logger = loggerFor() diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt index 0b3dcd43df..58cedf8b9d 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/InteractiveShell.kt @@ -142,7 +142,7 @@ object InteractiveShell { val extraCommandsPath = shellCommands.toAbsolutePath().createDirectories() val commandsFS = FS.Builder() .register("file", fileDriver) - .mount("file:" + extraCommandsPath) + .mount("file:$extraCommandsPath") .register("classpath", classpathDriver) .mount("classpath:/net/corda/tools/shell/") .mount("classpath:/crash/commands/") @@ -302,7 +302,7 @@ object InteractiveShell { try { // Attempt construction with the given arguments. paramNamesFromConstructor = parser.paramNamesFromConstructor(ctor) - val args = parser.parseArguments(clazz.name, paramNamesFromConstructor!!.zip(ctor.parameterTypes), inputData) + val args = parser.parseArguments(clazz.name, paramNamesFromConstructor.zip(ctor.parameterTypes), inputData) if (args.size != ctor.parameterTypes.size) { errors.add("${getPrototype()}: Wrong number of arguments (${args.size} provided, ${ctor.parameterTypes.size} needed)") continue @@ -375,7 +375,7 @@ object InteractiveShell { val parser = StringToMethodCallParser(CordaRPCOps::class.java, om) val call = parser.parse(cordaRPCOps, cmd) result = call.call() - if (result != null && result !is kotlin.Unit && result !is Void) { + if (result != null && result !== kotlin.Unit && result !is Void) { result = printAndFollowRPCResponse(result, out) } if (result is Future<*>) { @@ -429,9 +429,9 @@ object InteractiveShell { log.error(error.message) throw error } - .doOnNext { remaining -> + .doOnNext { (first, second) -> display { - println("...remaining: ${remaining.first}/${remaining.second}") + println("...remaining: ${first}/${second}") } } .doOnCompleted { diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt index 90e08363fa..82800e5ab1 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/SSHDConfiguration.kt @@ -11,7 +11,7 @@ data class SSHDConfiguration(val port: Int) { */ @JvmStatic fun parse(str: String): SSHDConfiguration { - require(!str.isNullOrBlank()) { SSHDConfiguration.MISSING_PORT_FORMAT.format(str) } + require(!str.isBlank()) { SSHDConfiguration.MISSING_PORT_FORMAT.format(str) } val port = try { str.toInt() } catch (ex: NumberFormatException) { diff --git a/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt b/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt index 349bbefc0e..00f8928b81 100644 --- a/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt +++ b/tools/shell/src/main/kotlin/net/corda/tools/shell/StandaloneShell.kt @@ -71,10 +71,10 @@ class StandaloneShell(private val configuration: ShellConfiguration) { val cordappJarPaths = getCordappsInDirectory(configuration.cordappsDirectory) val classLoader: ClassLoader = URLClassLoader(cordappJarPaths.toTypedArray(), javaClass.classLoader) with(configuration) { - if (user.isNullOrEmpty()) { + if (user.isEmpty()) { user = readLine("User:") } - if (password.isNullOrEmpty()) { + if (password.isEmpty()) { password = String(readPassword("Password:")) } } diff --git a/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt b/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt index 033bd3ba8f..06c243b37c 100644 --- a/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt +++ b/tools/shell/src/test/kotlin/net/corda/tools/shell/InteractiveShellTest.kt @@ -37,11 +37,12 @@ class InteractiveShellTest { } private val ids = InMemoryIdentityService(arrayOf(megaCorp.identity), DEV_ROOT_CA.certificate) + @Suppress("DEPRECATION") private val om = JacksonSupport.createInMemoryMapper(ids, YAMLFactory()) private fun check(input: String, expected: String) { var output: String? = null - InteractiveShell.runFlowFromString( { clazz, args -> + InteractiveShell.runFlowFromString({ clazz, args -> val instance = clazz.getConstructor(*args.map { it!!::class.java }.toTypedArray()).newInstance(*args) as FlowA output = instance.a diff --git a/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt b/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt index 2876482549..44892134f2 100644 --- a/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt +++ b/webserver/src/integration-test/kotlin/net/corda/webserver/WebserverDriverTests.kt @@ -1,3 +1,5 @@ +@file:Suppress("DEPRECATION") + package net.corda.webserver import net.corda.core.utilities.NetworkHostAndPort @@ -13,7 +15,7 @@ import java.util.concurrent.ScheduledExecutorService class WebserverDriverTests { companion object { - val executorService: ScheduledExecutorService = Executors.newScheduledThreadPool(2) + private val executorService: ScheduledExecutorService = Executors.newScheduledThreadPool(2) fun webserverMustBeUp(webserverHandle: WebserverHandle) { addressMustBeBound(executorService, webserverHandle.listenAddress, webserverHandle.process) diff --git a/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt b/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt index 793e6b4308..5ba08b691d 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/WebServerConfig.kt @@ -37,6 +37,6 @@ class WebServerConfig(override val baseDirectory: Path, val config: Config) : No } else { config.getConfigList("security.authService.dataSource.users") } - runAs = users.first().parseAs() + runAs = users.first().parseAs() } } diff --git a/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt b/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt index 1a5200cf72..1476cd6982 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/api/APIServer.kt @@ -91,5 +91,4 @@ interface APIServer { @Path("states") @Produces(MediaType.APPLICATION_JSON) fun states(): List> - } \ No newline at end of file diff --git a/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt b/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt index 958c540f61..5970c22e7d 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/internal/NodeWebServer.kt @@ -8,16 +8,25 @@ import net.corda.core.utilities.contextLogger import net.corda.webserver.WebServerConfig import net.corda.webserver.converters.CordaConverterProvider import net.corda.webserver.services.WebServerPluginRegistry -import net.corda.webserver.servlets.* +import net.corda.webserver.servlets.AttachmentDownloadServlet +import net.corda.webserver.servlets.CorDappInfoServlet +import net.corda.webserver.servlets.DataUploadServlet +import net.corda.webserver.servlets.ObjectMapperConfig +import net.corda.webserver.servlets.ResponseFilter import org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException -import org.eclipse.jetty.server.* +import org.eclipse.jetty.server.Connector +import org.eclipse.jetty.server.HttpConfiguration +import org.eclipse.jetty.server.HttpConnectionFactory +import org.eclipse.jetty.server.SecureRequestCustomizer +import org.eclipse.jetty.server.Server +import org.eclipse.jetty.server.ServerConnector +import org.eclipse.jetty.server.SslConnectionFactory import org.eclipse.jetty.server.handler.ErrorHandler import org.eclipse.jetty.server.handler.HandlerCollection import org.eclipse.jetty.servlet.DefaultServlet import org.eclipse.jetty.servlet.ServletContextHandler import org.eclipse.jetty.servlet.ServletHolder import org.eclipse.jetty.util.ssl.SslContextFactory -import org.eclipse.jetty.webapp.WebAppContext import org.glassfish.jersey.server.ResourceConfig import org.glassfish.jersey.server.ServerProperties import org.glassfish.jersey.servlet.ServletContainer @@ -28,7 +37,6 @@ import java.lang.reflect.InvocationTargetException import java.nio.file.NoSuchFileException import java.util.* import javax.servlet.http.HttpServletRequest -import javax.ws.rs.core.MediaType class NodeWebServer(val config: WebServerConfig) { private companion object { diff --git a/webserver/src/main/kotlin/net/corda/webserver/service/WebServerPluginRegistry.kt b/webserver/src/main/kotlin/net/corda/webserver/services/WebServerPluginRegistry.kt similarity index 95% rename from webserver/src/main/kotlin/net/corda/webserver/service/WebServerPluginRegistry.kt rename to webserver/src/main/kotlin/net/corda/webserver/services/WebServerPluginRegistry.kt index 6f7be07364..91981c66c4 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/service/WebServerPluginRegistry.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/services/WebServerPluginRegistry.kt @@ -26,6 +26,5 @@ interface WebServerPluginRegistry { * Optionally register extra JSON serializers to the default ObjectMapper provider * @param om The [ObjectMapper] to register custom types against. */ - fun customizeJSONSerialization(om: ObjectMapper): Unit {} - + fun customizeJSONSerialization(om: ObjectMapper) {} } \ No newline at end of file diff --git a/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt b/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt index 8daa446af9..4f51255e8b 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/servlets/CorDappInfoServlet.kt @@ -35,7 +35,7 @@ class CorDappInfoServlet(val plugins: List, val rpc: Co plugin.webApis.forEach { api -> val resource = Resource.from(api.apply(rpc)::class.java) p { +"${resource.name}:" } - val endpoints = processEndpoints("", resource, mutableListOf()) + val endpoints = processEndpoints("", resource, mutableListOf()) ul { endpoints.forEach { li { a(it.uri) { +"${it.method}\t${it.text}" } } diff --git a/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt b/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt index 5b29019585..ccb7c4d6e3 100644 --- a/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt +++ b/webserver/src/main/kotlin/net/corda/webserver/servlets/ResponseFilter.kt @@ -29,7 +29,5 @@ class ResponseFilter : ContainerResponseFilter { headers.add("Access-Control-Allow-Headers", "Content-Type,Accept,Origin") headers.add("Access-Control-Allow-Methods", "POST,PUT,GET,OPTIONS") } - } - }