Reformat files in node-api

This commit is contained in:
Tommy Lillehagen 2017-10-06 15:27:39 +01:00
parent cb9e27a84a
commit f98942d7ad
36 changed files with 256 additions and 212 deletions

View File

@ -68,7 +68,7 @@ object RPCApi {
val RPC_CLIENT_BINDING_REMOVAL_FILTER_EXPRESSION = val RPC_CLIENT_BINDING_REMOVAL_FILTER_EXPRESSION =
"${ManagementHelper.HDR_NOTIFICATION_TYPE} = '${CoreNotificationType.BINDING_REMOVED.name}' AND " + "${ManagementHelper.HDR_NOTIFICATION_TYPE} = '${CoreNotificationType.BINDING_REMOVED.name}' AND " +
"${ManagementHelper.HDR_ROUTING_NAME} LIKE '$RPC_CLIENT_QUEUE_NAME_PREFIX.%'" "${ManagementHelper.HDR_ROUTING_NAME} LIKE '$RPC_CLIENT_QUEUE_NAME_PREFIX.%'"
val RPC_CLIENT_BINDING_ADDITION_FILTER_EXPRESSION = val RPC_CLIENT_BINDING_ADDITION_FILTER_EXPRESSION =
"${ManagementHelper.HDR_NOTIFICATION_TYPE} = '${CoreNotificationType.BINDING_ADDED.name}' AND " + "${ManagementHelper.HDR_NOTIFICATION_TYPE} = '${CoreNotificationType.BINDING_ADDED.name}' AND " +
"${ManagementHelper.HDR_ROUTING_NAME} LIKE '$RPC_CLIENT_QUEUE_NAME_PREFIX.%'" "${ManagementHelper.HDR_ROUTING_NAME} LIKE '$RPC_CLIENT_QUEUE_NAME_PREFIX.%'"
@ -141,7 +141,7 @@ object RPCApi {
val ids = ArrayList<ObservableId>() val ids = ArrayList<ObservableId>()
val buffer = message.bodyBuffer val buffer = message.bodyBuffer
val numberOfIds = buffer.readInt() val numberOfIds = buffer.readInt()
for (i in 1 .. numberOfIds) { for (i in 1..numberOfIds) {
ids.add(ObservableId(buffer.readLong())) ids.add(ObservableId(buffer.readLong()))
} }
ObservablesClosed(ids) ObservablesClosed(ids)

View File

@ -1,4 +1,5 @@
@file:JvmName("ConfigUtilities") @file:JvmName("ConfigUtilities")
package net.corda.nodeapi.config package net.corda.nodeapi.config
import com.typesafe.config.Config import com.typesafe.config.Config

View File

@ -72,7 +72,7 @@ class AttachmentsClassLoader(attachments: List<Attachment>, parent: ClassLoader
val stream = ByteArrayOutputStream() val stream = ByteArrayOutputStream()
try { try {
attachment.extractFile(path, stream) attachment.extractFile(path, stream)
} catch(e: FileNotFoundException) { } catch (e: FileNotFoundException) {
throw ClassNotFoundException(name) throw ClassNotFoundException(name)
} }
val bytes = stream.toByteArray() val bytes = stream.toByteArray()
@ -99,7 +99,7 @@ class AttachmentsClassLoader(attachments: List<Attachment>, parent: ClassLoader
val stream = ByteArrayOutputStream() val stream = ByteArrayOutputStream()
attachment.extractFile(path, stream) attachment.extractFile(path, stream)
return ByteArrayInputStream(stream.toByteArray()) return ByteArrayInputStream(stream.toByteArray())
} catch(e: FileNotFoundException) { } catch (e: FileNotFoundException) {
return null return null
} }
} }

View File

@ -1,4 +1,5 @@
@file:JvmName("ClientContexts") @file:JvmName("ClientContexts")
package net.corda.nodeapi.internal.serialization package net.corda.nodeapi.internal.serialization
import net.corda.core.serialization.SerializationContext import net.corda.core.serialization.SerializationContext

View File

@ -31,9 +31,9 @@ class CordaClassResolver(serializationContext: SerializationContext) : DefaultCl
* The point is that we do not want to send Kotlin types "over the wire" via RPC. * The point is that we do not want to send Kotlin types "over the wire" via RPC.
*/ */
private val javaAliases: Map<Class<*>, Class<*>> = mapOf( private val javaAliases: Map<Class<*>, Class<*>> = mapOf(
listOf<Any>().javaClass to Collections.emptyList<Any>().javaClass, listOf<Any>().javaClass to Collections.emptyList<Any>().javaClass,
setOf<Any>().javaClass to Collections.emptySet<Any>().javaClass, setOf<Any>().javaClass to Collections.emptySet<Any>().javaClass,
mapOf<Any, Any>().javaClass to Collections.emptyMap<Any, Any>().javaClass mapOf<Any, Any>().javaClass to Collections.emptyMap<Any, Any>().javaClass
) )
private fun typeForSerializationOf(type: Class<*>): Class<*> = javaAliases[type] ?: type private fun typeForSerializationOf(type: Class<*>): Class<*> = javaAliases[type] ?: type
@ -194,7 +194,7 @@ class LoggingWhitelist(val delegate: ClassWhitelist, val global: Boolean = true)
if (fileName != null && fileName.isNotEmpty()) { if (fileName != null && fileName.isNotEmpty()) {
try { try {
return PrintWriter(Files.newBufferedWriter(Paths.get(fileName), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE), true) return PrintWriter(Files.newBufferedWriter(Paths.get(fileName), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE), true)
} catch(ioEx: Exception) { } catch (ioEx: Exception) {
log.error("Could not open/create whitelist journal file for append: $fileName", ioEx) log.error("Could not open/create whitelist journal file for append: $fileName", ioEx)
} }
} }

View File

