Oracle Arrays and Hibernate - java

Setup - Oracle 12.1.0.2, Kotlin, Hibernate
I have table which was created like this:
create or replace type capacity_varray as varray (4000) of int;
create table plan_capacities
(
id int generated by default as identity not null constraint plan_capacities_pkey primary key,
line_id int references lines (id) on delete cascade,
model_id int references models (id) on delete cascade,
plan_id int references plans (id) on delete cascade,
capacity capacity_varray
);
Model for this table:
#Entity()
#Table(name = "plan_capacities")
#TypeDefs(
TypeDef(name = "int-array", typeClass = IntArrayType::class)
)
data class PlanCapacity(
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int,
#ManyToOne
#JoinColumn(name = "line_Id")
val line: Line,
#ManyToOne()
#JoinColumn(name = "model_Id")
val model: Model,
#JsonBackReference
#ManyToOne()
#JoinColumn(name = "plan_id")
val plan: Plan,
#Column(name = "capacity")
#Type(type = "int-array")
val capacity: IntArray
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PlanCapacity
if (id != other.id) return false
if (line != other.line) return false
if (model != other.model) return false
if (plan != other.plan) return false
if (!Arrays.equals(capacity, other.capacity)) return false
return true
}
override fun hashCode(): Int {
var result = id
result = 31 * result + line.hashCode()
result = 31 * result + model.hashCode()
result = 31 * result + plan.hashCode()
result = 31 * result + Arrays.hashCode(capacity)
return result
}
}
The array is wrongly converted from the database and I get java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integerso I tried to implement my own converter implementing UserType but here I'm stuck with setting array to db.
What is correct way of working with this int array? How should I write model for this particular table and type?
I would like to have IntArray from that field.

Solution is to derive UserType:
class IntArrayOracleType : UserType {
override fun assemble(cached: Serializable?, owner: Any?) = deepCopy(cached)
override fun deepCopy(value: Any?) = (anyToIntArraySafe(value))?.copyOf()
override fun disassemble(value: Any?) = deepCopy(value)
override fun equals(x: Any?, y: Any?) = (x?.equals(y) ?: y?.equals(x)) ?: true
override fun hashCode(x: Any?) = x?.hashCode() ?: 0
override fun isMutable() = true
override fun nullSafeGet(resultSet: ResultSet,
names: Array<out String>?,
session: SharedSessionContractImplementor?,
owner: Any?): Any? {
if (resultSet.wasNull() || names == null) {
return null
}
return anyToIntArraySafe(resultSet.getArray(names[0])?.array) ?: intArrayOf()
}
override fun nullSafeSet(statement: PreparedStatement, value: Any?, index: Int, session: SharedSessionContractImplementor) {
val connection = statement.connection
if (value == null) {
statement.setNull(index, Types.ARRAY, "INTEGER_VARRAY")
} else {
val oraConnection = connection.unwrap(OracleConnection::class.java)
val array = oraConnection.createOracleArray("INTEGER_VARRAY", value)
statement.setArray(index, array)
}
}
override fun replace(original: Any?, target: Any?, owner: Any?) = (anyToIntArraySafe(original))?.copyOf()
override fun returnedClass() = IntArray::class.java
override fun sqlTypes() = intArrayOf(Types.ARRAY)
}
/**
* Takes Any? and tries to cast it to Array and than to IntArray - BigDecimal is checked.
*
* Note that when given array contains anything else then BigDecimal or Int exception will be thrown
* #return IntArray if successfully casted, null otherwise
* */
internal fun anyToIntArraySafe(array: Any?) = (array as? IntArray) ?: (array as? Array<*>)?.map {
it as? Int ?: (it as BigDecimal).intValueExact()
}?.toIntArray()
And here cast BigDecimal to Int. Then just change IntArrayType to IntArrayOracleType and now it works.

Related

#Query says it does not have the fields, although I have them in the query itself -> Kotlin Android Room

