Sunday, October 5, 2008

GDuration & Duration manipulation

There is a lot of difference between the Java Bean generated for xsd:duration using Apache xbean.jar and Weblogic weblogic ant target jwsc/wsdlc.

While the Apache translates it to org.apache.xmlbeans.GDuration, Weblogic translates it to java.lang.String. Since a String can be anything, it is recommended to use the toString() method in Java XML datatype API javax.xml.datatype.Duration to have consistent behaviour.

So, if there is a requirement to have both the xml beans, then create javax.xml.datatype.Duration using any of the methods present in javax.xml.datatype.DatatypeFactory and then convert it to the required formats.

Duration duration = DatatypeFactory.newInstance().newDuration(durationInMillis);
//for Apache
GDuration gDuration = new GDuration(1, duration.getYears(), duration.getMonths(), duration.getDays(),duration.getHours(),duration.getMinutes(),duration.getSeconds(), null);
//for Weblogic
String s = duration.toString();

Notice that the sign of the duration(positive or negative) is hard-coded as 1(positive). The getSign() method in javax.xml.datatype.Duration returns -1,0,+1. But the passing 0 to the GDuration(int,int,int,int,int,int,int,java.math.BigDecimal) constructor throws an IllegaArgumentException. Also, javax.xml.datatype.Duration does not have a method to return fraction part of the duration unlike the getFraction() method in org.apache.xmlbeans.GDuration.

To get the total number of milliseconds from javax.xml.datatype.Duration, we just need to call either getTimeInMillis(java.util.Calendar)
or getTimeInMillis(java.util.Date). However there is no equivalent API in org.apache.xmlbeans.GDuration.

To get the total number of milliseconds from org.apache.xmlbeans.GDuration, we need to do the following :

GDuration gDuration = new GDuration(durationString);
Calendar cal = Calendar.getInstance();
GDate base = new GDate(cal);
GDate d = base.add(gDuration);
long durationInMillis = d.getDate().getTime();

No comments: