java.lang.ClassCastException while trying to print container id in jade - java

I have a code for finding the list of containers from the ams in jade using queryPlatformAction method. I am getting a problem for typecasting the container id while putting the sop statement at the end..
Result result = (Result) content;
List listOfPlatforms = (List) result.getValue();
Iterator iter = listOfPlatforms.iterator();
while (iter.hasNext())
{
ContainerID next = (ContainerID) iter.next();
System.out.println(next.getID());
}
It is throwing an exception to me.
The exception is: java.lang.ClassCastException: jade.util.leap.ArrayList cannot
be cast to java.util.List
please help.

The two types of List are not in the same class hierarchy and therefore cannot be cast between each other, hence a ClassCastException.
The jade.util.leap.List interface is used within JADE to provide a List collection that looks the same between the different back-ends of JADE, but which is actually implemented differently. From the Javadocs, ArrayList only extends Object.
To fix this, declare listOfPlatforms to be of type jade.util.leap.List.

Related

How to map cache to a list of DTO object?

I have this cache that is basically a list of a DTO:
ClassA:
#Cacheable("MyList")
public List<MyObjectDTO> setCachedList(){
return api.getList(); //call to another api to fetch that list
}
ClassB:
public List<MyObjectDTO> getCachedList(){
if(!CacheManager.getCacheNames().contains("MyList"){
ClassB.setCachedList();
}
Cache cache = CacheManager.getCache("MyList");
Type listType = new TypeToken<List<MyObjectDTO>>(){}.getType(); //error occurs here
List<MyObjectDTO> returnList = modelMapper.map(cache, listType);
return returnList;
I get the following error in above code:
Failed to instantiate instance of destination java.util.List. Ensure that java.util.List has a non-private no-argument constructor.
I saw a similar question but since I am using cache of a list, I cannot extend it to concrete class.
I don't think the error is in the line you mention but in the one right after. Type returns List, but List is an interface and therefore impossible to instantiate, your mapper must be catching this exception and throwing the error.
You should try another way for getting the cache type, maybe cache.getClass() or something of the sort will do the trick.
I was able to resolve the issue by passing cache.get(SimpleKey.EMPTY).get() in the modelMapper instead of cache.

Using scala.collection.immutable.Map inside my java class

I get bellow exception from my java codes.
java.lang.ClassCastException: scala.collection.immutable.Map$Map1 cannot be cast to java.util.HashMap
at au.com.vroc.udf.medianUDF.update(medianUDF.java:79)
I am getting error in my spark application when I cast the buffer to HashMap of java.utill. This is my codes:
public void update(MutableAggregationBuffer buffer, Row input) {
if (!input.isNullAt(0)) {
HashMap currentBuffer=(HashMap) buffer.get(0);//getting exception here
//HashMap currentBuffer=new HashMap();
currentBuffer.put(input.getLong(0), input.getDouble(0));
//currentBuffer.add(currentMap);
buffer.update(0, currentBuffer);
}
}
I guess instead of java hashmap I have to use "scala.collection.immutable.Map$Map1" inside my java class. Can I use any tool in "JavaConversions" namespace.
Anyhep would be appreciated!
Simplest approach would likely be to use Scala Converters.
It should look something like this (not tested, but type-checks):
import scala.collections.JavaConverters
java.util.Map currentBuffer = JavaConverters.mapAsJavaMapConverter(buffer.get(0)).asJava();
Please note that it returns type-parameterized map (i.e. java.util.Map<K, V>), not the non-parameterized java.util.HashMapin your example - you might want to alter the rest of your code to work on the parameterized maps for better type safety.
You get java.util.Map you should use getJavaMap method:
java.util.Map<T, U> currentBuffer = (java.util.Map<T, U>) first.getJavaMap(0)
Note that this is not HashMap - initialized value is Encoded on update and decoded on get. To modify it, you have to make a copy.

ClassCastException after applying PathProperties

I'm trying to apply some PathProperties to my Finders but I keep getting this error :
[ClassCastException: java.util.ArrayList cannot be cast to com.avaje.ebean.bean.BeanCollection]
It only happens when I have a List<...> called in my PathProperties like so :
PathProperties pathProperties = PathProperties.parse("(*,historique(*))");
List<Devi> test = Devi.find.apply(pathProperties).findList();
Where my Finder is defined like this :
public static Finder<String,Devi> find = new Finder<String,Devi>(Devi.class);
Here, the object Devi is full of public variables, that I am able to call without any issue (the PathProperties "(*)" works), but when I try to access a List of objects inside this object (here, public List<Histo> historique), it won't work. I tried, and I'm also able to access an object within the object, as long as it's not a List.
I'm kinda lost here, I don't know what I did wrong.
According to https://github.com/ebean-orm/ebean/issues/591 , this is a bug triggered by initializing the ArrayList. Without the initialization it will apparently work.

Play-Framework: Causing a 'IllegalArgumentException occured

The error I get is 'IllegalArgumentException occured' Can not set java.util.ArrayList field mi.types.ListOfObjects.objects to java.util.LinkedList
I'm doing the following...
ListOfObjects objects = li.getUsersObjects();
which works perfectly fine normally, however when I do the exact same call with the exact same code inside of Play it doesn't. I'm calling it in my Security Controller inside the authenticate() function. There's a case where the users objects are gotten from an external server. That's when this call is made. It works fine without Play and I'm pretty sure worked before I put it in the Security Controller. Why would putting it here cause such a problem?
EDIT
ListOfObjects is a custom object which contains some values.. It's located inside li which is a library I'm importing. It looks something like this...
public class ListOfObjects {
private ArrayList<Object> objects;
public ArrayList<Object> getObjects(){
return objects;
}
}
getUserObjects simply returns the objects for that user. It grabs them from a server and then uses gson to parse them. However I'm getting the above error when I attempt to.
EDIT2
No matter what I do my type for getUserObjects seems to always be returning as a LinkedList even though it's an ArrayList object. I've tried calling getObjects() directly and there's no change.
EDIT 3
getUserObjects is defined as...
Gson gson = new Gson();
ListOfObjects objects = gson.fromJson(r.getBody(), ListOfObjects.class);
StackTrace...
where r.getBody() is the JSON response from the server
Execution exception (In /app/controllers/Security.java around line 57)
IllegalArgumentException occured : Can not set java.util.ArrayList field lm.types.ListOfObjects.objects to java.util.LinkedList
play.exceptions.JavaExecutionException: Can not set java.util.ArrayList field lm.types.ListOfObjects.objects to java.util.LinkedList
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:227)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.IllegalArgumentException: Can not set java.util.ArrayList field lm.types.ListOfObjects.objects to java.util.LinkedList
at com.google.gson.FieldAttributes.set(FieldAttributes.java:188)
at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler(JsonObjectDeserializationVisitor.java:118)
at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:158)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:131)
at com.google.gson.JsonDeserializationContextDefault.fromJsonObject(JsonDeserializationContextDefault.java:73)
at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializationContextDefault.java:51)
at com.google.gson.Gson.fromJson(Gson.java:568)
at com.google.gson.Gson.fromJson(Gson.java:515)
at com.google.gson.Gson.fromJson(Gson.java:484)
at com.google.gson.Gson.fromJson(Gson.java:434)
at com.google.gson.Gson.fromJson(Gson.java:406)
at lm.lib.LMethods.getUsersObjects(LMethods.java:165)
at controllers.Security.createNewUser(Security.java:57)
at controllers.Security.authenticate(Security.java:36)
at play.utils.Java.invokeStaticOrParent(Java.java:159)
at controllers.Secure$Security.invoke(Secure.java:193)
at controllers.Secure$Security.access$0(Secure.java:184)
at controllers.Secure.authenticate(Secure.java:64)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:540)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:498)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:474)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:469)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:157)
... 1 more
Debugger failed to attach: recv failed during handshake: Connection reset by peer
Exception message clearly says that Gson deserializes list as LinkedList, whereas field of your ListOfObjects is declared as ArrayList.
The general rule to avoid this kind of problems is not to use implementation classes in field declarations. Use List instead:
public class ListOfObjects {
private List<Object> objects;
...
}

