variable of type kotlin.collections.List becomes java.util.Arraylist and causes error - kotlin

I am trying to create an application with the walt.id API where I get an error stating the variable is expected to be of type kotlin.collections.List<kotlin.String> but it is of type java.util.ArrayList even though the variable is of the right type:
#Json(name = "#context")
var context: List<String>? = listOf("https://www.w3.org/2018/credentials/v1"),
I'm wondering if this is a Kotlin issue or a Walt.id Api issue since its implementation is unavailable.
The variable is part of a model that gets passed into a method that transforms the object:
package model
import com.beust.klaxon.Json
import id.walt.vclib.model.*
import id.walt.vclib.registry.VerifiableCredentialMetadata
import java.time.LocalDate
data class EHIC(
#Json(name = "#context")
var context: List<String>? = listOf("https://www.w3.org/2018/credentials/v1"),
...
When I try to call that method that transforms the implementation of the EHIC object, I get the following error:
Exception in thread "main" com.beust.klaxon.KlaxonException: Unable to instantiate VerifiableAttestation:
Parameter context: expected kotlin.collections.List<kotlin.String> but received java.util.ArrayList (value: [https://www.w3.org/2018/credentials/v1])
No argument provided for a required parameter: parameter #1 id of fun `<init>`(kotlin.collections.List<kotlin.String>, kotlin.String?, kotlin.String?, kotlin.String?, kotlin.String?, kotlin.String?, id.walt.vclib.credentials.VerifiableAttestation.VerifiableAttestationSubject?, id.walt.vclib.model.CredentialStatus?, id.walt.vclib.model.CredentialSchema?, kotlin.collections.List<id.walt.vclib.credentials.VerifiableAttestation.Evidence>?, id.walt.vclib.model.Proof?): id.walt.vclib.credentials.VerifiableAttestation
No argument provided for a required parameter: parameter #1 id of fun `<init>`(kotlin.collections.List<kotlin.String>, kotlin.String?, kotlin.String?, kotlin.String?, kotlin.String?, kotlin.String?, id.walt.vclib.credentials.VerifiableAttestation.VerifiableAttestationSubject?, id.walt.vclib.model.CredentialStatus?, id.walt.vclib.model.CredentialSchema?, kotlin.collections.List<id.walt.vclib.credentials.VerifiableAttestation.Evidence>?, id.walt.vclib.model.Proof?): id.walt.vclib.credentials.VerifiableAttestation
No argument provided for a required parameter: parameter #1 id of fun `<init>`(kotlin.collections.List<kotlin.String>, kotlin.String?, kotlin.String?, kotlin.String?, kotlin.String?, kotlin.String?, id.walt.vclib.credentials.VerifiableAttestation.VerifiableAttestationSubject?, id.walt.vclib.model.CredentialStatus?, id.walt.vclib.model.CredentialSchema?, kotlin.collections.List<id.walt.vclib.credentials.VerifiableAttestation.Evidence>?, id.walt.vclib.model.Proof?): id.walt.vclib.credentials.VerifiableAttestation
at com.beust.klaxon.JsonObjectConverter.initIntoUserClass(JsonObjectConverter.kt:115)
at com.beust.klaxon.JsonObjectConverter.fromJson(JsonObjectConverter.kt:30)
at com.beust.klaxon.DefaultConverter.fromJsonObject(DefaultConverter.kt:223)
at com.beust.klaxon.DefaultConverter.fromJson(DefaultConverter.kt:40)
at com.beust.klaxon.Klaxon.fromJsonObject(Klaxon.kt:296)
at id.walt.vclib.model.VerifiableCredential$Companion.fromString(VerifiableCredential.kt:219)
at id.walt.vclib.model.VerifiableCredentialKt.toCredential(VerifiableCredential.kt:198)
at ebsi.IssuerKt.issueCredentials(Issuer.kt:138)
at ebsi.IssuerKt.credentials(Issuer.kt:34)
at ebsi.IssuerKt.main(Issuer.kt:25)
at ebsi.IssuerKt.main(Issuer.kt)
Process finished with exit code 1
I have also tried to write the variable as:
#Json(name = "#context") var context: kotlin.collections.List<kotlin.String> = listOf("https://www.w3.org/2018/credentials/v1"),
But it still throws the same error.
I apologize for my bad english and for being vague, I'm very exhausted and in need of sleep. Help is much appreciated, thank you.
Some additional photos that might help:

I think you should do the opposite,
#Json(name = "#context")
var context: ArrayList<String>? = arrayListOf("https://www.w3.org/2018/credentials/v1")

Related

MapStruct Property has no write accessor in MetaData for target name

I have a FlatDTO that needs to be mapped to a nested Response containing InfoData and MetaData
The code for the response is generated by OpenAPI. So the below definitions can't be changed.
package org.mapstruct.example.kotlin.openapi
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.Valid
data class Response(
#field:Valid #field:JsonProperty("infoData", required = true) val infoData: InfoData,
#field:Valid #field:JsonProperty("metaData", required = true) val metaData: MetaData
)
data class InfoData(
#field:JsonProperty("id", required = true) val id: kotlin.String,
)
data class MetaData(
#field:JsonProperty("firstProperty") val firstProperty: String? = null,
)
I have defined FlatDTO as follows.
package org.mapstruct.example.kotlin.models
data class FlatDTO(
var id: String? = null,
var firstProperty: String,
)
Here is my mapper class which maps FlatDTO to Response
package org.mapstruct.example.kotlin.mapper
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.Mappings
import org.mapstruct.example.kotlin.models.FlatDTO
import org.mapstruct.example.kotlin.openapi.Response
#Mapper
interface DataMapper {
#Mappings(
Mapping(target = "infoData.id", source = "id"),
Mapping(target = "metaData.firstProperty", source = "firstProperty")
)
fun flatToResponse(flatDTO: FlatDTO): Response
}
When I try to build the code using mvn clean install
I get the following error.
error: Property "firstProperty" has no write accessor in MetaData for target name "metaData.firstProperty".
[ERROR] #org.mapstruct.Mappings(value = {#org.mapstruct.Mapping(target = "infoData.id", source = "id"), #org.mapstruct.Mapping(target = "metaData.firstProperty", source = "firstProperty")})
I understand that this message is trying to say that there is no setter function for firstProperty because it's defined as val but that code cannot be edited. I can write my own custom mapper that works just fine.
I wanted to understand if there is a way to use MapStruct in this scenario.

Kotlin and SimpleXML - Unable to satisfy ElementList Error

I'm struggling to get simpleXML and Kotlin to read a XML file properly.
I've got the following Root class:
class ServerConfiguration {
#field:Root(strict = false, name = "serverConfiguration")
#field:ElementList(required = true, name = "channels", entry = "channel", inline = true, type=Channel::class)
lateinit var channels: List<Channel>
#field:Element(name = "serverSettings", required = true, type = ServerSettings::class)
lateinit var serverSettings: ServerSettings
}
(The Channel class itself has also Lists, but even if I leave it with simple Attributes (ie Strings), it won't work.)
The XML contains:
<serverConfiguration version="3.5.2">
<date>2022-07-12 10:57:47</date>
<channelGroups>
[... lots of groups]
</channelGroups>
<channels>
<channel version="3.5.2">
<id>b7cb6bf9-d3a5-4a74-8399-b6689d915a15</id>
<nextMetaDataId>6</nextMetaDataId>
<name>cANACR_1_Fhir2Hl7Omg</name>
<connector class="[...].TcpReceiverProperties" version="3.5.2">
[... more ]
</channel>
[... a lot of channels]
</channels>
[... even more data]
</serverConfiguration>
Since there are multiple Tags in the xml that contain a "class" Attribute, I understand that I need to use inline = true in my #field:ElementList
I got through a lot of errors up until this point which I could resolve by myself but this one eludes me.
I run the Serializer via:
val serializer: Serializer = Persister()
val dataFetch = serializer.read(ServerConfiguration::class.java, myFile!!, false)
The Error (I cut out classpaths):
org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy #org.simpleframework.xml.ElementList(entry="channel", data=false, inline=true, name="channels", type=Channel.class, required=true, empty=true) on field 'channels' private java.util.List ServerConfiguration.channels for class ServerConfiguration at line 1
If anyone could nudge me in the right direction, I'd be very grateful.
Addendum:
If I set required=false the program runs, but not a single channel is read.
I've tried ArrayList, List, and Set as datatype
I've tried to circumvent lateinit with var channels: List<Channel> = mutableListOf()
I've got it working through adding a wrapper class for the nested lists:
ServerConfiguration.kt:
[...]
#field:Element(name="channels", required = true, type=ChannelList::class)
lateinit var channelList: ChannelList
ChannelList.kt:
class ChannelList {
#field:ElementList(required = true, inline = true,name = "channels", entry = "channel", type=Channel::class, data = true, empty=false)
var channels: List<Channel> = mutableListOf()
}
And finally Channel.kt:
class Channel {
#field:Element(name = "destinationConnectors", required = true, type = DestinationConnectorList::class)
lateinit var destinationConnectorList: DestinationConnectorList
#field:Element(name = "exportData", required = true, type=ExportData::class)
lateinit var exportData: ExportData
[...]
While this is working, I would have expected simpleXML to be able to add the Elements of the List directly without needing to use a wrapper class (ChannelList).
If anyone knows how to achieve this, please feel free to comment or add your solution.
Kind regards,
K

Make Pydantic chuck error for wrong argument names

Suppose I have the following class:
class ModelConfig(pydantic.BaseModel):
name: str = "bert"
If I were to instantiate it with model_config = ModelConfig(name2="hello"), this simply ignores that there is no name2 and just keeps name="bert". Is there a way to raise an error saying unknown argument in pydantic?
You can do this using the forbid Model Config
For example:
class ModelConfig(pydantic.BaseModel, extra=pydantic.Extra.forbid):
name: str = "bert"
Passing model_config = ModelConfig(name2="hello") will throw an error

ActiveJob::SerializationError: Unsupported argument type: Date/Class

I am getting a weird error while passing class and date to an ActiveJob with the Sidekiq adapter.
1] pry(main)> StripeTransactionsSyncJob.perform_later(Stripe::SyncCharges, nil, 3.days.ago.to_date)
ActiveJob::SerializationError: Unsupported argument type: Class
from /home/amit/.rvm/gems/ruby-2.5.8#immosite/gems/activejob-5.0.7.2/lib/active_job/arguments.rb:83:in `serialize_argument'
[2] pry(main)> StripeTransactionsSyncJob.perform_later('Stripe::SyncCharges', nil, 3.days.ago.to_date)
ActiveJob::SerializationError: Unsupported argument type: Date
from /home/amit/.rvm/gems/ruby-2.5.8#immosite/gems/activejob-5.0.7.2/lib/active_job/arguments.rb:83:in `serialize_argument'
As per the doc, ActiveJob should support both types of arguments out of the box. What is wrong here?
The guide you have referenced in your post refers to the v6.1.4 of Rails. See the version info on top-right corner on that page.
The guide for v5.0 doesn't explicitly specify about the arguments types supported. And looking at the source code (see below) for the version of Rails you are using i.e 5.0.7.2
def serialize_argument(argument)
case argument
when *TYPE_WHITELIST
argument
when GlobalID::Identification
convert_to_global_id_hash(argument)
when Array
argument.map { |arg| serialize_argument(arg) }
when ActiveSupport::HashWithIndifferentAccess
result = serialize_hash(argument)
result[WITH_INDIFFERENT_ACCESS_KEY] = serialize_argument(true)
result
when Hash
symbol_keys = argument.each_key.grep(Symbol).map(&:to_s)
result = serialize_hash(argument)
result[SYMBOL_KEYS_KEY] = symbol_keys
result
else
raise SerializationError.new("Unsupported argument type: #{argument.class.name}")
end
end
your passed argument types Class and Date are not supported and hence you are getting SerializationError.
Note: Whenever referring to the API-docs or Guide I would recommend to view them for the specific version of Rails you are using.
The Class/Date/DateTime/Time etc were not supported in Rails 5.0. So I need to use String form of data being passed to the Job.
For reference, here is the method(simplified) that does deserialization
def serialize_argument(argument)
case argument
when *[ NilClass, String, Integer, Float, BigDecimal, TrueClass, FalseClass ]
argument
when GlobalID::Identification
convert_to_global_id_hash(argument)
when Array
argument.map { |arg| serialize_argument(arg) }
when ActiveSupport::HashWithIndifferentAccess
result = serialize_hash(argument)
result[WITH_INDIFFERENT_ACCESS_KEY] = serialize_argument(true)
result
when Hash
symbol_keys = argument.each_key.grep(Symbol).map(&:to_s)
result = serialize_hash(argument)
result[SYMBOL_KEYS_KEY] = symbol_keys
result
else
raise SerializationError.new("Unsupported argument type: #{argument.class.name}")
end
end

Klint and spotless: com.pinterest.ktlint.core.ParseException: Expecting a parameter declaration

I'm getting weird exception when trying to run ./gradlew spotlessApply on my project in Kotlin.
Class causing the problem:
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class CurrentFluttering(
#PrimaryKey var id: Long = 0,
var currentCoinsHeap: Int = 0,
var currentEarnedCoins: Int = 0,
var startTime: Long = 0,
var pauseTime: Long = 0,
var time: Long = 0,
var firstCycle: Boolean = true,
var inBackground: Boolean = false,
var currentMissedCoins: Int = 0,
var isPaused: Boolean = false,
) : RealmObject()
Stack trace:
> Task :spotlessKotlin FAILED
Step 'ktlint' found problem in 'app/src/main/java/com/cfhero/android/model/state/CurrentFluttering.kt':
Expecting a parameter declaration
com.pinterest.ktlint.core.ParseException: Expecting a parameter declaration
at com.pinterest.ktlint.core.KtLint.format(KtLint.kt:357)
at sun.reflect.GeneratedMethodAccessor35.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.diffplug.spotless.kotlin.KtLintStep$State.lambda$createFormat$1(KtLintStep.java:173)
at com.diffplug.spotless.FormatterFunc.apply(FormatterFunc.java:31)
at com.diffplug.spotless.FormatterStepImpl$Standard.format(FormatterStepImpl.java:78)
at com.diffplug.spotless.FormatterStep$Strict.format(FormatterStep.java:76)
at com.diffplug.spotless.Formatter.compute(Formatter.java:230)
at com.diffplug.spotless.Formatter.applyToAndReturnResultIfDirty(Formatter.java:192)
at com.di
Have anybody experienced same or similar problem?
I found it. The problem was dangling ',' after last parameter in constructor (which Kotlin allows ).
var isPaused: Boolean = false, <- here ლ(ಠ益ಠლ)
) : RealmObject()
This is caused due to the default ktlint version used by the plugin. As of this time it's private static final String DEFAULT_VERSION = "0.35.0" which does not support trailing commas, although kotlin 1.4 does. In fact they had updated it to 0.40.0 at some point but got some formatting issues whiplash and eventually reverted the changes.
If you want though you can manually point to the latest version with something like
spotless {
kotlin {
target '**/*.kt'
ktlint("0.40.0")
}
}