CORDA-499: Remove further Kt classes (#1489)

* Change how NetworkHostAndPort is parsed

Change from using a global extension function to parse
NetworkHostAndPort strings, into using a function on the companion
object. This is a lot easier for Java interop and matches the common
style used elsewhere both in Corda and in Java libraries.

* Move JAR extraction into new utils file

* Move path verification function to ArtemisUtils

Move path verification function "requireOnDefaultFileSystem()" to new
ArtemisUtils.kt file, as this makes more sense from a Java interop
perspective.

* Add JvmName to AMQPSchemaExtensions

* Add JvmName to AMQPSerializationScheme

* Revert "Move JAR extraction into new utils file"

This reverts commit 1f0f41909b68ff21cc24b5efd6a1a360393a0a14.

* Reformat code

* Run formatter on ArtemisUtils
This commit is contained in:
Ross Nicoll 2017-09-14 17:34:01 +01:00 committed by josecoll
parent 68153b5acd
commit 3d577e5eed
12 changed files with 64 additions and 49 deletions

View File

@ -2,26 +2,20 @@ package net.corda.core.utilities
import net.corda.core.serialization.CordaSerializable import net.corda.core.serialization.CordaSerializable
import java.net.URI import java.net.URI
import java.net.URISyntaxException
/** /**
* Tuple of host and port. Use [parseNetworkHostAndPort] on untrusted data. * Tuple of host and port. Use [NetworkHostAndPort.parse] on untrusted data.
* @param host a hostname or IP address. IPv6 addresses must not be enclosed in square brackets. * @param host a hostname or IP address. IPv6 addresses must not be enclosed in square brackets.
* @param port a valid port number. * @param port a valid port number.
*/ */
@CordaSerializable @CordaSerializable
data class NetworkHostAndPort(val host: String, val port: Int) { data class NetworkHostAndPort(val host: String, val port: Int) {
companion object { companion object {
internal val invalidPortFormat = "Invalid port: %s" internal const val INVALID_PORT_FORMAT = "Invalid port: %s"
internal val unparseableAddressFormat = "Unparseable address: %s" internal const val UNPARSEABLE_ADDRESS_FORMAT = "Unparseable address: %s"
internal val missingPortFormat = "Missing port: %s" internal const val MISSING_PORT_FORMAT = "Missing port: %s"
} private val bracketedHost = "\\[(.*)]".toRegex()
init {
require(port in (0..0xffff)) { invalidPortFormat.format(port) }
}
override fun toString() = if (':' in host) "[$host]:$port" else "$host:$port"
}
/** /**
* Parses a string of the form host:port into a [NetworkHostAndPort]. * Parses a string of the form host:port into a [NetworkHostAndPort].
@ -29,11 +23,22 @@ data class NetworkHostAndPort(val host: String, val port: Int) {
* Note this does not parse the toString of a resolved [java.net.InetSocketAddress], which is of a host/IP:port form. * Note this does not parse the toString of a resolved [java.net.InetSocketAddress], which is of a host/IP:port form.
* @throws IllegalArgumentException if the port is missing, the string is garbage, or the NetworkHostAndPort constructor rejected the parsed parts. * @throws IllegalArgumentException if the port is missing, the string is garbage, or the NetworkHostAndPort constructor rejected the parsed parts.
*/ */
fun String.parseNetworkHostAndPort() = run { @JvmStatic
val uri = URI(null, this, null, null, null) fun parse(str: String): NetworkHostAndPort {
require(uri.host != null) { NetworkHostAndPort.unparseableAddressFormat.format(this) } val uri = try {
require(uri.port != -1) { NetworkHostAndPort.missingPortFormat.format(this) } URI(null, str, null, null, null)
NetworkHostAndPort(bracketedHost.matchEntire(uri.host)?.groupValues?.get(1) ?: uri.host, uri.port) } catch(ex: URISyntaxException) {
throw IllegalArgumentException("Host and port syntax is invalid, expected host:port")
}
require(uri.host != null) { NetworkHostAndPort.UNPARSEABLE_ADDRESS_FORMAT.format(str) }
require(uri.port != -1) { NetworkHostAndPort.MISSING_PORT_FORMAT.format(str) }
return NetworkHostAndPort(bracketedHost.matchEntire(uri.host)?.groupValues?.get(1) ?: uri.host, uri.port)
}
} }
private val bracketedHost = "\\[(.*)]".toRegex() init {
require(port in (0..0xffff)) { INVALID_PORT_FORMAT.format(port) }
}
override fun toString() = if (':' in host) "[$host]:$port" else "$host:$port"
}

View File

@ -24,7 +24,7 @@ class NetworkHostAndPortTest {
listOf(65536, -1).forEach { listOf(65536, -1).forEach {
assertThatThrownBy { assertThatThrownBy {
NetworkHostAndPort("example.com", it) NetworkHostAndPort("example.com", it)
}.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.invalidPortFormat.format(it)) }.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.INVALID_PORT_FORMAT.format(it))
} }
} }
@ -41,20 +41,20 @@ class NetworkHostAndPortTest {
@Test @Test
fun `parseNetworkHostAndPort works`() { fun `parseNetworkHostAndPort works`() {
assertEquals(NetworkHostAndPort("example.com", 1234), "example.com:1234".parseNetworkHostAndPort()) assertEquals(NetworkHostAndPort("example.com", 1234), NetworkHostAndPort.parse("example.com:1234"))
assertEquals(NetworkHostAndPort("example.com", 65535), "example.com:65535".parseNetworkHostAndPort()) assertEquals(NetworkHostAndPort("example.com", 65535), NetworkHostAndPort.parse("example.com:65535"))
assertEquals(NetworkHostAndPort("1.2.3.4", 1234), "1.2.3.4:1234".parseNetworkHostAndPort()) assertEquals(NetworkHostAndPort("1.2.3.4", 1234), NetworkHostAndPort.parse("1.2.3.4:1234"))
assertEquals(NetworkHostAndPort("::1", 1234), "[::1]:1234".parseNetworkHostAndPort()) assertEquals(NetworkHostAndPort("::1", 1234), NetworkHostAndPort.parse("[::1]:1234"))
assertEquals(NetworkHostAndPort("0:0:0:0:0:0:0:1", 1234), "[0:0:0:0:0:0:0:1]:1234".parseNetworkHostAndPort()) assertEquals(NetworkHostAndPort("0:0:0:0:0:0:0:1", 1234), NetworkHostAndPort.parse("[0:0:0:0:0:0:0:1]:1234"))
listOf("0:0:0:0:0:0:0:1:1234", ":1234", "example.com:-1").forEach { listOf("0:0:0:0:0:0:0:1:1234", ":1234", "example.com:-1").forEach {
assertThatThrownBy { assertThatThrownBy {
it.parseNetworkHostAndPort() NetworkHostAndPort.parse(it)
}.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.unparseableAddressFormat.format(it)) }.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.UNPARSEABLE_ADDRESS_FORMAT.format(it))
} }
listOf("example.com:", "example.com").forEach { listOf("example.com:", "example.com").forEach {
assertThatThrownBy { assertThatThrownBy {
it.parseNetworkHostAndPort() NetworkHostAndPort.parse(it)
}.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.missingPortFormat.format(it)) }.isInstanceOf(IllegalArgumentException::class.java).hasMessage(NetworkHostAndPort.MISSING_PORT_FORMAT.format(it))
} }
} }
} }

