i am trying to combine JAXB (as provided in the dom4j by Hibernate), Hibernate (4.1.3) and Eclipse (4.2) plug ins.
My "core" plugin contains a XMLUserType that takes a given pojo (annotated with @XmlRootElement and the rest; from another plug in) and converts it into an XML and vice versa. Unmarshalling works fine with this code (the cls is the class as given per string by a parameter:
public Object fromXMLString(final String xml) {
if (null != xml) {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(cls.getClassLoader());
final JAXBContext jc = JAXBContext.newInstance(cls);
final Unmarshaller unmarshaller = jc.createUnmarshaller();
final StreamSource sr = new StreamSource(new StringReader(xml));
final JAXBElement<?> element = unmarshaller.unmarshal(sr, cls);
return cls.cast(element.getValue());
} catch (final JAXBException e) {
e.printStackTrace();
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
return null;
}
/** {@inheritDoc} */
@Override
public void setParameterValues(final Properties parameters) {
final String clsName = (String) parameters.get("ClassType");
try {
this.cls = Thread.currentThread().getContextClassLoader().loadClass(clsName);
} catch (final ClassNotFoundException e) {
e.printStackTrace();
}
}
unfortunately marshaling just fails and i have no clue why.
public static Document convertToXML(final Object pojo, final Class<?> type) throws SystemException {
Document ret = null;
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(type.getClassLoader());
final JAXBContext jc = JAXBContext.newInstance(type);
final Marshaller marshaller = jc.createMarshaller();
final DocumentResult dr = new DocumentResult();
marshaller.marshal(pojo, dr);
final Document document = dr.getDocument();
ret = document;
} catch (final JAXBException e) {
e.printStackTrace();
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
return ret;
}
It doesn't matter whether or not the ClassLoader is set. It always fails with this exception:
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type
"packagingdetails.PackagingDetails" as an element because it is missing an
@XmlRootElement annotation
I believe that the reason is either one of this reasons: 1. The annotations are represented by proxies and can therefore not be resolved 2. The ClassLoader makes trouble...
Regarding 1.: I noticed that
final Annotation[] annotations = type.getAnnotations();
XmlRootElement xmlRootElement = null;
for (final Annotation a : annotations) {
if (XmlRootElement.class.isAssignableFrom(a.annotationType())) {
xmlRootElement = (XmlRootElement) a;
break;
}
}
always fails (i tried to use that to get the name of the XmlRootElement to create a JAXBElement, but this seems not to be feasible...; my JAXBType should remain generic)...
Has anyone any Ideas???
Thanks Matthias