I need to populate a JAX Bean from XML, however there is no setter method. I get the following message below
Failed to invoke public javax.xml.datatype.XMLGregorianCalendar() with no args
I wrote the following methods to take a date and transform it to XMLGregorianCalendar, and then call a setter in my wrapper class. However I still get the exception. Is there a standard way of handling this data type that I am overlooking? Maybe my wrapper class is not calling it, but Netbeans won't allow me to attach a debugger to it for some reason.
public XMLGregorianCalendar asXMLGregorianCalendar(java.util.Date date) throws DatatypeConfigurationException {
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
if (date == null) {
return null;
} else {
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(date.getTime());
return datatypeFactory.newXMLGregorianCalendar(gc);
}
}
The setter in the Bean is below
public void setDeliveryDate(XMLGregorianCalendar value) {
this.deliveryDate = value;
}
Your sample code shows you trying to populate it with a Date object, while the question itself says you are trying to populate from XML. So unless I misunderstand, to populate from XML just use:
XmlGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(yourXmlDateTimeString);
I would suggest using Joda Time -- The Java Date Api frustrates a lot of developers. If you want to stick with the core libraries, try using a DataTypeFactory.
public static XMLGregorianCalendar asXMLGregorianCalendar(Date date) {
java.util.GregorianCalendar calDate = new java.util.GregorianCalendar();
calDate.setTime(date);
javax.xml.datatype.XMLGregorianCalendar calendar = null;
try {
javax.xml.datatype.DatatypeFactory factory = javax.xml.datatype.DatatypeFactory.newInstance();
calendar = factory.newXMLGregorianCalendar(
calDate.get(java.util.GregorianCalendar.YEAR),
calDate.get(java.util.GregorianCalendar.MONTH) + 1,
calDate.get(java.util.GregorianCalendar.DAY_OF_MONTH),
calDate.get(java.util.GregorianCalendar.HOUR_OF_DAY),
calDate.get(java.util.GregorianCalendar.MINUTE),
calDate.get(java.util.GregorianCalendar.SECOND),
calDate.get(java.util.GregorianCalendar.MILLISECOND), 0);
} catch (DatatypeConfigurationException dce) {
//handle or throw
}
return calendar;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With