I got this code in my DAO:
#Query("select Conversation.*, User.* from Conversation join User on Conversation.createdBy = User.userUuid where conversationUuid = :conversationUuid")
fun selectAllForOverview(conversationUuid: UUID): LiveData<List<ConversationSelectAllForOverview>>
This is ConversationSelectAllForOverview
data class ConversationSelectAllForOverview(
#Embedded(prefix = "arg0")
val arg0: DbConversation,
#Embedded(prefix = "arg1")
val arg1: DbUser
)
I read that I needed to annotate my fields with a prefix to get rid of errors when they have common field names. I get this error and I don't know how I can remove it. I am 100% sure all the columns are available, since DbConversation and DbUser are just generated from the database. How can I fix this problem? DbConversation and DbUser share some columns, see the definition of DbConversation here: https://gist.github.com/Jasperav/381243e7b3cf387bfc0e9f1343f9faeb. DbUser looks the same.
error: The columns returned by the query does not have the fields
[conversationUuid,createdBy,tsCreated,distanceMapped,showOnMap,showOnOverview,allowMessagesByInRangeRegularUsers,allowMessagesByOutOfRangeRegularUsers,stillReadableForOutOfRangeRegularUsers,freedomInReplies,title,subject,likes,latitude,longitude,hasPassword,isSubscribed,showOnMapScreen,isLiked,bypassChecks,isHidden,nsfw,currentDirectEvents,totalDirectEventsAfterLastJoin,subscriptions,userUuid,username,karma,tsCreated,allowsPrivateChats,allowsNsfw,thisUserBlockedCurrentUser,incomingFriendshipRequest,outstandingFriendshipRequest,friends,bio,appRoleMapped]
in entity.ConversationSelectAllForOverview even though they are
annotated as non-null or primitive. Columns returned by the query:
[conversationUuid,createdBy,tsCreated,distanceMapped,showOnMap,showOnOverview,allowMessagesByInRangeRegularUsers,allowMessagesByOutOfRangeRegularUsers,stillReadableForOutOfRangeRegularUsers,freedomInReplies,title,subject,likes,avatar,latitude,longitude,hasPassword,isSubscribed,showOnMapScreen,isLiked,bypassChecks,isHidden,conversationReportReasonMapped,nsfw,currentDirectEvents,totalDirectEventsAfterLastJoin,lastReadConversationEventPk,mostRecentConversationEventUuid,relevance,subscriptions,userUuid,username,karma,tsCreated,allowsPrivateChats,allowsNsfw,avatar,currentUserBlockedThisUserTsCreated,thisUserBlockedCurrentUser,searchScreenScore,recentSearchedTsCreated,userReportReasonMapped,incomingFriendshipRequest,outstandingFriendshipRequest,friends,bio,appRoleMapped]
public abstract androidx.lifecycle.LiveData<java.util.List<entity.ConversationSelectAllForOverview>>
selectAllForOverview(#org.jetbrains.annotations.NotNull()
The Issue
You are prefixing the columns in the #Embedded annotation in conjunction with the output columns not being prefixed according to the query.
For example the ConversationSelectAllForOverview class is expecting to find the column named arg0conversationUuid in the output/result of the query but the query only has the column conversationUuid.
The Fix
Instead of using select Conversation.*, User.* .... you need to use
select Conversation.conversationUuid AS arg0conversationUuid, Conversation.createdBy AS arg0createdBy ....
AS giving the output conversationUuid column an alias of arg0conversationUuid etc.
i.e. for every column in both tables you have to alias the actual column with it's prefix.
e.g. using (only partially adjusted):-
#Query("select " +
"Conversation.conversationUuid AS arg0conversationUuid" +
", Conversation.createdBy AS arg0createdBy" +
", Conversation.tsCreated AS arg0tsCreated" +
", Conversation.distanceMapped AS arg0distanceMapped" +
/* .... */
", User.* from Conversation join User on Conversation.createdBy = User.userUuid where conversationUuid = :conversationUuid")
fun selectAllForOverview(conversationUuid: UUID): LiveData<List<ConversationSelectAllForOverview>>
the message is then The columns returned by the query does not have the fields [showOnMap,showOnOverview ....
i.e. conversationUuid, createdBy, tsCreated and distanceMapped are now not included in the field-column mismatch list.
Alternative Fix (untested and reliant upon Room 2.5.0 libraries )
Another solution, which may work with Room 2.5.0 (untested) would be to use the #Relation annotation instead of the #Embedded annotation for the child(ren). e.g. without any other changes other than:-
data class ConversationSelectAllForOverview(
#Embedded/*(prefix = "arg0")*/
val arg0: DbConversation,
#Relation(
entity = DbUser::class,
parentColumn = "createdBy",
entityColumn = "userUuid"
)
val arg1: DbUser
)
and then using :-
#Transaction
#Query("SELECT * FROM Conversation WHERE conversationUUid=:conversationUuid")
fun selectAllForOverview(conversationUuid: UUID): LiveData<List<ConversationSelectAllForOverview>>
Then it compiles successfully (again not run, see below). i.e. there are no issues with the duplicated columns (again see below).
You could also use (note the function name being different to allow both to be compiled):-
#Transaction
#Query("select Conversation.*,User.* from Conversation join User on Conversation.createdBy = User.userUuid where conversationUuid = :conversationUuid")
fun selectAllForOverviewAlt(conversationUuid: UUID): LiveData<List<ConversationSelectAllForOverview>>
However the JOINed columns are superfluous as Room uses the #Relationship parameters to then build the DbUser object via a subsequent query (hence the #Transaction).
NOTE Room used to take the last value found, for a like named output column, and apply that last value to all of the fields so named. This has reportedly been fixed with 2.5.0. This hasn't been confirmed as being the case though. As such you may get unintended results, so if you take this approach you should confirm that values are as expected (i.e. check the values of the like named columns/fields).
Additional a Demo
The following is a working demo based upon the code as per the question DbConversation class. BUT, to simplify matters other code has been made up and additionally many of the fields have been commented out. LiveData has been commented out and .allowMainThreadQueries to simplify the demo.
The Demo uses both fixes and for the #Relation both the original query and the suggested more consice query.
A debugging breakpoint has been used to demonstrate the sets of 3 returns.
The Database Code (everything needed for the demo plus some that isn't due to commenting out). It should be Noted that much of the code may differ, simple assumptions have been made.
:-
#Entity(
tableName = "Conversation",
primaryKeys = ["conversationUuid"],
indices = [/*Index(value = ["nsfw", "relevance"]), Index(value = ["isSubscribed"]),*/ Index(value = ["createdBy"])/*, Index(
value = ["avatar"]
), Index(value = ["mostRecentConversationEventUuid"])*/],
foreignKeys = [/*ForeignKey(
entity = DbConversationEventMostRecent::class,
childColumns = ["mostRecentConversationEventUuid"],
parentColumns = ["conversationEventUuid"],
onDelete = SET_NULL,
onUpdate = CASCADE,
), ForeignKey(
entity = DbMedia::class,
childColumns = ["avatar"],
parentColumns = ["mediaUuid"],
onDelete = CASCADE,
onUpdate = NO_ACTION,
), */ForeignKey(
entity = DbUser::class,
childColumns = ["createdBy"],
parentColumns = ["userUuid"],
onDelete = CASCADE,
onUpdate = NO_ACTION,
)]
)
data class DbConversation(
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val conversationUuid: UUID,
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val createdBy: UUID,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val tsCreated: Long,
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val distanceMapped: ConversationDistance,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val showOnMap: Boolean,
/*
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val showOnOverview: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val allowMessagesByInRangeRegularUsers: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val allowMessagesByOutOfRangeRegularUsers: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val stillReadableForOutOfRangeRegularUsers: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val freedomInReplies: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val title: String,
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val subject: String,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val likes: Long,
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val avatar: UUID?,
#ColumnInfo(typeAffinity = ColumnInfo.REAL)
val latitude: Double,
#ColumnInfo(typeAffinity = ColumnInfo.REAL)
val longitude: Double,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val hasPassword: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val isSubscribed: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val showOnMapScreen: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val isLiked: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val bypassChecks: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val isHidden: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val conversationReportReasonMapped: ConversationReportReason?,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val nsfw: Boolean,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val currentDirectEvents: Long,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val totalDirectEventsAfterLastJoin: Long,
#ColumnInfo(typeAffinity = ColumnInfo.BLOB)
val lastReadConversationEventPk: ConversationEventPk?,
#ColumnInfo(typeAffinity = ColumnInfo.TEXT)
val mostRecentConversationEventUuid: UUID?,
#ColumnInfo(typeAffinity = ColumnInfo.REAL)
val relevance: Double?,
#ColumnInfo(typeAffinity = ColumnInfo.INTEGER)
val subscriptions: Long
*/
)
#Dao
interface AllDAOs {
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(dbUser: DbUser): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(dbConversation: DbConversation): Long
#Query("select " +
"Conversation.conversationUuid AS arg0conversationUuid" +
", Conversation.createdBy AS arg0createdBy" +
", Conversation.tsCreated AS arg0tsCreated" +
", Conversation.distanceMapped AS arg0distanceMapped" +
", Conversation.showOnMap AS arg0showOnMap" +
/* .... */
",User.userUuid AS arg1userUuid" + /*?????? made up/incomplete/asssumed */
",User.userName AS arg1userName" +
" from Conversation join User on Conversation.createdBy = User.userUuid where conversationUuid = :conversationUuid")
fun selectAllForOverviewOld(conversationUuid: UUID): /*LiveData<*/List<OldConversationSelectAllForOverview>/*>*/
#Query("SELECT * FROM Conversation WHERE conversationUuid=:conversationUuid")
fun selectConversationByUuid(conversationUuid: UUID): List<DbConversation>
#Query("SELECT * FROM Conversation WHERE conversationUuid=:conversationUuid")
fun selectAllForOverview(conversationUuid: UUID): /*LiveData<*/List<ConversationSelectAllForOverview>/*>*/
#Query("select Conversation.*,User.* from Conversation join User on Conversation.createdBy = User.userUuid where conversationUuid = :conversationUuid")
fun selectAllForOverviewAlt(conversationUuid: UUID): /*LiveData<*/List<ConversationSelectAllForOverview>/*>*/
}
data class ConversationDistance(
val blah: String
)
data class ConversationReportReason(
val blah: String
)
data class ConversationEventPk(
val blah: ByteArray
)
class RoomTypeConverters {
#TypeConverter
fun fromConversationDistanceToJSON(conversationDistance: ConversationDistance): String = Gson().toJson(conversationDistance)
#TypeConverter
fun toConversationDistanceFromJSON(json: String): ConversationDistance = Gson().fromJson(json,ConversationDistance::class.java)
#TypeConverter
fun fromConversationReportReasonToJSON(conversationReportReason: ConversationReportReason): String = Gson().toJson(conversationReportReason)
#TypeConverter
fun toConversationReportReasonFromJSON(json: String): ConversationReportReason = Gson().fromJson(json,ConversationReportReason::class.java)
#TypeConverter
fun fromConversationEventPkToByteArray(conversationEventPk: ConversationEventPk): ByteArray = ByteArray(100)
#TypeConverter
fun toConversationEventPkFromByteArray(byteArray: ByteArray): ConversationEventPk = ConversationEventPk(byteArray)
}
#Entity(tableName = "User")
data class DbUser(
#PrimaryKey
val userUuid: UUID,
val userName: String
)
#Entity
data class DbMedia(
#PrimaryKey
val mediaUuid: UUID,
val mediaName: String
)
#Entity
data class DbConversationEventMostRecent(
#PrimaryKey
val conversationEventUuid: UUID
)
data class ConversationSelectAllForOverview(
#Embedded/*(prefix = "arg0")*/
val arg0: DbConversation,
#Relation(
entity = DbUser::class,
parentColumn = "createdBy",
entityColumn = "userUuid"
)
val arg1: DbUser
)
data class OldConversationSelectAllForOverview(
#Embedded(prefix = "arg0")
val arg0: DbConversation,
#Embedded(prefix = "arg1")
val arg1: DbUser
)
#TypeConverters(value = [RoomTypeConverters::class])
#Database(entities = [DbMedia::class,DbUser::class,DbConversationEventMostRecent::class,DbConversation::class], exportSchema = false, version = 1)
abstract class TheDatabase: RoomDatabase() {
abstract fun getAllDAOs(): AllDAOs
companion object {
private var instance: TheDatabase? = null
fun getInstance(context: Context): TheDatabase {
if (instance==null) {
instance=Room.databaseBuilder(context,TheDatabase::class.java,"the_database")
.allowMainThreadQueries() /* For brevity of demo */
.build()
}
return instance as TheDatabase
}
}
}
The Activity Code:-
class MainActivity : AppCompatActivity() {
lateinit var db: TheDatabase
lateinit var dao: AllDAOs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = TheDatabase.getInstance(this)
dao = db.getAllDAOs()
val u1uuid = UUID(10L,10L)
val u2uuid = UUID(11L,12L)
val c1uuid = UUID(20L,20L)
val c2uuid = UUID(21L,21L)
val c3uuid = UUID(22L,10L)
val c4uuid = UUID(15L,10L)
dao.insert(DbUser(u1uuid,"Fred"))
dao.insert(DbUser(u2uuid,"Mary"))
dao.insert(DbConversation(c1uuid,u1uuid,0, ConversationDistance("blah blah blah"),true))
dao.insert(DbConversation(c2uuid,u2uuid,0,ConversationDistance("uhm uhm uhm"),true))
dao.insert(DbConversation(c3uuid,u1uuid,0,ConversationDistance("meh meh meh"),true))
dao.insert(DbConversation(c4uuid,u1uuid,0,ConversationDistance("good good good"),true))
val c1 = dao.selectConversationByUuid(c1uuid)
val c2 = dao.selectConversationByUuid(c2uuid)
val c3 = dao.selectConversationByUuid(c3uuid)
val c4 = dao.selectConversationByUuid(c4uuid)
val t1c1 = dao.selectAllForOverviewOld(c1uuid)
val t1c2 = dao.selectAllForOverview(c1uuid)
val t1c3 = dao.selectAllForOverviewAlt(c1uuid)
val t2c1 = dao.selectAllForOverviewOld(c2uuid)
val t2c2 = dao.selectAllForOverview(c2uuid)
val t2c3 = dao.selectAllForOverviewAlt(c2uuid)
if (t1c1==null) t1c1==null /*<<<<<<<<<< BREAKPOINT HERE >>>>>>>>>>*/
}
}
When run from a fresh install, then The debug window, with t1?? and t2?? expanded:-
As can be seen all 3 queries produce the same result. As such the simplest solution would be to
ensure that you are using Room 2.5.0 libraries, AND
use #Relation instead of #Embedded and use the more concise query just extracting the relevant DbConversation(s).
Take a look at your classes DbConversation and DbUser and make sure these classes are #Embeddable. If not, put the annotation on the class.
Another solution is look at the error again. It say that query return a bunch of columns that your DTO (ConversationSelectAllForOverview) doens't hold; the fields of your DTO are the objects and not the columns fields. You can create an interface receiving all those columns that db return:
interface nameInterface(
val conversationUuid: Any,
val createdBy: Any,
val tsCreated: Any,
val distanceMapped: Any,
val showOnMap: Any,
val showOnOverview: Any,
val allowMessagesByInRangeRegularUsers: Any,
val allowMessagesByOutOfRangeRegularUsers: Any,
val stillReadableForOutOfRangeRegularUsers: Any,
val freedomInReplies: Any,
val title: Any,
val subject: Any,
val likes: Any,
val latitude: Any,
val longitude: Any,
val hasPassword: Any,
val isSubscribed: Any,
val showOnMapScreen: Any,
val isLiked: Any,
val bypassChecks: Any,
val isHidden: Any,
val nsfw: Any,
val currentDirectEvents: Any,
val totalDirectEventsAfterLastJoin: Any,
val subscriptions: Any,
val userUuid: Any,
val username: Any,
val karma: Any,
val tsCreated: Any,
val allowsPrivateChats: Any,
val allowsNsfw: Any,
val thisUserBlockedCurrentUser: Any,
val incomingFriendshipRequest: Any,
val outstandingFriendshipRequest: Any,
val friends: Any,
val bio: Any,
val appRoleMapped: Any)

