Can someone help me to fix this, I am trying to debug this method after upgrading from java conversion to java convertors. I am very new to scala.
def parse(table: String,json: String): Either[Map[String, _], Map[String, Object]] = {
try {
val parsedMap = jsonObjectMapper.readValue(json, classOf[MessageDetails])
//Convert from class type to Map type
val javaMap = jsonObjectMapper.convertValue(parsedMap,classOf[java.util.Map[String,Object]])
val msgBodyContent = javaMap.get("MessageDetails").asInstanceOf[java.util.LinkedHashMap[String,Object]]
// Move messageBody content to top level
var outMap = javaMap
if (msgBodyContent != null) {
outMap = javaMap - "MessageDetails" ++ msgBodyContent
}
Right(outMap.toMap)
} catch {
case e: Exception =>
logger.error("unable to parse JSON", e)
Left(createErrorRec(json,"JSON_PARSE_ERROR",e.getMessage,table))
}
}
getting error
value - is not a member of java.util.Map[String,Object] &
value toMap is not a member of java.util.Map[String,Object]
Related
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
}
fun getSummary(id: String): List<Summary> {
val request = GetSummaryRequest(id)
val response = client.getSummary(request) as GetSummaryResponse
return when (val result = response.result) {
is GetSummarySuccessResponse-> result.summaryList
is GetSummaryFailResponse-> throw TreasuryRpcException("There was an error calling getSummary")
else -> "No message"
}
}
it gives me a red line for :List<Summary> because return can be List<Summary>, Exception,String, I know I probably can use Any as return type.
Just want to know the best practice in this case. Thanks!
The exception is thrown so it is not part of the return type. You should return either emptyList() or null for the else condition so the return type can still be List<Summary> or at least List<Summary>?. You only need nullability if you need to distinguish that condition from a successful result.
You probably need to use sealed class in this case.
First of all create a sealed class as follows:
sealed class Resource<out R>
data class Success<out R>(val data: R) : Resource<R>()
data class Failed(val t: Throwable? = null) : Resource<Nothing>()
data class Info(val message: String = "Something went wrong") : Resource<Nothing>()
In your code change the return type from List<Summary> to Resource<List<Summary>>. After changing, the code will look like following:
fun getSummary(id: String): Resource<List<Summary>> {
val request = GetSummaryRequest(id)
val response = client.getSummary(request) as GetSummaryResponse
return when (val result = response.result) {
is GetSummarySuccessResponse-> Success(result.summaryList)
is GetSummaryFailResponse-> Failed(TreasuryRpcException("There was an error calling getSummary"))
else -> Info("No message")
}
}
The code where you call getSummary() should look like following:
val summaryResource = getSummary(id)
when(summaryResource) {
is Success -> {
val summary = summaryResource.data
// Do something with summary
}
is Failed -> {
val t = summaryResource.t
println(t?.message)
// Do something with t
}
is Info -> {
val msg = summaryResource.message
println(msg)
// Do something with msg
}
}
I have string like this.
val input = "perm1|0,perm2|2,perm2|1"
Desired output type is
val output: Set<String, Set<Long>>
and desired output value is
{perm1 [], perm2 [1,2] }
Here I need empty set if value is 0. I am using groupByTo like this
val output = input.split(",")
.map { it.split("|") }
.groupByTo(
mutableMapOf(),
keySelector = { it[0] },
valueTransform = { it[1].toLong() }
)
However the output structure is like this
MutableMap<String, MutableList<Long>>
and output is
{perm1 [0], perm2 [1,2] }
I am looking for best way to get desired output without using imperative style like this.
val output = mutableMapOf<String, Set<Long>>()
input.split(",").forEach {
val t = it.split("|")
if (t[1].contentEquals("0")) {
output[t[0]] = mutableSetOf()
}
if (output.containsKey(t[0]) && !t[1].contentEquals("0")) {
output[t[0]] = output[t[0]]!! + t[1].toLong()
}
if (!output.containsKey(t[0]) && !t[1].contentEquals("0")) {
output[t[0]] = mutableSetOf()
output[t[0]] = output[t[0]]!! + t[1].toLong()
}
}
You can simply use mapValues to convert values type from List<Long> to Set<Long>
var res : Map<String, Set<Long>> = input.split(",")
.map { it.split("|") }
.groupBy( {it[0]}, {it[1].toLong()} )
.mapValues { it.value.toSet() }
And of you want to replace list of 0 with empty set you can do it using if-expression
var res : Map<String, Set<Long>> = input.split(",")
.map { it.split("|") }
.groupBy( {it[0]}, {it[1].toLong()} )
.mapValues { if(it.value == listOf<Long>(0)) setOf() else it.value.toSet() }
Note that you cannot have Set with key-value pair, result will be of type map. Below code gives sorted set in the values.
val result = "perm1|0,perm2|2,perm2|1".split(",")
.map {
val split = it.split("|")
split[0] to split[1].toLong()
}.groupBy({ it.first }, { it.second })
.mapValues { it.value.toSortedSet() }
While the other answer(s) might be easier to grasp, they build immediate lists and maps in between, that are basically discarded right after the next operation. The following tries to omit that using splitToSequence (Sequences) and groupingBy (see Grouping bottom part):
val result: Map<String, Set<Long>> = input.splitToSequence(',')
.map { it.split('|', limit = 2) }
.groupingBy { it[0] }
.fold({ _, _ -> mutableSetOf<Long>() }) { _, accumulator, element ->
accumulator.also {
it.add(element[1].toLong()))
}
}
You can of course also filter out the addition of 0 in the set with a simple condition in the fold-step:
// alternative fold skipping 0-values, but keeping keys
.fold({ _, _ -> mutableSetOf<Long>() }) { _, accumulator, element ->
accumulator.also {
val value = element[1].toLong()
if (value != 0L)
it.add(value)
}
}
Alternatively also aggregating might be ok, but then your result-variable needs to change to Map<String, MutableSet<Long>>:
val result: Map<String, MutableSet<Long>> = // ...
.aggregate { _, accumulator, element, first ->
(if (first) mutableSetOf<Long>() else accumulator!!).also {
val value = element[1].toLong()
if (value != 0L)
it.add(value)
}
}
open class Test {
fun getAsHashMap() : HashMap<String, Any> {
val hashMap = HashMap<String, Any>()
val className = this.javaClass.kotlin
for (prop in className::class.memberProperties) {
val field = className::class.java.getDeclaredField(prop.name)
val fieldSerializedName : SerializedName? = field.getAnnotation(SerializedName::class.java)
fieldSerializedName?.let {
hashMap[fieldSerializedName.value] = prop.get(this)!!
} ?: run {
hashMap[prop.name] = prop.get(this)!!
}
}
return hashMap
}
}
I have wrote above function to map the memberProperties of object instance of its child class to hashmap. It either uses serialized name of the member or prop name [Based on availability of serialized name for that property]
But unfortunately I get the following error.
This is my first time using reflection java/kotlin, please let me know if it can be fixed.
Edit 1:
It works perfectly if I use name of the this.javaClass.kotlin directly like this
data class ProductInformation (
#field:SerializedName("productid")
val productId: Int,
#field:SerializedName("productname")
val productName: String,
#field:SerializedName("brandname")
val brandName: String,
#field:SerializedName("originalprice")
val originalPrice: Int,
#field:SerializedName("sellingprice")
val sellingPrice: Int,
#field:SerializedName("productgender")
val productGender: String,
#field:SerializedName("productvariant")
val productVariant: String,
#field:SerializedName("discounted")
val discounted: String,
#field:SerializedName("productcategory")
val productCategory: String
) : StructuredEventAttribute {
override fun getAsHashMap(): HashMap<String, Any> {
val hashMap = HashMap<String, Any>()
for (prop in ProductInformation::class.memberProperties) {
val field = ProductInformation::class.java.getDeclaredField(prop.name)
val fieldSerializedName : SerializedName? = field.getAnnotation(SerializedName::class.java)
fieldSerializedName?.let {
hashMap[fieldSerializedName.value] = prop.get(this)!!
} ?: run {
hashMap[prop.name] = prop.get(this)!!
}
}
return hashMap
}
}
interface StructuredEventAttribute {
fun getAsHashMap() : HashMap<String, Any>
}
It works perfectly fine
ProductInformation::class.memberProperties returns a collection of ProductInformation class member properties.
className::class.memberProperties (where className = this.javaClass.kotlin) returns a collection of member properties of class of className, which is KClass<out Test>. In short you are getting members of KClass instead of Test.
Solution: change className::class.memberProperties to className.memberProperties.
using Jsoup, I extract JavaScript part in html file. and store it as java String Object.
and I want to extract function list, variables list in js's function using javax.script.ScriptEngine
JavaScript part has several function section.
ex)
function a() {
var a_1;
var a_2
...
}
function b() {
var b_1;
var b_2;
...
}
function c() {
var c_1;
var c_2;
...
}
My Goals is right below.
List funcList
a
b
c
List varListA
a_1
a_2
...
List varListB
b_1
b_2
...
List varListC
c_1
c_2
...
How can I extract function list and variables list(or maybe values)?
I think you can do this by using javascript introspection after having loaded the javascript in the Engine - e.g. for functions:
ScriptEngine engine;
// create the engine and have it load your javascript
Bindings bind = engine.getBindings(ScriptContext.ENGINE_SCOPE);
Set<String> allAttributes = bind.keySet();
Set<String> allFunctions = new HashSet<String>();
for ( String attr : allAttributes ) {
if ( "function".equals( engine.eval("typeof " + attr) ) ) {
allFunctions.add(attr);
}
}
System.out.println(allFunctions);
I haven't found a way to extract the variables inside functions (local variables) without delving in internal mechanics (and thus unsafe to use) of the javascript scripting engine.
It is pretty tricky. ScriptEngine API seems not good for inspecting the code. So, I have such kind of pretty ugly solution with instance of and cast operators.
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
for (Map.Entry<String, Object> scopeEntry : bindings.entrySet()) {
Object value = scopeEntry.getValue();
String name = scopeEntry.getKey();
if (value instanceof NativeFunction) {
log.info("Function -> " + name);
NativeFunction function = NativeFunction.class.cast(value);
DebuggableScript debuggableFunction = function.getDebuggableView();
for (int i = 0; i < debuggableFunction.getParamAndVarCount(); i++) {
log.info("First level arg: " + debuggableFunction.getParamOrVarName(i));
}
} else if (value instanceof Undefined
|| value instanceof String
|| value instanceof Number) {
log.info("Global arg -> " + name);
}
}
I had similar issue. Maybe it will be helpfull for others.
I use groove as script lang. My Task was to retrive all invokable functions from the script. And then filter this functions by some criteria.
Unfortunately this approach is usefull only for groovy...
Get script engine:
public ScriptEngine getEngine() throws Exception {
if (engine == null)
engine = new ScriptEngineManager().getEngineByName(scriptType);
if (engine == null)
throw new Exception("Could not find implementation of " + scriptType);
return engine;
}
Compile and evaluate script:
public void evaluateScript(String script) throws Exception {
Bindings bindings = getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
bindings.putAll(binding);
try {
if (engine instanceof Compilable)
compiledScript = ((Compilable)getEngine()).compile(script);
getEngine().eval(script);
} catch (Throwable e) {
e.printStackTrace();
}
}
Get functions from script. I did not found other ways how to get all invokable methods from script except Reflection. Yeah, i know that this approach depends on ScriptEngine implementation, but it's the only one :)
public List getInvokableList() throws ScriptException {
List list = new ArrayList();
try {
Class compiledClass = compiledScript.getClass();
Field clasz = compiledClass.getDeclaredField("clasz");
clasz.setAccessible(true);
Class scrClass = (Class)clasz.get(compiledScript);
Method[] methods = scrClass.getDeclaredMethods();
clasz.setAccessible(false);
for (int i = 0, j = methods.length; i < j; i++) {
Annotation[] annotations = methods[i].getDeclaredAnnotations();
boolean ok = false;
for (int k = 0, m = annotations.length; k < m; k++) {
ok = annotations[k] instanceof CalculatedField;
if (ok) break;
}
if (ok)
list.add(methods[i].getName());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
}
return list;
}
In my task i don't need all functions, for this i create custom annotation and use it in the script:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface CalculatedField {
}
Script example:
import com.vssk.CalculatedField;
def utilFunc(s) {
s
}
#CalculatedField
def func3() {
utilFunc('Testing func from groovy')
}
Method to invoke script function by it's name:
public Object executeFunc(String name) throws Exception {
return ((Invocable)getEngine()).invokeFunction(name);
}