ClassCastException error when casting back to original class

I have the following code:
public void doJob() {
MyObj s;
for ( Object o : MyObj.all().fetch()) {
s = (MyObj) o; // ClassCastException here
if (!s.fileExists()) {
//Do some stuff
}
}
}
which is throwing this exception:
play.exceptions.JavaExecutionException: models.MyObj cannot be cast to models.MyObj
at play.jobs.Job.call(Job.java:155)
at Invocation.Job(Play!)
Caused by: java.lang.ClassCastException: models.MyObj cannot be cast to models.MyObj
at jobs.OrphanSurveys.doJob(OrphanSurveys.java:18)
at play.jobs.Job.doJobWithResult(Job.java:50)
at play.jobs.Job.call(Job.java:146)
... 1 more
(This method runs inside a Play Job class, if that matters.)
The MyObj.all().fetch() is returning an Iterable of some kind containing all of the MyObj objects in the database. MyObj inherits this method from the Play! Framework's Model class, if that matters. That's why it's returning a list of Objects rather than MyObjs, and I can't change how it works.
So, is there some reason that I can't cast back to MyObj? I can see how there would be some weirdness casting back from an Object, but Java seems to know what the class of the object used to be.
Thanks!
It looks like you have ClassLoader issues. The objects being returned by your fetch() method were loaded in a different ClassLoader than the one being used in the current thread to try and cast.
Try this to confirm. Add the three lines of code to your exising code.
for ( Object o : MyObj.all().fetch()) {
// Check classloaders
System.out.println(o.getClass().getClassLoader());
System.out.println(MyObj.class.getClassLoader());
break;
//
s = (MyObj) o; // ClassCastException here
if (!s.fileExists()) {
//Do some stuff
}
}
I saw a recent post here on StackOverflow that indicated that if two otherwise identical instances of the same class are loaded by different classloaders, you cannot cast between them.
Post in question
Check whether you are not subject to the multiple classloader condition here too.
From your stack trace, apparently, there's some other kinds of entries in your collection.
Use o.getClass().getName() inside your loop to know what is .all().fetch() really returning.
Note: Maybe some model.Survey objects?

Categories