Java/Kotlin MongoDB search without counting

I need to search for objects using org.springframework.data.mongodb.core.query.Query and org.springframework.data.domain.Pageable.
I implemented a search with getting the number of objects each time. This is not very optimal, as I understand it.
fun search(query: Query, pageable: Pageable): Page<BookDocument> {
val bookObjects = mongoTemplate.find(
query.with(pageable),
BookDocument::class.java
)
val count = mongoTemplate.count(query, BookDocument::class.java)
return PageImpl(bookObjects, pageable, count)
}
Is it possible to implement a search without counting?
Actually my function should return such PageDto. But I don't know how it can be most optimally implemented.
class PageDto<T>(
val pageable: Pageable,
val data: List<T>,
val hasNext: Boolean,
val hasPrevious: Boolean // optional field
)
So, I solved this issue like this:
fun search(query: Query, pageable: Pageable): PageDto<BookDocument> {
val bookObjects = mongoTemplate.find(query, BookDocument::class.java)
return PageDto(pageable, bookObjects)
}
data class PageDto<T>(
val pageable: Pageable,
val content: List<T>,
val hasNext: Boolean,
val hasPrevious: Boolean
) {
constructor(
pageable: Pageable,
data: List<T>
) : this(
pageable = pageable,
content = data.take(pageable.pageSize),
hasNext = data.count() > pageable.pageSize,
hasPrevious = pageable.offset > 0
)
}