View File

@ -7,8 +7,6 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory
import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants
import org.bouncycastle.asn1.x500.X500Name import org.bouncycastle.asn1.x500.X500Name
import java.nio.file.FileSystems
import java.nio.file.Path
sealed class ConnectionDirection { sealed class ConnectionDirection {
data class Inbound(val acceptorFactoryClassName: String) : ConnectionDirection() data class Inbound(val acceptorFactoryClassName: String) : ConnectionDirection()
@ -54,8 +52,8 @@ class ArtemisTcpTransport {
) )
if (config != null && enableSSL) { if (config != null && enableSSL) {
config.sslKeystore.expectedOnDefaultFileSystem() config.sslKeystore.requireOnDefaultFileSystem()
config.trustStoreFile.expectedOnDefaultFileSystem() config.trustStoreFile.requireOnDefaultFileSystem()
val tlsOptions = mapOf( val tlsOptions = mapOf(
// Enable TLS transport layer with client certs and restrict to at least SHA256 in handshake // Enable TLS transport layer with client certs and restrict to at least SHA256 in handshake
// and AES encryption // and AES encryption
@ -81,7 +79,3 @@ class ArtemisTcpTransport {
} }
} }
} }
fun Path.expectedOnDefaultFileSystem() {
require(fileSystem == FileSystems.getDefault()) { "Artemis only uses the default file system" }
}

