Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intermittent ClassCastException from ElementNSImpl to own type during unmarshalling

We are experiencing an exceedingly hard to track down issue where we are seeing ClassCastExceptions sometimes when trying to iterate over a list of unmarshalled objects. The important bit is sometimes, after a reboot the particular code works fine. This seems to point in the direction of concurrency/timing/race condition. I can confirm that neither the JAXBContext, nor the marshallers and unmarshallers are being used concurrently. We've gone as far as serializing access to them through locking.

However, since we run on an OSGi platform where individual bundles are getting initialized asynchronously through Spring DM it can be that 2 different bundles are creating their JAXBContext at the same time.

In any case I would appreciate any pointers towards an explanation for what could cause these intermittent ClassCastExceptions. The intermittent is important since they indicate that the code itself is normally working fine but that some external factor seems to influence the behaviour.

Here's a specific example of the exception (note I removed the company specific stuff):

Caused by: java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to com.foobar.TunnelType
    at com.foobar.NetMonitorImpl.getVpnStatus(NetMonitorImpl.java:180)

That method at line 180 is a for() construct looping over a Collection of TunnelType objects inside of an unmarshalled object (said unmarshalling works fine BTW).

Given that the actual object unmarshalling went fine, is it even physically possible for JAXB to leave ElementNSImpl objects inside of nested collections?

Runtime environment:

  • JAXB 2.1
  • OSGi
  • Spring DM
  • The JAXBContext is initialised with the ClassLoader of the bundle containing the classes to be marshalled/unmarshalled
like image 656
Boris Terzic Avatar asked Dec 18 '08 13:12

Boris Terzic


2 Answers

I get this exception ONLY when I forget to tell JAXBContext about ALL to-be-marshalled types it could be dealing with.

JAXBContext.newInstance(MyClass1.class,MyClass2.class, [...]);
like image 161
ivan_ivanovich_ivanoff Avatar answered Nov 13 '22 16:11

ivan_ivanovich_ivanoff


Neither of the approaches suggested here did it for me. However this resolved my problem

@XmlAnyElement(lax = true)
public List<Foo> foos;
like image 25
Johan Sjöberg Avatar answered Nov 13 '22 18:11

Johan Sjöberg