Reflection to get default value of parameter

I am trying to use reflection to get all the optional fields in a class and their default values (if any). This is my attempt:
fun getOptionalFields(componentType: KClass<out Any>): Map<String, DefaultValueData> {
val cons = componentType.primaryConstructor
val constructorSetup = cons?.parameters
?.filterNot { it.isOptional }
?.associate { it to getValueForNonOptional(it) } ?: error("Something went wrong when choosing default val")
val constructorInst = (cons.callBy(constructorSetup)::class as KClass<Any>)
val conParams = (componentType.primaryConstructor?.parameters ?: emptyList())
.filter { p -> p.isOptional }
.associate { p ->
Pair(p.name ?: "",
DefaultValueData(
p.type,
// the below line crashes
constructorInst.memberProperties.first { m -> m.name == p.name }.get(constructorInst)
)
)
}
return conParams
}
The error: Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
I am a bit puzzled at what get() wants me to pass if not the instance to get the value from?
You are trying to get the value by providing a KClass instead of the actual instance.
This is a working solution based on your method signature and your code above:
data class Test(
val required: String,
val optional: Int = 7
)
val componentType = Test::class
val constructorInst = Test("required") // i skipped constructing the class via constructor
val conParams = (componentType.primaryConstructor?.parameters ?: emptyList())
.filter { p -> p.isOptional }
.associate { p ->
Pair(p.name ?: "",
Pair(
p.type,
componentType.memberProperties.first { m -> m.name == p.name }.get(constructorInst)
)
)
}
println(conParams) // <- OUTPUTS: {optional=(kotlin.Int, 7)}
Why have i removed this code?
val constructorSetup = cons?.parameters
?.filterNot { it.isOptional }
?.associate { it to getValueForNonOptional(it) } ?: error("Something went wrong when choosing default val")
val constructorInst = (cons.callBy(constructorSetup)::class as KClass<Any>)
The resulting object cons.callBy(constructorSetup) is unused because calling ::class on the expression rendered it useless. Additionally it is not required to perform the requested task in your question.
When updating your above code, result will look like
fun getOptionalFields(componentType: KClass<out Any>): Map<String, DefaultValueData> {
val cons = componentType.primaryConstructor
val constructorSetup = cons?.parameters
?.filterNot { it.isOptional }
?.associate { it to getValueForNonOptional(it) } ?: error("Something went wrong when choosing default val")
val constructorInst = cons.callBy(constructorSetup) // <- removed ::class and cast
val conParams = (componentType.primaryConstructor?.parameters ?: emptyList())
.filter { p -> p.isOptional }
.associate { p ->
val value = constructorInst::class.memberProperties.first { m -> m.name == p.name }.get(constructorInst) as KProperty1<out Any, out Any>
Pair(p.name ?: "",
DefaultValueData(
p.type,
value
)
)
}
return conParams
}