View File

@ -0,0 +1,14 @@
@file:JvmName("ArtemisUtils")
package net.corda.nodeapi
import java.nio.file.FileSystems
import java.nio.file.Path
/**
* Require that the [Path] is on a default file system, and therefore is one that Artemis is willing to use.
* @throws IllegalArgumentException if the path is not on a default file system.
*/
fun Path.requireOnDefaultFileSystem() {
require(fileSystem == FileSystems.getDefault()) { "Artemis only uses the default file system" }
}

View File

@ -6,7 +6,6 @@ import com.typesafe.config.ConfigUtil
import net.corda.core.identity.CordaX500Name import net.corda.core.identity.CordaX500Name
import net.corda.core.internal.noneOrSingle import net.corda.core.internal.noneOrSingle
import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.parseNetworkHostAndPort
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import java.net.Proxy import java.net.Proxy
import java.net.URL import java.net.URL
@ -69,7 +68,7 @@ private fun Config.getSingleValue(path: String, type: KType): Any? {
Boolean::class -> getBoolean(path) Boolean::class -> getBoolean(path)
LocalDate::class -> LocalDate.parse(getString(path)) LocalDate::class -> LocalDate.parse(getString(path))
Instant::class -> Instant.parse(getString(path)) Instant::class -> Instant.parse(getString(path))
NetworkHostAndPort::class -> getString(path).parseNetworkHostAndPort() NetworkHostAndPort::class -> NetworkHostAndPort.parse(getString(path))
Path::class -> Paths.get(getString(path)) Path::class -> Paths.get(getString(path))
URL::class -> URL(getString(path)) URL::class -> URL(getString(path))
Properties::class -> getConfig(path).toProperties() Properties::class -> getConfig(path).toProperties()
@ -97,7 +96,7 @@ private fun Config.getCollectionValue(path: String, type: KType): Collection<Any
Boolean::class -> getBooleanList(path) Boolean::class -> getBooleanList(path)
LocalDate::class -> getStringList(path).map(LocalDate::parse) LocalDate::class -> getStringList(path).map(LocalDate::parse)
Instant::class -> getStringList(path).map(Instant::parse) Instant::class -> getStringList(path).map(Instant::parse)
NetworkHostAndPort::class -> getStringList(path).map { it.parseNetworkHostAndPort() } NetworkHostAndPort::class -> getStringList(path).map(NetworkHostAndPort.Companion::parse)
Path::class -> getStringList(path).map { Paths.get(it) } Path::class -> getStringList(path).map { Paths.get(it) }
URL::class -> getStringList(path).map(::URL) URL::class -> getStringList(path).map(::URL)
CordaX500Name::class -> getStringList(path).map(CordaX500Name.Companion::parse) CordaX500Name::class -> getStringList(path).map(CordaX500Name.Companion::parse)

View File

@ -1,3 +1,5 @@
@file:JvmName("AMQPSerializationScheme")
package net.corda.nodeapi.internal.serialization package net.corda.nodeapi.internal.serialization
import net.corda.core.node.CordaPluginRegistry import net.corda.core.node.CordaPluginRegistry

View File

@ -1,3 +1,5 @@
@file:JvmName("AMQPSchemaExtensions")
package net.corda.nodeapi.internal.serialization.carpenter package net.corda.nodeapi.internal.serialization.carpenter
import net.corda.nodeapi.internal.serialization.amqp.CompositeType import net.corda.nodeapi.internal.serialization.amqp.CompositeType

View File

@ -242,7 +242,7 @@ open class Node(override val configuration: FullNodeConfiguration,
session.deleteQueue(queueName) session.deleteQueue(queueName)
clientFactory.close() clientFactory.close()
return publicHostAndPort.removePrefix("/").parseNetworkHostAndPort().host return NetworkHostAndPort.parse(publicHostAndPort.removePrefix("/")).host
} }
override fun startMessagingService(rpcOps: RPCOps) { override fun startMessagingService(rpcOps: RPCOps) {

View File

@ -119,7 +119,7 @@ class ArtemisMessagingServer(override val config: NodeConfiguration,
private val nodeRunsNetworkMapService = config.networkMapService == null private val nodeRunsNetworkMapService = config.networkMapService == null
init { init {
config.baseDirectory.expectedOnDefaultFileSystem() config.baseDirectory.requireOnDefaultFileSystem()
} }
/** /**

View File

@ -12,7 +12,6 @@ import net.corda.core.internal.concurrent.map
import net.corda.core.internal.div import net.corda.core.internal.div
import net.corda.core.messaging.RPCOps import net.corda.core.messaging.RPCOps
import net.corda.core.utilities.NetworkHostAndPort import net.corda.core.utilities.NetworkHostAndPort
import net.corda.core.utilities.parseNetworkHostAndPort
import net.corda.node.services.RPCUserService import net.corda.node.services.RPCUserService
import net.corda.node.services.messaging.ArtemisMessagingServer import net.corda.node.services.messaging.ArtemisMessagingServer
import net.corda.node.services.messaging.RPCServer import net.corda.node.services.messaging.RPCServer
@ -508,7 +507,7 @@ class RandomRpcUser {
require(args.size == 4) require(args.size == 4)
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
val rpcClass = Class.forName(args[0]) as Class<RPCOps> val rpcClass = Class.forName(args[0]) as Class<RPCOps>
val hostAndPort = args[1].parseNetworkHostAndPort() val hostAndPort = NetworkHostAndPort.parse(args[1])
val username = args[2] val username = args[2]
val password = args[3] val password = args[3]
CordaRPCClient.initialiseSerialization() CordaRPCClient.initialiseSerialization()

View File

@ -653,7 +653,7 @@ class DriverDSL(
is NetworkMapStartStrategy.Nominated -> { is NetworkMapStartStrategy.Nominated -> {
serviceConfig(networkMapCandidates.filter { serviceConfig(networkMapCandidates.filter {
it.name == legalName.toString() it.name == legalName.toString()
}.single().config.getString("p2pAddress").parseNetworkHostAndPort()).let { }.single().config.getString("p2pAddress").let(NetworkHostAndPort.Companion::parse)).let {
{ nodeName: CordaX500Name -> if (nodeName == legalName) null else it } { nodeName: CordaX500Name -> if (nodeName == legalName) null else it }
} }
} }

View File

@ -4,7 +4,7 @@ import com.typesafe.config.Config
import net.corda.core.identity.CordaX500Name import net.corda.core.identity.CordaX500Name
import net.corda.core.node.services.ServiceInfo import net.corda.core.node.services.ServiceInfo
import net.corda.core.node.services.ServiceType import net.corda.core.node.services.ServiceType
import net.corda.core.utilities.parseNetworkHostAndPort import net.corda.core.utilities.NetworkHostAndPort
import tornadofx.* import tornadofx.*
import java.io.IOException import java.io.IOException
import java.nio.file.Files import java.nio.file.Files
@ -48,7 +48,7 @@ class InstallFactory : Controller() {
private fun Config.parsePort(path: String): Int { private fun Config.parsePort(path: String): Int {
val address = this.getString(path) val address = this.getString(path)
val port = address.parseNetworkHostAndPort().port val port = NetworkHostAndPort.parse(address).port
require(nodeController.isPortValid(port), { "Invalid port $port from '$path'." }) require(nodeController.isPortValid(port), { "Invalid port $port from '$path'." })
return port return port
} }