@ -140,6 +140,7 @@ object DefaultKryoCustomizer {
// Use this to allow construction of objects using a JVM backdoor that skips invoking the constructors, if there // Use this to allow construction of objects using a JVM backdoor that skips invoking the constructors, if there
// is no no-arg constructor available. // is no no-arg constructor available.
private val defaultStrategy = Kryo.DefaultInstantiatorStrategy(fallbackStrategy) private val defaultStrategy = Kryo.DefaultInstantiatorStrategy(fallbackStrategy)
override fun <T> newInstantiatorOf(type: Class<T>): ObjectInstantiator<T> { override fun <T> newInstantiatorOf(type: Class<T>): ObjectInstantiator<T> {
// However this doesn't work for non-public classes in the java. namespace // However this doesn't work for non-public classes in the java. namespace
val strat = if (type.name.startsWith("java.") && !isPublic(type.modifiers)) fallbackStrategy else defaultStrategy val strat = if (type.name.startsWith("java.") && !isPublic(type.modifiers)) fallbackStrategy else defaultStrategy
@ -151,6 +152,7 @@ object DefaultKryoCustomizer {
override fun write(kryo: Kryo, output: Output, obj: PartyAndCertificate) { override fun write(kryo: Kryo, output: Output, obj: PartyAndCertificate) {
kryo.writeClassAndObject(output, obj.certPath) kryo.writeClassAndObject(output, obj.certPath)
} }
override fun read(kryo: Kryo, input: Input, type: Class<PartyAndCertificate>): PartyAndCertificate { override fun read(kryo: Kryo, input: Input, type: Class<PartyAndCertificate>): PartyAndCertificate {
return PartyAndCertificate(kryo.readClassAndObject(input) as CertPath) return PartyAndCertificate(kryo.readClassAndObject(input) as CertPath)
} }

View File

@ -546,7 +546,7 @@ class ThrowableSerializer<T>(kryo: Kryo, type: Class<T>) : Serializer<Throwable>
override fun read(kryo: Kryo, input: Input, type: Class<Throwable>): Throwable { override fun read(kryo: Kryo, input: Input, type: Class<Throwable>): Throwable {
val throwableRead = delegate.read(kryo, input, type) val throwableRead = delegate.read(kryo, input, type)
if(throwableRead.suppressed.isEmpty()) { if (throwableRead.suppressed.isEmpty()) {
throwableRead.setSuppressedToSentinel() throwableRead.setSuppressedToSentinel()
} }
return throwableRead return throwableRead

View File

@ -142,8 +142,8 @@ open class SerializationFactoryImpl : SerializationFactory() {
private object AutoCloseableSerialisationDetector : Serializer<AutoCloseable>() { private object AutoCloseableSerialisationDetector : Serializer<AutoCloseable>() {
override fun write(kryo: Kryo, output: Output, closeable: AutoCloseable) { override fun write(kryo: Kryo, output: Output, closeable: AutoCloseable) {
val message = "${closeable.javaClass.name}, which is a closeable resource, has been detected during flow checkpointing. " + val message = "${closeable.javaClass.name}, which is a closeable resource, has been detected during flow checkpointing. " +
"Restoring such resources across node restarts is not supported. Make sure code accessing it is " + "Restoring such resources across node restarts is not supported. Make sure code accessing it is " +
"confined to a private method or the reference is nulled out." "confined to a private method or the reference is nulled out."
throw UnsupportedOperationException(message) throw UnsupportedOperationException(message)
} }

View File

@ -1,4 +1,5 @@
@file:JvmName("ServerContexts") @file:JvmName("ServerContexts")
package net.corda.nodeapi.internal.serialization package net.corda.nodeapi.internal.serialization
import net.corda.core.serialization.ClassWhitelist import net.corda.core.serialization.ClassWhitelist

View File

@ -6,7 +6,7 @@ import java.util.*
internal fun checkUseCase(allowedUseCases: EnumSet<SerializationContext.UseCase>) { internal fun checkUseCase(allowedUseCases: EnumSet<SerializationContext.UseCase>) {
val currentContext: SerializationContext = SerializationFactory.currentFactory?.currentContext ?: throw IllegalStateException("Current context is not set") val currentContext: SerializationContext = SerializationFactory.currentFactory?.currentContext ?: throw IllegalStateException("Current context is not set")
if(!allowedUseCases.contains(currentContext.useCase)) { if (!allowedUseCases.contains(currentContext.useCase)) {
throw IllegalStateException("UseCase '${currentContext.useCase}' is not within '$allowedUseCases'") throw IllegalStateException("UseCase '${currentContext.useCase}' is not within '$allowedUseCases'")
} }
} }

View File

@ -23,14 +23,13 @@ open class ArraySerializer(override val type: Type, factory: SerializerFactory)
// //
// We *need* to retain knowledge for AMQP deserialisation weather that lowest primitive // We *need* to retain knowledge for AMQP deserialisation weather that lowest primitive
// was boxed or unboxed so just infer it recursively // was boxed or unboxed so just infer it recursively
private fun calcTypeName(type: Type) : String = private fun calcTypeName(type: Type): String =
if (type.componentType().isArray()) { if (type.componentType().isArray()) {
val typeName = calcTypeName(type.componentType()); "$typeName[]" val typeName = calcTypeName(type.componentType()); "$typeName[]"
} } else {
else { val arrayType = if (type.asClass()!!.componentType.isPrimitive) "[p]" else "[]"
val arrayType = if (type.asClass()!!.componentType.isPrimitive) "[p]" else "[]" "${type.componentType().typeName}$arrayType"
"${type.componentType().typeName}$arrayType" }
}
override val typeDescriptor by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${fingerprintForType(type, factory)}") } override val typeDescriptor by lazy { Symbol.valueOf("$DESCRIPTOR_DOMAIN:${fingerprintForType(type, factory)}") }
internal val elementType: Type by lazy { type.componentType() } internal val elementType: Type by lazy { type.componentType() }

View File

@ -35,11 +35,10 @@ class CollectionSerializer(val declaredType: ParameterizedType, factory: Seriali
} }
fun deriveParameterizedType(declaredType: Type, declaredClass: Class<*>, actualClass: Class<*>?): ParameterizedType { fun deriveParameterizedType(declaredType: Type, declaredClass: Class<*>, actualClass: Class<*>?): ParameterizedType {
if(supportedTypes.containsKey(declaredClass)) { if (supportedTypes.containsKey(declaredClass)) {
// Simple case - it is already known to be a collection. // Simple case - it is already known to be a collection.
return deriveParametrizedType(declaredType, uncheckedCast(declaredClass)) return deriveParametrizedType(declaredType, uncheckedCast(declaredClass))
} } else if (actualClass != null && Collection::class.java.isAssignableFrom(actualClass)) {
else if (actualClass != null && Collection::class.java.isAssignableFrom(actualClass)) {
// Declared class is not collection, but [actualClass] is - represent it accordingly. // Declared class is not collection, but [actualClass] is - represent it accordingly.
val collectionClass = findMostSuitableCollectionType(actualClass) val collectionClass = findMostSuitableCollectionType(actualClass)
return deriveParametrizedType(declaredType, collectionClass) return deriveParametrizedType(declaredType, collectionClass)
@ -49,11 +48,11 @@ class CollectionSerializer(val declaredType: ParameterizedType, factory: Seriali
} }
private fun deriveParametrizedType(declaredType: Type, collectionClass: Class<out Collection<*>>): ParameterizedType = private fun deriveParametrizedType(declaredType: Type, collectionClass: Class<out Collection<*>>): ParameterizedType =
(declaredType as? ParameterizedType) ?: DeserializedParameterizedType(collectionClass, arrayOf(SerializerFactory.AnyType)) (declaredType as? ParameterizedType) ?: DeserializedParameterizedType(collectionClass, arrayOf(SerializerFactory.AnyType))
private fun findMostSuitableCollectionType(actualClass: Class<*>): Class<out Collection<*>> = private fun findMostSuitableCollectionType(actualClass: Class<*>): Class<out Collection<*>> =
supportedTypes.keys.findLast { it.isAssignableFrom(actualClass) }!! supportedTypes.keys.findLast { it.isAssignableFrom(actualClass) }!!
} }
@ -61,13 +60,13 @@ class CollectionSerializer(val declaredType: ParameterizedType, factory: Seriali
private val typeNotation: TypeNotation = RestrictedType(SerializerFactory.nameForType(declaredType), null, emptyList(), "list", Descriptor(typeDescriptor), emptyList()) private val typeNotation: TypeNotation = RestrictedType(SerializerFactory.nameForType(declaredType), null, emptyList(), "list", Descriptor(typeDescriptor), emptyList())
override fun writeClassInfo(output: SerializationOutput) = ifThrowsAppend({declaredType.typeName}) { override fun writeClassInfo(output: SerializationOutput) = ifThrowsAppend({ declaredType.typeName }) {
if (output.writeTypeNotations(typeNotation)) { if (output.writeTypeNotations(typeNotation)) {
output.requireSerializer(declaredType.actualTypeArguments[0]) output.requireSerializer(declaredType.actualTypeArguments[0])
} }
} }
override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput) = ifThrowsAppend({declaredType.typeName}) { override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput) = ifThrowsAppend({ declaredType.typeName }) {
// Write described // Write described
data.withDescribed(typeNotation.descriptor) { data.withDescribed(typeNotation.descriptor) {
withList { withList {
@ -78,7 +77,7 @@ class CollectionSerializer(val declaredType: ParameterizedType, factory: Seriali
} }
} }
override fun readObject(obj: Any, schema: Schema, input: DeserializationInput): Any = ifThrowsAppend({declaredType.typeName}) { override fun readObject(obj: Any, schema: Schema, input: DeserializationInput): Any = ifThrowsAppend({ declaredType.typeName }) {
// TODO: Can we verify the entries in the list? // TODO: Can we verify the entries in the list?
concreteBuilder((obj as List<*>).map { input.readObjectOrNull(it, schema, declaredType.actualTypeArguments[0]) }) concreteBuilder((obj as List<*>).map { input.readObjectOrNull(it, schema, declaredType.actualTypeArguments[0]) })
} }

View File

@ -102,9 +102,9 @@ abstract class CustomSerializer<T : Any> : AMQPSerializer<T> {
* custom serializers. * custom serializers.
*/ */
abstract class Proxy<T : Any, P : Any>(clazz: Class<T>, abstract class Proxy<T : Any, P : Any>(clazz: Class<T>,
protected val proxyClass: Class<P>, protected val proxyClass: Class<P>,
protected val factory: SerializerFactory, protected val factory: SerializerFactory,
withInheritance: Boolean = true) : CustomSerializerImp<T>(clazz, withInheritance) { withInheritance: Boolean = true) : CustomSerializerImp<T>(clazz, withInheritance) {
override fun isSerializerFor(clazz: Class<*>): Boolean = if (withInheritance) this.clazz.isAssignableFrom(clazz) else this.clazz == clazz override fun isSerializerFor(clazz: Class<*>): Boolean = if (withInheritance) this.clazz.isAssignableFrom(clazz) else this.clazz == clazz
private val proxySerializer: ObjectSerializer by lazy { ObjectSerializer(proxyClass, factory) } private val proxySerializer: ObjectSerializer by lazy { ObjectSerializer(proxyClass, factory) }
@ -151,11 +151,10 @@ abstract class CustomSerializer<T : Any> : AMQPSerializer<T> {
* @param unmake A lambda that extracts the string value for an instance, that defaults to the [toString] method. * @param unmake A lambda that extracts the string value for an instance, that defaults to the [toString] method.
*/ */
abstract class ToString<T : Any>(clazz: Class<T>, withInheritance: Boolean = false, abstract class ToString<T : Any>(clazz: Class<T>, withInheritance: Boolean = false,
private val maker: (String) -> T = clazz.getConstructor(String::class.java).let { private val maker: (String) -> T = clazz.getConstructor(String::class.java).let { `constructor` ->
`constructor` -> { string -> `constructor`.newInstance(string) }
{ string -> `constructor`.newInstance(string) } },
}, private val unmaker: (T) -> String = { obj -> obj.toString() })
private val unmaker: (T) -> String = { obj -> obj.toString() })
: CustomSerializerImp<T>(clazz, withInheritance) { : CustomSerializerImp<T>(clazz, withInheritance) {
override val schemaForDocumentation = Schema( override val schemaForDocumentation = Schema(

View File

@ -80,9 +80,9 @@ class DeserializationInput(internal val serializerFactory: SerializerFactory) {
private fun <R> des(generator: () -> R): R { private fun <R> des(generator: () -> R): R {
try { try {
return generator() return generator()
} catch(nse: NotSerializableException) { } catch (nse: NotSerializableException) {
throw nse throw nse
} catch(t: Throwable) { } catch (t: Throwable) {
throw NotSerializableException("Unexpected throwable: ${t.message} ${t.getStackTraceAsString()}") throw NotSerializableException("Unexpected throwable: ${t.message} ${t.getStackTraceAsString()}")
} finally { } finally {
objectHistory.clear() objectHistory.clear()
@ -152,10 +152,10 @@ class DeserializationInput(internal val serializerFactory: SerializerFactory) {
* In the future tighter control might be needed * In the future tighter control might be needed
*/ */
private fun Type.materiallyEquivalentTo(that: Type): Boolean = private fun Type.materiallyEquivalentTo(that: Type): Boolean =
when(that) { when (that) {
is ParameterizedType -> asClass() == that.asClass() is ParameterizedType -> asClass() == that.asClass()
is TypeVariable<*> -> isSubClassOf(that.bounds.first()) is TypeVariable<*> -> isSubClassOf(that.bounds.first())
is WildcardType -> isSubClassOf(that.upperBounds.first()) is WildcardType -> isSubClassOf(that.upperBounds.first())
else -> false else -> false
} }
} }

View File

@ -42,11 +42,10 @@ class MapSerializer(private val declaredType: ParameterizedType, factory: Serial
fun deriveParameterizedType(declaredType: Type, declaredClass: Class<*>, actualClass: Class<*>?): ParameterizedType { fun deriveParameterizedType(declaredType: Type, declaredClass: Class<*>, actualClass: Class<*>?): ParameterizedType {
declaredClass.checkSupportedMapType() declaredClass.checkSupportedMapType()
if(supportedTypes.containsKey(declaredClass)) { if (supportedTypes.containsKey(declaredClass)) {
// Simple case - it is already known to be a map. // Simple case - it is already known to be a map.
return deriveParametrizedType(declaredType, uncheckedCast(declaredClass)) return deriveParametrizedType(declaredType, uncheckedCast(declaredClass))
} } else if (actualClass != null && Map::class.java.isAssignableFrom(actualClass)) {
else if (actualClass != null && Map::class.java.isAssignableFrom(actualClass)) {
// Declared class is not map, but [actualClass] is - represent it accordingly. // Declared class is not map, but [actualClass] is - represent it accordingly.
val mapClass = findMostSuitableMapType(actualClass) val mapClass = findMostSuitableMapType(actualClass)
return deriveParametrizedType(declaredType, mapClass) return deriveParametrizedType(declaredType, mapClass)
@ -67,14 +66,14 @@ class MapSerializer(private val declaredType: ParameterizedType, factory: Serial
private val typeNotation: TypeNotation = RestrictedType(SerializerFactory.nameForType(declaredType), null, emptyList(), "map", Descriptor(typeDescriptor), emptyList()) private val typeNotation: TypeNotation = RestrictedType(SerializerFactory.nameForType(declaredType), null, emptyList(), "map", Descriptor(typeDescriptor), emptyList())
override fun writeClassInfo(output: SerializationOutput) = ifThrowsAppend({declaredType.typeName}) { override fun writeClassInfo(output: SerializationOutput) = ifThrowsAppend({ declaredType.typeName }) {
if (output.writeTypeNotations(typeNotation)) { if (output.writeTypeNotations(typeNotation)) {
output.requireSerializer(declaredType.actualTypeArguments[0]) output.requireSerializer(declaredType.actualTypeArguments[0])
output.requireSerializer(declaredType.actualTypeArguments[1]) output.requireSerializer(declaredType.actualTypeArguments[1])
} }
} }
override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput) = ifThrowsAppend({declaredType.typeName}) { override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput) = ifThrowsAppend({ declaredType.typeName }) {
obj.javaClass.checkSupportedMapType() obj.javaClass.checkSupportedMapType()
// Write described // Write described
data.withDescribed(typeNotation.descriptor) { data.withDescribed(typeNotation.descriptor) {
@ -89,7 +88,7 @@ class MapSerializer(private val declaredType: ParameterizedType, factory: Serial
} }
} }
override fun readObject(obj: Any, schema: Schema, input: DeserializationInput): Any = ifThrowsAppend({declaredType.typeName}) { override fun readObject(obj: Any, schema: Schema, input: DeserializationInput): Any = ifThrowsAppend({ declaredType.typeName }) {
// TODO: General generics question. Do we need to validate that entries in Maps and Collections match the generic type? Is it a security hole? // TODO: General generics question. Do we need to validate that entries in Maps and Collections match the generic type? Is it a security hole?
val entries: Iterable<Pair<Any?, Any?>> = (obj as Map<*, *>).map { readEntry(schema, input, it) } val entries: Iterable<Pair<Any?, Any?>> = (obj as Map<*, *>).map { readEntry(schema, input, it) }
concreteBuilder(entries.toMap()) concreteBuilder(entries.toMap())
@ -108,13 +107,11 @@ internal fun Class<*>.checkSupportedMapType() {
if (HashMap::class.java.isAssignableFrom(this) && !LinkedHashMap::class.java.isAssignableFrom(this)) { if (HashMap::class.java.isAssignableFrom(this) && !LinkedHashMap::class.java.isAssignableFrom(this)) {
throw IllegalArgumentException( throw IllegalArgumentException(
"Map type $this is unstable under iteration. Suggested fix: use java.util.LinkedHashMap instead.") "Map type $this is unstable under iteration. Suggested fix: use java.util.LinkedHashMap instead.")
} } else if (WeakHashMap::class.java.isAssignableFrom(this)) {
else if (WeakHashMap::class.java.isAssignableFrom(this)) { throw IllegalArgumentException("Weak references with map types not supported. Suggested fix: "
throw IllegalArgumentException ("Weak references with map types not supported. Suggested fix: " + "use java.util.LinkedHashMap instead.")
+ "use java.util.LinkedHashMap instead.") } else if (Dictionary::class.java.isAssignableFrom(this)) {
} throw IllegalArgumentException(
else if (Dictionary::class.java.isAssignableFrom(this)) {
throw IllegalArgumentException (
"Unable to serialise deprecated type $this. Suggested fix: prefer java.util.map implementations") "Unable to serialise deprecated type $this. Suggested fix: prefer java.util.map implementations")
} }
} }

View File

@ -41,7 +41,7 @@ open class ObjectSerializer(val clazz: Type, factory: SerializerFactory) : AMQPS
} }
} }
override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput) = ifThrowsAppend({clazz.typeName}) { override fun writeObject(obj: Any, data: Data, type: Type, output: SerializationOutput) = ifThrowsAppend({ clazz.typeName }) {
// Write described // Write described
data.withDescribed(typeNotation.descriptor) { data.withDescribed(typeNotation.descriptor) {
// Write list // Write list
@ -53,7 +53,7 @@ open class ObjectSerializer(val clazz: Type, factory: SerializerFactory) : AMQPS
} }
} }
override fun readObject(obj: Any, schema: Schema, input: DeserializationInput): Any = ifThrowsAppend({clazz.typeName}) { override fun readObject(obj: Any, schema: Schema, input: DeserializationInput): Any = ifThrowsAppend({ clazz.typeName }) {
if (obj is List<*>) { if (obj is List<*>) {
if (obj.size > propertySerializers.size) throw NotSerializableException("Too many properties in described type $typeName") if (obj.size > propertySerializers.size) throw NotSerializableException("Too many properties in described type $typeName")
val params = obj.zip(propertySerializers).map { it.second.readProperty(it.first, schema, input) } val params = obj.zip(propertySerializers).map { it.second.readProperty(it.first, schema, input) }

View File

@ -52,7 +52,7 @@ sealed class PropertySerializer(val name: String, val readMethod: Method?, val r
try { try {
val returnTypeString = this.declaringClass.kotlin.memberProperties.firstOrNull { it.javaGetter == this }?.returnType?.toString() ?: "?" val returnTypeString = this.declaringClass.kotlin.memberProperties.firstOrNull { it.javaGetter == this }?.returnType?.toString() ?: "?"
return returnTypeString.endsWith('?') || returnTypeString.endsWith('!') return returnTypeString.endsWith('?') || returnTypeString.endsWith('!')
} catch(e: kotlin.reflect.jvm.internal.KotlinReflectionInternalError) { } catch (e: kotlin.reflect.jvm.internal.KotlinReflectionInternalError) {
// This might happen for some types, e.g. kotlin.Throwable? - the root cause of the issue is: https://youtrack.jetbrains.com/issue/KT-13077 // This might happen for some types, e.g. kotlin.Throwable? - the root cause of the issue is: https://youtrack.jetbrains.com/issue/KT-13077
// TODO: Revisit this when Kotlin issue is fixed. // TODO: Revisit this when Kotlin issue is fixed.
logger.error("Unexpected internal Kotlin error", e) logger.error("Unexpected internal Kotlin error", e)
@ -66,7 +66,7 @@ sealed class PropertySerializer(val name: String, val readMethod: Method?, val r
fun make(name: String, readMethod: Method?, resolvedType: Type, factory: SerializerFactory): PropertySerializer { fun make(name: String, readMethod: Method?, resolvedType: Type, factory: SerializerFactory): PropertySerializer {
readMethod?.isAccessible = true readMethod?.isAccessible = true
if (SerializerFactory.isPrimitive(resolvedType)) { if (SerializerFactory.isPrimitive(resolvedType)) {
return when(resolvedType) { return when (resolvedType) {
Char::class.java, Character::class.java -> AMQPCharPropertySerializer(name, readMethod) Char::class.java, Character::class.java -> AMQPCharPropertySerializer(name, readMethod)
else -> AMQPPrimitivePropertySerializer(name, readMethod, resolvedType) else -> AMQPPrimitivePropertySerializer(name, readMethod, resolvedType)
} }
@ -86,17 +86,17 @@ sealed class PropertySerializer(val name: String, val readMethod: Method?, val r
// This is lazy so we don't get an infinite loop when a method returns an instance of the class. // This is lazy so we don't get an infinite loop when a method returns an instance of the class.
private val typeSerializer: AMQPSerializer<*> by lazy { lazyTypeSerializer() } private val typeSerializer: AMQPSerializer<*> by lazy { lazyTypeSerializer() }
override fun writeClassInfo(output: SerializationOutput) = ifThrowsAppend({nameForDebug}) { override fun writeClassInfo(output: SerializationOutput) = ifThrowsAppend({ nameForDebug }) {
if (resolvedType != Any::class.java) { if (resolvedType != Any::class.java) {
typeSerializer.writeClassInfo(output) typeSerializer.writeClassInfo(output)
} }
} }
override fun readProperty(obj: Any?, schema: Schema, input: DeserializationInput): Any? = ifThrowsAppend({nameForDebug}) { override fun readProperty(obj: Any?, schema: Schema, input: DeserializationInput): Any? = ifThrowsAppend({ nameForDebug }) {
input.readObjectOrNull(obj, schema, resolvedType) input.readObjectOrNull(obj, schema, resolvedType)
} }
override fun writeProperty(obj: Any?, data: Data, output: SerializationOutput) = ifThrowsAppend({nameForDebug}) { override fun writeProperty(obj: Any?, data: Data, output: SerializationOutput) = ifThrowsAppend({ nameForDebug }) {
output.writeObjectOrNull(readMethod!!.invoke(obj), data, resolvedType) output.writeObjectOrNull(readMethod!!.invoke(obj), data, resolvedType)
} }
@ -133,7 +133,7 @@ sealed class PropertySerializer(val name: String, val readMethod: Method?, val r
override fun writeClassInfo(output: SerializationOutput) {} override fun writeClassInfo(output: SerializationOutput) {}
override fun readProperty(obj: Any?, schema: Schema, input: DeserializationInput): Any? { override fun readProperty(obj: Any?, schema: Schema, input: DeserializationInput): Any? {
return if(obj == null) null else (obj as Short).toChar() return if (obj == null) null else (obj as Short).toChar()
} }
override fun writeProperty(obj: Any?, data: Data, output: SerializationOutput) { override fun writeProperty(obj: Any?, data: Data, output: SerializationOutput) {

View File

@ -82,14 +82,13 @@ open class SerializationOutput(internal val serializerFactory: SerializerFactory
} }
val retrievedRefCount = objectHistory[obj] val retrievedRefCount = objectHistory[obj]
if(retrievedRefCount == null) { if (retrievedRefCount == null) {
serializer.writeObject(obj, data, type, this) serializer.writeObject(obj, data, type, this)
// Important to do it after serialization such that dependent object will have preceding reference numbers // Important to do it after serialization such that dependent object will have preceding reference numbers
// assigned to them first as they will be first read from the stream on receiving end. // 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 // 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) if (suitableForObjectReference(obj.javaClass)) objectHistory.put(obj, objectHistory.size)
} } else {
else {
data.writeReferencedObject(ReferencedObject(retrievedRefCount)) data.writeReferencedObject(ReferencedObject(retrievedRefCount))
} }
} }

View File

@ -27,7 +27,7 @@ class ThrowableSerializer(factory: SerializerFactory) : CustomSerializer.Proxy<T
for (prop in props) { for (prop in props) {
extraProperties[prop.name] = prop.readMethod!!.invoke(obj) extraProperties[prop.name] = prop.readMethod!!.invoke(obj)
} }
} catch(e: NotSerializableException) { } catch (e: NotSerializableException) {
logger.warn("Unexpected exception", e) logger.warn("Unexpected exception", e)
} }
obj.originalMessage obj.originalMessage

View File

@ -12,10 +12,12 @@ class ZonedDateTimeSerializer(factory: SerializerFactory) : CustomSerializer.Pro
// so that any change to internals of `ZonedDateTime` is detected early. // so that any change to internals of `ZonedDateTime` is detected early.
companion object { companion object {
val ofLenient = ZonedDateTime::class.java.getDeclaredMethod("ofLenient", LocalDateTime::class.java, ZoneOffset::class.java, ZoneId::class.java) val ofLenient = ZonedDateTime::class.java.getDeclaredMethod("ofLenient", LocalDateTime::class.java, ZoneOffset::class.java, ZoneId::class.java)
init { init {
ofLenient.isAccessible = true ofLenient.isAccessible = true
} }
} }
override val additionalSerializers: Iterable<CustomSerializer<out Any>> = listOf(LocalDateTimeSerializer(factory), ZoneIdSerializer(factory)) override val additionalSerializers: Iterable<CustomSerializer<out Any>> = listOf(LocalDateTimeSerializer(factory), ZoneIdSerializer(factory))
override fun toProxy(obj: ZonedDateTime): ZonedDateTimeProxy = ZonedDateTimeProxy(obj.toLocalDateTime(), obj.offset, obj.zone) override fun toProxy(obj: ZonedDateTime): ZonedDateTimeProxy = ZonedDateTimeProxy(obj.toLocalDateTime(), obj.offset, obj.zone)

View File

@ -132,5 +132,10 @@ fun AMQPField.validateType(classloader: ClassLoader) = when (type) {
} }
private fun ClassLoader.exists(clazz: String) = run { private fun ClassLoader.exists(clazz: String) = run {
try { this.loadClass(clazz); true } catch (e: ClassNotFoundException) { false } } try {
this.loadClass(clazz); true
} catch (e: ClassNotFoundException) {
false
}
}

View File

@ -24,7 +24,7 @@ abstract class Schema(
updater: (String, Field) -> Unit) { updater: (String, Field) -> Unit) {
private fun Map<String, Field>.descriptors() = LinkedHashMap(this.mapValues { it.value.descriptor }) private fun Map<String, Field>.descriptors() = LinkedHashMap(this.mapValues { it.value.descriptor })
var flags : EnumMap<SchemaFlags, Boolean> = EnumMap(SchemaFlags::class.java) var flags: EnumMap<SchemaFlags, Boolean> = EnumMap(SchemaFlags::class.java)
init { init {
fields.forEach { updater(it.key, it.value) } fields.forEach { updater(it.key, it.value) }
@ -49,15 +49,15 @@ abstract class Schema(
get() = "[L$jvmName;" get() = "[L$jvmName;"
fun unsetCordaSerializable() { fun unsetCordaSerializable() {
flags.replace (SchemaFlags.CordaSerializable, false) flags.replace(SchemaFlags.CordaSerializable, false)
} }
} }
fun EnumMap<SchemaFlags, Boolean>.cordaSerializable() : Boolean { fun EnumMap<SchemaFlags, Boolean>.cordaSerializable(): Boolean {
return this.getOrDefault(SchemaFlags.CordaSerializable, true) == true return this.getOrDefault(SchemaFlags.CordaSerializable, true) == true
} }
fun EnumMap<SchemaFlags, Boolean>.simpleFieldAccess() : Boolean { fun EnumMap<SchemaFlags, Boolean>.simpleFieldAccess(): Boolean {
return this.getOrDefault(SchemaFlags.SimpleFieldAccess, true) == true return this.getOrDefault(SchemaFlags.SimpleFieldAccess, true) == true
} }

View File

@ -12,7 +12,8 @@ import java.util.List;
public class ListsSerializationJavaTest { public class ListsSerializationJavaTest {
@CordaSerializable @CordaSerializable
interface Parent {} interface Parent {
}
public static class Child implements Parent { public static class Child implements Parent {
private final int value; private final int value;
@ -123,7 +124,7 @@ public class ListsSerializationJavaTest {
} }
// Have to have own version as Kotlin inline functions cannot be easily called from Java // Have to have own version as Kotlin inline functions cannot be easily called from Java
private static<T> void assertEqualAfterRoundTripSerialization(T container, Class<T> clazz) throws Exception { private static <T> void assertEqualAfterRoundTripSerialization(T container, Class<T> clazz) throws Exception {
SerializerFactory factory1 = new SerializerFactory(AllWhitelist.INSTANCE, ClassLoader.getSystemClassLoader()); SerializerFactory factory1 = new SerializerFactory(AllWhitelist.INSTANCE, ClassLoader.getSystemClassLoader());
SerializationOutput ser = new SerializationOutput(factory1); SerializationOutput ser = new SerializationOutput(factory1);
SerializedBytes<Object> bytes = ser.serialize(container); SerializedBytes<Object> bytes = ser.serialize(container);

View File

@ -37,7 +37,7 @@ class AttachmentsClassLoaderStaticContractTests : TestDependencyInjectionBase()
fun generateInitial(owner: PartyAndReference, magicNumber: Int, notary: Party): TransactionBuilder { fun generateInitial(owner: PartyAndReference, magicNumber: Int, notary: Party): TransactionBuilder {
val state = State(magicNumber) val state = State(magicNumber)
return TransactionBuilder(notary) return TransactionBuilder(notary)
.withItems(StateAndContract(state, ATTACHMENT_PROGRAM_ID), Command(Commands.Create(), owner.party.owningKey)) .withItems(StateAndContract(state, ATTACHMENT_PROGRAM_ID), Command(Commands.Create(), owner.party.owningKey))
} }
} }
@ -45,7 +45,7 @@ class AttachmentsClassLoaderStaticContractTests : TestDependencyInjectionBase()
@Before @Before
fun `create service hub`() { fun `create service hub`() {
serviceHub = MockServices(cordappPackages=listOf("net.corda.nodeapi.internal")) serviceHub = MockServices(cordappPackages = listOf("net.corda.nodeapi.internal"))
} }
@After @After

View File

@ -45,6 +45,7 @@ class AttachmentsClassLoaderTests : TestDependencyInjectionBase() {
whenever(serviceHub.attachments).thenReturn(attachmentStorage) whenever(serviceHub.attachments).thenReturn(attachmentStorage)
return this.withServiceHub(serviceHub) return this.withServiceHub(serviceHub)
} }
private fun SerializationContext.withServiceHub(serviceHub: ServiceHub): SerializationContext { private fun SerializationContext.withServiceHub(serviceHub: ServiceHub): SerializationContext {
return this.withTokenContext(SerializeAsTokenContextImpl(serviceHub) {}).withProperty(attachmentsClassLoaderEnabledPropertyName, true) return this.withTokenContext(SerializeAsTokenContextImpl(serviceHub) {}).withProperty(attachmentsClassLoaderEnabledPropertyName, true)
} }
@ -266,7 +267,7 @@ class AttachmentsClassLoaderTests : TestDependencyInjectionBase() {
@Test @Test
fun `test serialization of sub-sequence OpaqueBytes`() { fun `test serialization of sub-sequence OpaqueBytes`() {
val bytesSequence = ByteSequence.of("0123456789".toByteArray(), 3 ,2) val bytesSequence = ByteSequence.of("0123456789".toByteArray(), 3, 2)
val bytes = bytesSequence.serialize() val bytes = bytesSequence.serialize()
val copiedBytesSequence = bytes.deserialize() val copiedBytesSequence = bytes.deserialize()
@ -310,8 +311,8 @@ class AttachmentsClassLoaderTests : TestDependencyInjectionBase() {
val attachmentRef = serviceHub.attachmentId val attachmentRef = serviceHub.attachmentId
val bytes = run { val bytes = run {
val outboundContext = SerializationFactory.defaultFactory.defaultContext val outboundContext = SerializationFactory.defaultFactory.defaultContext
.withServiceHub(serviceHub) .withServiceHub(serviceHub)
.withClassLoader(child) .withClassLoader(child)
val wireTransaction = tx.toWireTransaction(serviceHub, outboundContext) val wireTransaction = tx.toWireTransaction(serviceHub, outboundContext)
wireTransaction.serialize(context = outboundContext) wireTransaction.serialize(context = outboundContext)
} }

View File

@ -271,6 +271,7 @@ class CordaClassResolverTests {
} }
open class SubHashSet<E> : HashSet<E>() open class SubHashSet<E> : HashSet<E>()
@Test @Test
fun `Check blacklisted subclass`() { fun `Check blacklisted subclass`() {
expectedEx.expect(IllegalStateException::class.java) expectedEx.expect(IllegalStateException::class.java)
@ -281,6 +282,7 @@ class CordaClassResolverTests {
} }
class SubSubHashSet<E> : SubHashSet<E>() class SubSubHashSet<E> : SubHashSet<E>()
@Test @Test
fun `Check blacklisted subsubclass`() { fun `Check blacklisted subsubclass`() {
expectedEx.expect(IllegalStateException::class.java) expectedEx.expect(IllegalStateException::class.java)
@ -291,6 +293,7 @@ class CordaClassResolverTests {
} }
class ConnectionImpl(private val connection: Connection) : Connection by connection class ConnectionImpl(private val connection: Connection) : Connection by connection
@Test @Test
fun `Check blacklisted interface impl`() { fun `Check blacklisted interface impl`() {
expectedEx.expect(IllegalStateException::class.java) expectedEx.expect(IllegalStateException::class.java)
@ -302,6 +305,7 @@ class CordaClassResolverTests {
interface SubConnection : Connection interface SubConnection : Connection
class SubConnectionImpl(private val subConnection: SubConnection) : SubConnection by subConnection class SubConnectionImpl(private val subConnection: SubConnection) : SubConnection by subConnection
@Test @Test
fun `Check blacklisted super-interface impl`() { fun `Check blacklisted super-interface impl`() {
expectedEx.expect(IllegalStateException::class.java) expectedEx.expect(IllegalStateException::class.java)
@ -320,6 +324,7 @@ class CordaClassResolverTests {
@CordaSerializable @CordaSerializable
class CordaSerializableHashSet<E> : HashSet<E>() class CordaSerializableHashSet<E> : HashSet<E>()
@Test @Test
fun `Check blacklist precedes CordaSerializable`() { fun `Check blacklist precedes CordaSerializable`() {
expectedEx.expect(IllegalStateException::class.java) expectedEx.expect(IllegalStateException::class.java)

View File

@ -188,10 +188,10 @@ class KryoTests : TestDependencyInjectionBase() {
@Test @Test
fun `serialize - deserialize PrivacySalt`() { fun `serialize - deserialize PrivacySalt`() {
val expected = PrivacySalt(byteArrayOf( val expected = PrivacySalt(byteArrayOf(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32 31, 32
)) ))
val serializedBytes = expected.serialize(factory, context) val serializedBytes = expected.serialize(factory, context)
val actual = serializedBytes.deserialize(factory, context) val actual = serializedBytes.deserialize(factory, context)
@ -267,7 +267,7 @@ class KryoTests : TestDependencyInjectionBase() {
assertEquals(exception.message, exception2.message) assertEquals(exception.message, exception2.message)
assertEquals(1, exception2.suppressed.size) assertEquals(1, exception2.suppressed.size)
assertNotNull({ exception2.suppressed.find { it.message == toBeSuppressedOnSenderSide.message }}) assertNotNull({ exception2.suppressed.find { it.message == toBeSuppressedOnSenderSide.message } })
val toBeSuppressedOnReceiverSide = IllegalStateException("bazz2") val toBeSuppressedOnReceiverSide = IllegalStateException("bazz2")
exception2.addSuppressed(toBeSuppressedOnReceiverSide) exception2.addSuppressed(toBeSuppressedOnReceiverSide)

View File

@ -22,12 +22,12 @@ class ListsSerializationTest : TestDependencyInjectionBase() {
private companion object { private companion object {
val javaEmptyListClass = Collections.emptyList<Any>().javaClass val javaEmptyListClass = Collections.emptyList<Any>().javaClass
fun<T : Any> verifyEnvelope(serBytes: SerializedBytes<T>, envVerBody: (Envelope) -> Unit) = fun <T : Any> verifyEnvelope(serBytes: SerializedBytes<T>, envVerBody: (Envelope) -> Unit) =
amqpSpecific("AMQP specific envelope verification") { amqpSpecific("AMQP specific envelope verification") {
val context = SerializationFactory.defaultFactory.defaultContext val context = SerializationFactory.defaultFactory.defaultContext
val envelope = DeserializationInput(SerializerFactory(context.whitelist, context.deserializationClassLoader)).getEnvelope(serBytes) val envelope = DeserializationInput(SerializerFactory(context.whitelist, context.deserializationClassLoader)).getEnvelope(serBytes)
envVerBody(envelope) envVerBody(envelope)
} }
} }
@Test @Test
@ -54,7 +54,7 @@ class ListsSerializationTest : TestDependencyInjectionBase() {
} }
@Test @Test
fun `check empty list serialises as Java emptyList`() = kryoSpecific("Kryo specific test"){ fun `check empty list serialises as Java emptyList`() = kryoSpecific("Kryo specific test") {
val nameID = 0 val nameID = 0
val serializedForm = emptyList<Int>().serialize() val serializedForm = emptyList<Int>().serialize()
val output = ByteArrayOutputStream().apply { val output = ByteArrayOutputStream().apply {
@ -86,7 +86,7 @@ class ListsSerializationTest : TestDependencyInjectionBase() {
data class Child(val value: Int) : Parent data class Child(val value: Int) : Parent
@CordaSerializable @CordaSerializable
data class CovariantContainer<out T: Parent>(val payload: List<T>) data class CovariantContainer<out T : Parent>(val payload: List<T>)
@Test @Test
fun `check covariance`() { fun `check covariance`() {
@ -99,11 +99,11 @@ class ListsSerializationTest : TestDependencyInjectionBase() {
envelope.schema.types.single { typeNotation -> typeNotation.name == java.util.List::class.java.name + "<?>" } envelope.schema.types.single { typeNotation -> typeNotation.name == java.util.List::class.java.name + "<?>" }
} }
assertEqualAfterRoundTripSerialization(container, {bytes -> verifyEnvelope(bytes, ::verifyEnvelopeBody)}) assertEqualAfterRoundTripSerialization(container, { bytes -> verifyEnvelope(bytes, ::verifyEnvelopeBody) })
} }
} }
internal inline fun<reified T : Any> assertEqualAfterRoundTripSerialization(obj: T, noinline streamValidation: ((SerializedBytes<T>) -> Unit)? = null) { internal inline fun <reified T : Any> assertEqualAfterRoundTripSerialization(obj: T, noinline streamValidation: ((SerializedBytes<T>) -> Unit)? = null) {
val serializedForm: SerializedBytes<T> = obj.serialize() val serializedForm: SerializedBytes<T> = obj.serialize()
streamValidation?.invoke(serializedForm) streamValidation?.invoke(serializedForm)

View File

@ -12,7 +12,7 @@ import org.junit.Before
import org.junit.Test import org.junit.Test
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
class SerializationTokenTest : TestDependencyInjectionBase() { class SerializationTokenTest : TestDependencyInjectionBase() {
private lateinit var factory: SerializationFactory private lateinit var factory: SerializationFactory
private lateinit var context: SerializationContext private lateinit var context: SerializationContext
@ -58,7 +58,7 @@ class SerializationTokenTest : TestDependencyInjectionBase() {
val testContext = this.context.withTokenContext(context) val testContext = this.context.withTokenContext(context)
val serializedBytes = tokenizableBefore.serialize(factory, testContext) val serializedBytes = tokenizableBefore.serialize(factory, testContext)
val tokenizableAfter = serializedBytes.deserialize(factory, testContext) val tokenizableAfter = serializedBytes.deserialize(factory, testContext)
assertThat(tokenizableAfter).isSameAs(tokenizableBefore) assertThat(tokenizableAfter).isSameAs(tokenizableBefore)
} }
@Test(expected = UnsupportedOperationException::class) @Test(expected = UnsupportedOperationException::class)
@ -92,11 +92,11 @@ class SerializationTokenTest : TestDependencyInjectionBase() {
val kryo: Kryo = DefaultKryoCustomizer.customize(CordaKryo(CordaClassResolver(this.context))) val kryo: Kryo = DefaultKryoCustomizer.customize(CordaKryo(CordaClassResolver(this.context)))
val stream = ByteArrayOutputStream() val stream = ByteArrayOutputStream()
Output(stream).use { Output(stream).use {
it.write(KryoHeaderV0_1.bytes) it.write(KryoHeaderV0_1.bytes)
kryo.writeClass(it, SingletonSerializeAsToken::class.java) kryo.writeClass(it, SingletonSerializeAsToken::class.java)
kryo.writeObject(it, emptyList<Any>()) kryo.writeObject(it, emptyList<Any>())
} }
val serializedBytes = SerializedBytes<Any>(stream.toByteArray()) val serializedBytes = SerializedBytes<Any>(stream.toByteArray())
serializedBytes.deserialize(factory, testContext) serializedBytes.deserialize(factory, testContext)
} }
@ -105,6 +105,7 @@ class SerializationTokenTest : TestDependencyInjectionBase() {
object UnitSerializationToken : SerializationToken { object UnitSerializationToken : SerializationToken {
override fun fromToken(context: SerializeAsTokenContext): Any = UnitSerializeAsToken() override fun fromToken(context: SerializeAsTokenContext): Any = UnitSerializeAsToken()
} }
override fun toToken(context: SerializeAsTokenContext): SerializationToken = UnitSerializationToken override fun toToken(context: SerializeAsTokenContext): SerializationToken = UnitSerializationToken
} }

View File

@ -17,25 +17,28 @@ class DeserializeMapTests {
@Test @Test
fun mapTest() { fun mapTest() {
data class C(val c: Map<String, Int>) data class C(val c: Map<String, Int>)
val c = C (mapOf("A" to 1, "B" to 2))
val c = C(mapOf("A" to 1, "B" to 2))
val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c) val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c)
DeserializationInput(sf).deserialize(serialisedBytes) DeserializationInput(sf).deserialize(serialisedBytes)
} }
@Test(expected=java.io.NotSerializableException::class) @Test(expected = java.io.NotSerializableException::class)
fun abstractMapFromMapOf() { fun abstractMapFromMapOf() {
data class C(val c: AbstractMap<String, Int>) data class C(val c: AbstractMap<String, Int>)
val c = C (mapOf("A" to 1, "B" to 2) as AbstractMap)
val c = C(mapOf("A" to 1, "B" to 2) as AbstractMap)
val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c) val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c)
DeserializationInput(sf).deserialize(serialisedBytes) DeserializationInput(sf).deserialize(serialisedBytes)
} }
@Test(expected=java.io.NotSerializableException::class) @Test(expected = java.io.NotSerializableException::class)
fun abstractMapFromTreeMap() { fun abstractMapFromTreeMap() {
data class C(val c: AbstractMap<String, Int>) data class C(val c: AbstractMap<String, Int>)
val c = C (TreeMap(mapOf("A" to 1, "B" to 2)))
val c = C(TreeMap(mapOf("A" to 1, "B" to 2)))
val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c) val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c)
DeserializationInput(sf).deserialize(serialisedBytes) DeserializationInput(sf).deserialize(serialisedBytes)
@ -44,7 +47,8 @@ class DeserializeMapTests {
@Test @Test
fun sortedMapTest() { fun sortedMapTest() {
data class C(val c: SortedMap<String, Int>) data class C(val c: SortedMap<String, Int>)
val c = C(sortedMapOf ("A" to 1, "B" to 2))
val c = C(sortedMapOf("A" to 1, "B" to 2))
val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c) val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c)
DeserializationInput(sf).deserialize(serialisedBytes) DeserializationInput(sf).deserialize(serialisedBytes)
} }
@ -52,7 +56,8 @@ class DeserializeMapTests {
@Test @Test
fun navigableMapTest() { fun navigableMapTest() {
data class C(val c: NavigableMap<String, Int>) data class C(val c: NavigableMap<String, Int>)
val c = C(TreeMap (mapOf("A" to 1, "B" to 2)).descendingMap())
val c = C(TreeMap(mapOf("A" to 1, "B" to 2)).descendingMap())
val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c) val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c)
DeserializationInput(sf).deserialize(serialisedBytes) DeserializationInput(sf).deserialize(serialisedBytes)
@ -61,9 +66,10 @@ class DeserializeMapTests {
@Test @Test
fun dictionaryTest() { fun dictionaryTest() {
data class C(val c: Dictionary<String, Int>) data class C(val c: Dictionary<String, Int>)
val v : Hashtable<String, Int> = Hashtable()
v.put ("a", 1) val v: Hashtable<String, Int> = Hashtable()
v.put ("b", 2) v.put("a", 1)
v.put("b", 2)
val c = C(v) val c = C(v)
// expected to throw // expected to throw
@ -74,9 +80,10 @@ class DeserializeMapTests {
@Test @Test
fun hashtableTest() { fun hashtableTest() {
data class C(val c: Hashtable<String, Int>) data class C(val c: Hashtable<String, Int>)
val v : Hashtable<String, Int> = Hashtable()
v.put ("a", 1) val v: Hashtable<String, Int> = Hashtable()
v.put ("b", 2) v.put("a", 1)
v.put("b", 2)
val c = C(v) val c = C(v)
// expected to throw // expected to throw
@ -86,8 +93,9 @@ class DeserializeMapTests {
@Test @Test
fun hashMapTest() { fun hashMapTest() {
data class C(val c : HashMap<String, Int>) data class C(val c: HashMap<String, Int>)
val c = C (HashMap (mapOf("A" to 1, "B" to 2)))
val c = C(HashMap(mapOf("A" to 1, "B" to 2)))
// expect this to throw // expect this to throw
Assertions.assertThatThrownBy { TestSerializationOutput(VERBOSE, sf).serialize(c) } Assertions.assertThatThrownBy { TestSerializationOutput(VERBOSE, sf).serialize(c) }
@ -96,8 +104,9 @@ class DeserializeMapTests {
@Test @Test
fun weakHashMapTest() { fun weakHashMapTest() {
data class C(val c : WeakHashMap<String, Int>) data class C(val c: WeakHashMap<String, Int>)
val c = C (WeakHashMap (mapOf("A" to 1, "B" to 2)))
val c = C(WeakHashMap(mapOf("A" to 1, "B" to 2)))
Assertions.assertThatThrownBy { TestSerializationOutput(VERBOSE, sf).serialize(c) } Assertions.assertThatThrownBy { TestSerializationOutput(VERBOSE, sf).serialize(c) }
.isInstanceOf(IllegalArgumentException::class.java).hasMessageContaining("Weak references with map types not supported. Suggested fix: use java.util.LinkedHashMap instead.") .isInstanceOf(IllegalArgumentException::class.java).hasMessageContaining("Weak references with map types not supported. Suggested fix: use java.util.LinkedHashMap instead.")
@ -106,7 +115,8 @@ class DeserializeMapTests {
@Test @Test
fun concreteTreeMapTest() { fun concreteTreeMapTest() {
data class C(val c: TreeMap<String, Int>) data class C(val c: TreeMap<String, Int>)
val c = C(TreeMap (mapOf("A" to 1, "B" to 3)))
val c = C(TreeMap(mapOf("A" to 1, "B" to 3)))
val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c) val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c)
DeserializationInput(sf).deserialize(serialisedBytes) DeserializationInput(sf).deserialize(serialisedBytes)
@ -114,8 +124,9 @@ class DeserializeMapTests {
@Test @Test
fun concreteLinkedHashMapTest() { fun concreteLinkedHashMapTest() {
data class C(val c : LinkedHashMap<String, Int>) data class C(val c: LinkedHashMap<String, Int>)
val c = C (LinkedHashMap (mapOf("A" to 1, "B" to 2)))
val c = C(LinkedHashMap(mapOf("A" to 1, "B" to 2)))
val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c) val serialisedBytes = TestSerializationOutput(VERBOSE, sf).serialize(c)
DeserializationInput(sf).deserialize(serialisedBytes) DeserializationInput(sf).deserialize(serialisedBytes)

View File

@ -402,7 +402,8 @@ class DeserializeSimpleTypesTests {
@Test @Test
fun arrayOfArrayOfInt() { fun arrayOfArrayOfInt() {
class C(val c: Array<Array<Int>>) class C(val c: Array<Array<Int>>)
val c = C (arrayOf (arrayOf(1,2,3), arrayOf(4,5,6)))
val c = C(arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6)))
val serialisedC = TestSerializationOutput(VERBOSE, sf1).serialize(c) val serialisedC = TestSerializationOutput(VERBOSE, sf1).serialize(c)
val deserializedC = DeserializationInput(sf1).deserialize(serialisedC) val deserializedC = DeserializationInput(sf1).deserialize(serialisedC)
@ -421,7 +422,8 @@ class DeserializeSimpleTypesTests {
@Test @Test
fun arrayOfIntArray() { fun arrayOfIntArray() {
class C(val c: Array<IntArray>) class C(val c: Array<IntArray>)
val c = C (arrayOf (IntArray(3), IntArray(3)))
val c = C(arrayOf(IntArray(3), IntArray(3)))
c.c[0][0] = 1; c.c[0][1] = 2; c.c[0][2] = 3 c.c[0][0] = 1; c.c[0][1] = 2; c.c[0][2] = 3
c.c[1][0] = 4; c.c[1][1] = 5; c.c[1][2] = 6 c.c[1][0] = 4; c.c[1][1] = 5; c.c[1][2] = 6
@ -444,22 +446,32 @@ class DeserializeSimpleTypesTests {
class C(val c: Array<Array<IntArray>>) class C(val c: Array<Array<IntArray>>)
val c = C(arrayOf(arrayOf(IntArray(3), IntArray(3), IntArray(3)), val c = C(arrayOf(arrayOf(IntArray(3), IntArray(3), IntArray(3)),
arrayOf(IntArray(3), IntArray(3), IntArray(3)), arrayOf(IntArray(3), IntArray(3), IntArray(3)),
arrayOf(IntArray(3), IntArray(3), IntArray(3)))) arrayOf(IntArray(3), IntArray(3), IntArray(3))))
for (i in 0..2) { for (j in 0..2) { for (k in 0..2) { c.c[i][j][k] = i + j + k } } } for (i in 0..2) {
for (j in 0..2) {
for (k in 0..2) {
c.c[i][j][k] = i + j + k
}
}
}
val serialisedC = TestSerializationOutput(VERBOSE, sf1).serialize(c) val serialisedC = TestSerializationOutput(VERBOSE, sf1).serialize(c)
val deserializedC = DeserializationInput(sf1).deserialize(serialisedC) val deserializedC = DeserializationInput(sf1).deserialize(serialisedC)
for (i in 0..2) { for (j in 0..2) { for (k in 0..2) { for (i in 0..2) {
assertEquals(c.c[i][j][k], deserializedC.c[i][j][k]) for (j in 0..2) {
}}} for (k in 0..2) {
assertEquals(c.c[i][j][k], deserializedC.c[i][j][k])
}
}
}
} }
@Test @Test
fun nestedRepeatedTypes() { fun nestedRepeatedTypes() {
class A(val a : A?, val b: Int) class A(val a: A?, val b: Int)
var a = A(A(A(A(A(null, 1), 2), 3), 4), 5) var a = A(A(A(A(A(null, 1), 2), 3), 4), 5)

View File

@ -49,7 +49,7 @@ class EnumTests {
} }
enum class BrasWithInit (val someList: List<Int>) { enum class BrasWithInit(val someList: List<Int>) {
TSHIRT(emptyList()), TSHIRT(emptyList()),
UNDERWIRE(listOf(1, 2, 3)), UNDERWIRE(listOf(1, 2, 3)),
PUSHUP(listOf(100, 200)), PUSHUP(listOf(100, 200)),
@ -90,7 +90,7 @@ class EnumTests {
assertEquals(8, schema_bras.choices.size) assertEquals(8, schema_bras.choices.size)
Bras.values().forEach { Bras.values().forEach {
val bra = it val bra = it
assertNotNull (schema_bras.choices.find { it.name == bra.name }) assertNotNull(schema_bras.choices.find { it.name == bra.name })
} }
} }
@ -115,7 +115,7 @@ class EnumTests {
assertEquals(8, schema_bras.choices.size) assertEquals(8, schema_bras.choices.size)
Bras.values().forEach { Bras.values().forEach {
val bra = it val bra = it
assertNotNull (schema_bras.choices.find { it.name == bra.name }) assertNotNull(schema_bras.choices.find { it.name == bra.name })
} }
// Test the actual deserialised object // Test the actual deserialised object
@ -124,13 +124,13 @@ class EnumTests {
@Test @Test
fun multiEnum() { fun multiEnum() {
data class Support (val top: Bras, val day : DayOfWeek) data class Support(val top: Bras, val day: DayOfWeek)
data class WeeklySupport (val tops: List<Support>) data class WeeklySupport(val tops: List<Support>)
val week = WeeklySupport (listOf( val week = WeeklySupport(listOf(
Support (Bras.PUSHUP, DayOfWeek.MONDAY), Support(Bras.PUSHUP, DayOfWeek.MONDAY),
Support (Bras.UNDERWIRE, DayOfWeek.WEDNESDAY), Support(Bras.UNDERWIRE, DayOfWeek.WEDNESDAY),
Support (Bras.PADDED, DayOfWeek.SUNDAY))) Support(Bras.PADDED, DayOfWeek.SUNDAY)))
val obj = DeserializationInput(sf1).deserialize(TestSerializationOutput(VERBOSE, sf1).serialize(week)) val obj = DeserializationInput(sf1).deserialize(TestSerializationOutput(VERBOSE, sf1).serialize(week))
@ -146,7 +146,7 @@ class EnumTests {
fun enumWithInit() { fun enumWithInit() {
data class C(val c: BrasWithInit) data class C(val c: BrasWithInit)
val c = C (BrasWithInit.PUSHUP) val c = C(BrasWithInit.PUSHUP)
val obj = DeserializationInput(sf1).deserialize(TestSerializationOutput(VERBOSE, sf1).serialize(c)) val obj = DeserializationInput(sf1).deserialize(TestSerializationOutput(VERBOSE, sf1).serialize(c))
assertEquals(c.c, obj.c) assertEquals(c.c, obj.c)
@ -157,7 +157,7 @@ class EnumTests {
val path = EnumTests::class.java.getResource("EnumTests.changedEnum1") val path = EnumTests::class.java.getResource("EnumTests.changedEnum1")
val f = File(path.toURI()) val f = File(path.toURI())
data class C (val a: OldBras) data class C(val a: OldBras)
// Original version of the class for the serialised version of this class // Original version of the class for the serialised version of this class
// //
@ -177,7 +177,7 @@ class EnumTests {
val path = EnumTests::class.java.getResource("EnumTests.changedEnum2") val path = EnumTests::class.java.getResource("EnumTests.changedEnum2")
val f = File(path.toURI()) val f = File(path.toURI())
data class C (val a: OldBras2) data class C(val a: OldBras2)
// DO NOT CHANGE THIS, it's important we serialise with a value that doesn't // DO NOT CHANGE THIS, it's important we serialise with a value that doesn't
// change position in the upated enum class // change position in the upated enum class
@ -197,9 +197,9 @@ class EnumTests {
@Test @Test
fun enumNotWhitelistedFails() { fun enumNotWhitelistedFails() {
data class C (val c: Bras) data class C(val c: Bras)
class WL (val allowed: String): ClassWhitelist { class WL(val allowed: String) : ClassWhitelist {
override fun hasListed(type: Class<*>): Boolean { override fun hasListed(type: Class<*>): Boolean {
return type.name == allowed return type.name == allowed
} }
@ -214,7 +214,7 @@ class EnumTests {
@Test @Test
fun enumWhitelisted() { fun enumWhitelisted() {
data class C (val c: Bras) data class C(val c: Bras)
class WL : ClassWhitelist { class WL : ClassWhitelist {
override fun hasListed(type: Class<*>): Boolean { override fun hasListed(type: Class<*>): Boolean {
@ -231,7 +231,7 @@ class EnumTests {
@Test @Test
fun enumAnnotated() { fun enumAnnotated() {
@CordaSerializable data class C (val c: AnnotatedBras) @CordaSerializable data class C(val c: AnnotatedBras)
class WL : ClassWhitelist { class WL : ClassWhitelist {
override fun hasListed(type: Class<*>) = false override fun hasListed(type: Class<*>) = false
@ -245,21 +245,21 @@ class EnumTests {
@Test @Test
fun deserializeNonWhitlistedEnum() { fun deserializeNonWhitlistedEnum() {
data class C (val c: Bras) data class C(val c: Bras)
class WL (val allowed: List<String>) : ClassWhitelist { class WL(val allowed: List<String>) : ClassWhitelist {
override fun hasListed(type: Class<*>) = type.name in allowed override fun hasListed(type: Class<*>) = type.name in allowed
} }
// first serialise the class using a context in which Bras are whitelisted // first serialise the class using a context in which Bras are whitelisted
val factory = SerializerFactory(WL(listOf (classTestName("C"), val factory = SerializerFactory(WL(listOf(classTestName("C"),
"net.corda.nodeapi.internal.serialization.amqp.EnumTests\$Bras")), "net.corda.nodeapi.internal.serialization.amqp.EnumTests\$Bras")),
ClassLoader.getSystemClassLoader()) ClassLoader.getSystemClassLoader())
val bytes = TestSerializationOutput(VERBOSE, factory).serialize(C(Bras.UNDERWIRE)) val bytes = TestSerializationOutput(VERBOSE, factory).serialize(C(Bras.UNDERWIRE))
// then take that serialised object and attempt to deserialize it in a context that // then take that serialised object and attempt to deserialize it in a context that
// disallows the Bras enum // disallows the Bras enum
val factory2 = SerializerFactory(WL(listOf (classTestName("C"))), ClassLoader.getSystemClassLoader()) val factory2 = SerializerFactory(WL(listOf(classTestName("C"))), ClassLoader.getSystemClassLoader())
Assertions.assertThatThrownBy { Assertions.assertThatThrownBy {
DeserializationInput(factory2).deserialize(bytes) DeserializationInput(factory2).deserialize(bytes)
}.isInstanceOf(NotSerializableException::class.java) }.isInstanceOf(NotSerializableException::class.java)

View File

@ -32,7 +32,7 @@ class EvolvabilityTests {
// f.writeBytes(sc.bytes) // f.writeBytes(sc.bytes)
// new version of the class, in this case the order of the parameters has been swapped // new version of the class, in this case the order of the parameters has been swapped
data class C (val b: Int, val a: Int) data class C(val b: Int, val a: Int)
val sc2 = f.readBytes() val sc2 = f.readBytes()
val deserializedC = DeserializationInput(sf).deserialize(SerializedBytes<C>(sc2)) val deserializedC = DeserializationInput(sf).deserialize(SerializedBytes<C>(sc2))
@ -56,7 +56,7 @@ class EvolvabilityTests {
// f.writeBytes(sc.bytes) // f.writeBytes(sc.bytes)
// new version of the class, in this case the order of the parameters has been swapped // new version of the class, in this case the order of the parameters has been swapped
data class C (val b: String, val a: Int) data class C(val b: String, val a: Int)
val sc2 = f.readBytes() val sc2 = f.readBytes()
val deserializedC = DeserializationInput(sf).deserialize(SerializedBytes<C>(sc2)) val deserializedC = DeserializationInput(sf).deserialize(SerializedBytes<C>(sc2))
@ -79,13 +79,13 @@ class EvolvabilityTests {
// f.writeBytes(sc.bytes) // f.writeBytes(sc.bytes)
// println ("Path = $path") // println ("Path = $path")
data class C (val a: Int, val b: Int?) data class C(val a: Int, val b: Int?)
val sc2 = f.readBytes() val sc2 = f.readBytes()
val deserializedC = DeserializationInput(sf).deserialize(SerializedBytes<C>(sc2)) val deserializedC = DeserializationInput(sf).deserialize(SerializedBytes<C>(sc2))
assertEquals (A, deserializedC.a) assertEquals(A, deserializedC.a)
assertEquals (null, deserializedC.b) assertEquals(null, deserializedC.b)
} }
@Test(expected = NotSerializableException::class) @Test(expected = NotSerializableException::class)
@ -104,7 +104,7 @@ class EvolvabilityTests {
// println ("Path = $path") // println ("Path = $path")
// new version of the class, in this case a new parameter has been added (b) // new version of the class, in this case a new parameter has been added (b)
data class C (val a: Int, val b: Int) data class C(val a: Int, val b: Int)
val sc2 = f.readBytes() val sc2 = f.readBytes()
@ -132,13 +132,13 @@ class EvolvabilityTests {
// f.writeBytes(scc.bytes) // f.writeBytes(scc.bytes)
// println ("Path = $path") // println ("Path = $path")
data class CC (val b: String, val d: Int) data class CC(val b: String, val d: Int)
val sc2 = f.readBytes() val sc2 = f.readBytes()
val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2)) val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2))
assertEquals (B, deserializedCC.b) assertEquals(B, deserializedCC.b)
assertEquals (D, deserializedCC.d) assertEquals(D, deserializedCC.d)
} }
@Suppress("UNUSED_VARIABLE") @Suppress("UNUSED_VARIABLE")
@ -185,16 +185,16 @@ class EvolvabilityTests {
// println ("Path = $path") // println ("Path = $path")
@Suppress("UNUSED") @Suppress("UNUSED")
data class CC (val a: Int, val b: String) { data class CC(val a: Int, val b: String) {
@DeprecatedConstructorForDeserialization(1) @DeprecatedConstructorForDeserialization(1)
constructor (a: Int) : this (a, "hello") constructor (a: Int) : this(a, "hello")
} }
val sc2 = f.readBytes() val sc2 = f.readBytes()
val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2)) val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2))
assertEquals (A, deserializedCC.a) assertEquals(A, deserializedCC.a)
assertEquals ("hello", deserializedCC.b) assertEquals("hello", deserializedCC.b)
} }
@Test(expected = NotSerializableException::class) @Test(expected = NotSerializableException::class)
@ -214,9 +214,9 @@ class EvolvabilityTests {
// f.writeBytes(scc.bytes) // f.writeBytes(scc.bytes)
// println ("Path = $path") // println ("Path = $path")
data class CC (val a: Int, val b: String) { data class CC(val a: Int, val b: String) {
// constructor annotation purposefully omitted // constructor annotation purposefully omitted
constructor (a: Int) : this (a, "hello") constructor (a: Int) : this(a, "hello")
} }
// we expect this to throw as we should not find any constructors // we expect this to throw as we should not find any constructors
@ -242,20 +242,20 @@ class EvolvabilityTests {
// println ("Path = $path") // println ("Path = $path")
@Suppress("UNUSED") @Suppress("UNUSED")
data class CC (val a: Int, val b: Int, val c: String, val d: String) { data class CC(val a: Int, val b: Int, val c: String, val d: String) {
// ensure none of the original parameters align with the initial // ensure none of the original parameters align with the initial
// construction order // construction order
@DeprecatedConstructorForDeserialization(1) @DeprecatedConstructorForDeserialization(1)
constructor (c: String, a: Int, b: Int) : this (a, b, c, "wibble") constructor (c: String, a: Int, b: Int) : this(a, b, c, "wibble")
} }
val sc2 = f.readBytes() val sc2 = f.readBytes()
val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2)) val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2))
assertEquals (A, deserializedCC.a) assertEquals(A, deserializedCC.a)
assertEquals (B, deserializedCC.b) assertEquals(B, deserializedCC.b)
assertEquals (C, deserializedCC.c) assertEquals(C, deserializedCC.c)
assertEquals ("wibble", deserializedCC.d) assertEquals("wibble", deserializedCC.d)
} }
@Test @Test
@ -277,20 +277,20 @@ class EvolvabilityTests {
// println ("Path = $path") // println ("Path = $path")
// b is removed, d is added // b is removed, d is added
data class CC (val a: Int, val c: String, val d: String) { data class CC(val a: Int, val c: String, val d: String) {
// ensure none of the original parameters align with the initial // ensure none of the original parameters align with the initial
// construction order // construction order
@Suppress("UNUSED") @Suppress("UNUSED")
@DeprecatedConstructorForDeserialization(1) @DeprecatedConstructorForDeserialization(1)
constructor (c: String, a: Int) : this (a, c, "wibble") constructor (c: String, a: Int) : this(a, c, "wibble")
} }
val sc2 = f.readBytes() val sc2 = f.readBytes()
val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2)) val deserializedCC = DeserializationInput(sf).deserialize(SerializedBytes<CC>(sc2))
assertEquals (A, deserializedCC.a) assertEquals(A, deserializedCC.a)
assertEquals (C, deserializedCC.c) assertEquals(C, deserializedCC.c)
assertEquals ("wibble", deserializedCC.d) assertEquals("wibble", deserializedCC.d)
} }
@Test @Test
@ -322,13 +322,15 @@ class EvolvabilityTests {
// println ("Path = $path1") // println ("Path = $path1")
@Suppress("UNUSED") @Suppress("UNUSED")
data class C (val e: Int, val c: Int, val b: Int, val a: Int, val d: Int) { data class C(val e: Int, val c: Int, val b: Int, val a: Int, val d: Int) {
@DeprecatedConstructorForDeserialization(1) @DeprecatedConstructorForDeserialization(1)
constructor (b: Int, a: Int) : this (-1, -1, b, a, -1) constructor (b: Int, a: Int) : this(-1, -1, b, a, -1)
@DeprecatedConstructorForDeserialization(2) @DeprecatedConstructorForDeserialization(2)
constructor (a: Int, c: Int, b: Int) : this (-1, c, b, a, -1) constructor (a: Int, c: Int, b: Int) : this(-1, c, b, a, -1)
@DeprecatedConstructorForDeserialization(3) @DeprecatedConstructorForDeserialization(3)
constructor (a: Int, b: Int, c: Int, d: Int) : this (-1, c, b, a, d) constructor (a: Int, b: Int, c: Int, d: Int) : this(-1, c, b, a, d)
} }
val sb1 = File(path1.toURI()).readBytes() val sb1 = File(path1.toURI()).readBytes()
@ -376,15 +378,16 @@ class EvolvabilityTests {
// println ("Path = $path") // println ("Path = $path")
// Add a parameter to inner but keep outer unchanged // Add a parameter to inner but keep outer unchanged
data class Inner (val a: Int, val b: String?) data class Inner(val a: Int, val b: String?)
data class Outer (val a: Int, val b: Inner)
data class Outer(val a: Int, val b: Inner)
val sc2 = f.readBytes() val sc2 = f.readBytes()
val outer = DeserializationInput(sf).deserialize(SerializedBytes<Outer>(sc2)) val outer = DeserializationInput(sf).deserialize(SerializedBytes<Outer>(sc2))
assertEquals (oa, outer.a) assertEquals(oa, outer.a)
assertEquals (ia, outer.b.a) assertEquals(ia, outer.b.a)
assertEquals (null, outer.b.b) assertEquals(null, outer.b.b)
} }
@Test @Test
@ -416,15 +419,18 @@ class EvolvabilityTests {
// println ("Path = $path1") // println ("Path = $path1")
@Suppress("UNUSED") @Suppress("UNUSED")
data class C (val b: Int, val c: Int, val d: Int, val e: Int, val f: Int, val g: Int) { data class C(val b: Int, val c: Int, val d: Int, val e: Int, val f: Int, val g: Int) {
@DeprecatedConstructorForDeserialization(1) @DeprecatedConstructorForDeserialization(1)
constructor (b: Int, c: Int) : this (b, c, -1, -1, -1, -1) constructor (b: Int, c: Int) : this(b, c, -1, -1, -1, -1)
@DeprecatedConstructorForDeserialization(2) @DeprecatedConstructorForDeserialization(2)
constructor (b: Int, c: Int, d: Int) : this (b, c, d, -1, -1, -1) constructor (b: Int, c: Int, d: Int) : this(b, c, d, -1, -1, -1)
@DeprecatedConstructorForDeserialization(3) @DeprecatedConstructorForDeserialization(3)
constructor (b: Int, c: Int, d: Int, e: Int) : this (b, c, d, e, -1, -1) constructor (b: Int, c: Int, d: Int, e: Int) : this(b, c, d, e, -1, -1)
@DeprecatedConstructorForDeserialization(4) @DeprecatedConstructorForDeserialization(4)
constructor (b: Int, c: Int, d: Int, e: Int, f: Int) : this (b, c, d, e, f, -1) constructor (b: Int, c: Int, d: Int, e: Int, f: Int) : this(b, c, d, e, f, -1)
} }
val sb1 = File(path1.toURI()).readBytes() val sb1 = File(path1.toURI()).readBytes()

View File

@ -50,7 +50,7 @@ class SerializationOutputTests {
data class testShort(val s: Short) data class testShort(val s: Short)
data class testBoolean(val b : Boolean) data class testBoolean(val b: Boolean)
interface FooInterface { interface FooInterface {
val pub: Int val pub: Int
@ -145,13 +145,13 @@ class SerializationOutputTests {
data class PolymorphicProperty(val foo: FooInterface?) data class PolymorphicProperty(val foo: FooInterface?)
private inline fun<reified T : Any> serdes(obj: T, private inline fun <reified T : Any> serdes(obj: T,
factory: SerializerFactory = SerializerFactory ( factory: SerializerFactory = SerializerFactory(
AllWhitelist, ClassLoader.getSystemClassLoader()), AllWhitelist, ClassLoader.getSystemClassLoader()),
freshDeserializationFactory: SerializerFactory = SerializerFactory( freshDeserializationFactory: SerializerFactory = SerializerFactory(
AllWhitelist, ClassLoader.getSystemClassLoader()), AllWhitelist, ClassLoader.getSystemClassLoader()),
expectedEqual: Boolean = true, expectedEqual: Boolean = true,
expectDeserializedEqual: Boolean = true): T { expectDeserializedEqual: Boolean = true): T {
val ser = SerializationOutput(factory) val ser = SerializationOutput(factory)
val bytes = ser.serialize(obj) val bytes = ser.serialize(obj)
@ -446,10 +446,10 @@ class SerializationOutputTests {
try { try {
try { try {
throw IOException("Layer 1") throw IOException("Layer 1")
} catch(t: Throwable) { } catch (t: Throwable) {
throw IllegalStateException("Layer 2", t) throw IllegalStateException("Layer 2", t)
} }
} catch(t: Throwable) { } catch (t: Throwable) {
val desThrowable = serdesThrowableWithInternalInfo(t, factory, factory2, false) val desThrowable = serdesThrowableWithInternalInfo(t, factory, factory2, false)
assertSerializedThrowableEquivalent(t, desThrowable) assertSerializedThrowableEquivalent(t, desThrowable)
} }
@ -476,12 +476,12 @@ class SerializationOutputTests {
try { try {
try { try {
throw IOException("Layer 1") throw IOException("Layer 1")
} catch(t: Throwable) { } catch (t: Throwable) {
val e = IllegalStateException("Layer 2") val e = IllegalStateException("Layer 2")
e.addSuppressed(t) e.addSuppressed(t)
throw e throw e
} }
} catch(t: Throwable) { } catch (t: Throwable) {
val desThrowable = serdesThrowableWithInternalInfo(t, factory, factory2, false) val desThrowable = serdesThrowableWithInternalInfo(t, factory, factory2, false)
assertSerializedThrowableEquivalent(t, desThrowable) assertSerializedThrowableEquivalent(t, desThrowable)
} }
@ -535,6 +535,7 @@ class SerializationOutputTests {
} }
val FOO_PROGRAM_ID = "net.corda.nodeapi.internal.serialization.amqp.SerializationOutputTests.FooContract" val FOO_PROGRAM_ID = "net.corda.nodeapi.internal.serialization.amqp.SerializationOutputTests.FooContract"
class FooState : ContractState { class FooState : ContractState {
override val participants: List<AbstractParty> = emptyList() override val participants: List<AbstractParty> = emptyList()
} }

View File

@ -19,6 +19,7 @@ class SerializeAndReturnSchemaTest {
@Test @Test
fun getSchema() { fun getSchema() {
data class C(val a: Int, val b: Int) data class C(val a: Int, val b: Int)
val a = 1 val a = 1
val b = 2 val b = 2

View File

@ -12,7 +12,7 @@ import java.lang.reflect.Type
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import kotlin.test.assertEquals import kotlin.test.assertEquals
class InStatic : Exception ("Help!, help!, I'm being repressed") class InStatic : Exception("Help!, help!, I'm being repressed")
class C { class C {
companion object { companion object {
@ -28,7 +28,7 @@ class C {
// comment out the companion object from here, comment out the test code and uncomment // comment out the companion object from here, comment out the test code and uncomment
// the generation code, then re-run the test and copy the file shown in the output print // the generation code, then re-run the test and copy the file shown in the output print
// to the resource directory // to the resource directory
class C2 (var b: Int) { class C2(var b: Int) {
/* /*
companion object { companion object {
init { init {
@ -39,14 +39,14 @@ class C2 (var b: Int) {
} }
class StaticInitialisationOfSerializedObjectTest { class StaticInitialisationOfSerializedObjectTest {
@Test(expected=java.lang.ExceptionInInitializerError::class) @Test(expected = java.lang.ExceptionInInitializerError::class)
fun itBlowsUp() { fun itBlowsUp() {
C() C()
} }
@Test @Test
fun KotlinObjectWithCompanionObject() { fun KotlinObjectWithCompanionObject() {
data class D (val c : C) data class D(val c: C)
val sf = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader()) val sf = SerializerFactory(AllWhitelist, ClassLoader.getSystemClassLoader())
@ -71,7 +71,7 @@ class StaticInitialisationOfSerializedObjectTest {
@Test @Test
fun deserializeTest() { fun deserializeTest() {
data class D (val c : C2) data class D(val c: C2)
val path = EvolvabilityTests::class.java.getResource("StaticInitialisationOfSerializedObjectTest.deserializeTest") val path = EvolvabilityTests::class.java.getResource("StaticInitialisationOfSerializedObjectTest.deserializeTest")
val f = File(path.toURI()) val f = File(path.toURI())
@ -86,7 +86,7 @@ class StaticInitialisationOfSerializedObjectTest {
class WL : ClassWhitelist { class WL : ClassWhitelist {
override fun hasListed(type: Class<*>) = override fun hasListed(type: Class<*>) =
type.name == "net.corda.nodeapi.internal.serialization.amqp" + type.name == "net.corda.nodeapi.internal.serialization.amqp" +
".StaticInitialisationOfSerializedObjectTest\$deserializeTest\$D" ".StaticInitialisationOfSerializedObjectTest\$deserializeTest\$D"
} }
val sf2 = SerializerFactory(WL(), ClassLoader.getSystemClassLoader()) val sf2 = SerializerFactory(WL(), ClassLoader.getSystemClassLoader())
@ -100,14 +100,14 @@ class StaticInitialisationOfSerializedObjectTest {
// Version of a serializer factory that will allow the class carpenter living on the // 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 // factory to have a different whitelist applied to it than the factory
class TestSerializerFactory(wl1: ClassWhitelist, wl2: ClassWhitelist) : class TestSerializerFactory(wl1: ClassWhitelist, wl2: ClassWhitelist) :
SerializerFactory (wl1, ClassLoader.getSystemClassLoader()) { SerializerFactory(wl1, ClassLoader.getSystemClassLoader()) {
override val classCarpenter = ClassCarpenter(ClassLoader.getSystemClassLoader(), wl2) override val classCarpenter = ClassCarpenter(ClassLoader.getSystemClassLoader(), wl2)
} }
// This time have the serilization factory and the carpenter use different whitelists // This time have the serilization factory and the carpenter use different whitelists
@Test @Test
fun deserializeTest2() { fun deserializeTest2() {
data class D (val c : C2) data class D(val c: C2)
val path = EvolvabilityTests::class.java.getResource("StaticInitialisationOfSerializedObjectTest.deserializeTest2") val path = EvolvabilityTests::class.java.getResource("StaticInitialisationOfSerializedObjectTest.deserializeTest2")
val f = File(path.toURI()) val f = File(path.toURI())