"map(From)' in 'Mapper' clashes with 'map(Object)' in 'CursorToMessageImpl'; both methods have same erasure, yet neither overrides the other

This is code in kotlin. Showing error Type inference failed: inline fun T.apply(block: T.() -> Unit): T cannot be applied to receiver: Message arguments: (Message.() -> Any) .
**map(From)' in 'Mapper' clashes with 'map(Object)' in 'CursorToMessageImpl'; both methods have same erasure, yet neither overrides the other
**
class CursorToMessageImpl #Inject constructor(
private val context: Context,
private val cursorToPart: CursorToPart,
private val keys: KeyManager,
private val permissionManager: PermissionManager,
private val preferences: Preferences) : CursorToMessage
{
private val uri = Uri.parse("content://mms-sms/complete-conversations")
private val projection = arrayOf(
MmsSms.TYPE_DISCRIMINATOR_COLUMN,
MmsSms._ID,
Mms.DATE,
Mms.DATE_SENT,
Mms.READ,
Mms.THREAD_ID,
Mms.LOCKED,
Sms.ADDRESS,
Sms.BODY,
Sms.SEEN,
Sms.TYPE,
Sms.STATUS,
Sms.ERROR_CODE,
Mms.SUBJECT,
Mms.SUBJECT_CHARSET,
Mms.SEEN,
Mms.MESSAGE_TYPE,
Mms.MESSAGE_BOX,
Mms.DELIVERY_REPORT,
Mms.READ_REPORT,
MmsSms.PendingMessages.ERROR_TYPE,
Mms.STATUS
)
override fun map(from: Pair<Cursor, CursorToMessage.MessageColumns>): Message {
val cursor = from.first
val columnsMap = from.second
return Message().apply {
type = when {
cursor.getColumnIndex(MmsSms.TYPE_DISCRIMINATOR_COLUMN) != -1 -> cursor.getString(columnsMap.msgType)
cursor.getColumnIndex(Mms.SUBJECT) != -1 -> "mms"
cursor.getColumnIndex(Sms.ADDRESS) != -1 -> "sms"
else -> "unknown"
}
id = keys.newId()
threadId = cursor.getLong(columnsMap.threadId)
contentId = cursor.getLong(columnsMap.msgId)
date = cursor.getLong(columnsMap.date)
dateSent = cursor.getLong(columnsMap.dateSent)
read = cursor.getInt(columnsMap.read) != 0
locked = cursor.getInt(columnsMap.locked) != 0
subId = if (columnsMap.subId != -1) cursor.getInt(columnsMap.subId)
else -1
when (type) {
"sms" -> {
address = cursor.getString(columnsMap.smsAddress) ?: ""
boxId = cursor.getInt(columnsMap.smsType)
seen = cursor.getInt(columnsMap.smsSeen) != 0
body = columnsMap.smsBody
.takeIf { column -> column != -1 } // The column may not be set
?.let { column -> cursor.getString(column) } ?: "" // cursor.getString() may return null
errorCode = cursor.getInt(columnsMap.smsErrorCode)
deliveryStatus = cursor.getInt(columnsMap.smsStatus)
}
"mms" -> {
address = getMmsAddress(contentId)
boxId = cursor.getInt(columnsMap.mmsMessageBox)
date *= 1000L
dateSent *= 1000L
seen = cursor.getInt(columnsMap.mmsSeen) != 0
mmsDeliveryStatusString = cursor.getString(columnsMap.mmsDeliveryReport) ?: ""
errorType = if (columnsMap.mmsErrorType != -1) cursor.getInt(columnsMap.mmsErrorType) else 0
messageSize = 0
readReportString = cursor.getString(columnsMap.mmsReadReport) ?: ""
messageType = cursor.getInt(columnsMap.mmsMessageType)
mmsStatus = cursor.getInt(columnsMap.mmsStatus)
val subjectCharset = cursor.getInt(columnsMap.mmsSubjectCharset)
subject = cursor.getString(columnsMap.mmsSubject)
?.takeIf { it.isNotBlank() }
?.let(_root_ide_package_.app.google.android.mms.pdu_alt.PduPersister::getBytes)
?.let { _root_ide_package_.app.google.android.mms.pdu_alt.EncodedStringValue(subjectCharset, it).string } ?: ""
textContentType = ""
attachmentType = Message.AttachmentType.NOT_LOADED
parts.addAll(cursorToPart.getPartsCursor(contentId)?.map { cursorToPart.map(it) } ?: listOf())
}
else -> -1
}
}
}
**and interference mapper is :-**
interface Mapper<in From, out To> {
fun map(from: From): To
}
I'm not 100% sure this is your issue, but since else -> -1 in your when statement doesn't accomplish anything, try removing it. A when statement doesn't have to be exhaustive when it isn't being forced to be evaluated as an expression (by assigning its result to a variable or property).
else -> -1 at the bottom of your when statement causes it to be a when expression that returns Any. Usually, the compiler can interpret a lambda ending in an expression other than Unit as having an implicit return of Unit if there are no overloads that it would otherwise match. But there may be some cases where the involved classes are complex enough to prevent it from deducing that.

How to deserialize nested class with Gson in Kotlin?

I have json as in below, I'm really new on kotlin and i tried all examples but cannot set my nested class values when i convert to json
Here my json
{"Init":{"MOP":[{"Id":"1","Type":"0","ProtocolVersion":"1.0","MopCode":"*NEXB","TerminalId":"'P400Plus-275008565'","IP":"'192.168.1.15'","Currency":"EUR"},{"Id":"2","Type":"0","ProtocolVersion":"1.0","MopCode":"*NEXF","TerminalId":"'P400Plus-275008565'","IP":"'10.0.0.0:901'","Currency":"EUR"}]}}
Here my POJO
class Root {
#JsonProperty("Init")
var init: Init? = null
}
class MOP {
#JsonProperty("Id")
var id: String? = null
#JsonProperty("Type")
var type: String? = null
#JsonProperty("ProtocolVersion")
var protocolVersion: String? = null
#JsonProperty("MopCode")
var mopCode: String? = null
#JsonProperty("TerminalId")
var terminalId: String? = null
#JsonProperty("IP")
var ip: String? = null
#JsonProperty("Currency")
var currency: String? = null
}
class Init {
#JsonProperty("MOP")
var mop: List<MOP>? = null
}
Here my trial
val root: TestClass.Root = gson.fromJson(receiveString,TestClass.Root::class.java)
val initList = HashMap<String?,String?>()
if (root.init != null){
val mopList = root.init!!.mop
if (mopList != null) {
for (item in mopList){
initList.put(item.mopCode,item.id)
}
}
}
Always root.init and root.init.mop are null
What you can suggest me?
Thanks
Your Json construction has different tree.
You should use following structure:
data class Root (
#SerializedName("Init") val init : Init
)
data class Init (
#SerializedName("MOP") val mOP : List<MOP>
)
data class MOP (
#SerializedName("Id") val id : Int,
#SerializedName("Type") val type : Int,
#SerializedName("ProtocolVersion") val protocolVersion : Double,
#SerializedName("MopCode") val mopCode : String,
#SerializedName("TerminalId") val terminalId : String,
#SerializedName("IP") val iP : String,
#SerializedName("Currency") val currency : String
)
And you can parse just with:
Gson().fromJson(data,Root::class.java)
Also if you are using Gson, you should use SerializedName instead JsonProperty.

Categories