Search code examples
xmlsoapcxf

How to pad an xsd:decimal with zeros?


We are using CXF to speak to an external SOAP interface with a bit of a weird bahviour. The interface expects xsd:decimal to be left padded with zeros up to 15 digits. So 23 will become 000000000000023.

How can I achieve this padding with CXF?


Solution

  • Solved it myself. I created an XmlJavaTypeAdapter for this, which I then use via the @XmlJavaTypeAdapter annotation.

    public class XmlDecimalAdapter extends XmlAdapter< String, BigDecimal > 
    {
    
       ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    
       @Override
       public String marshal( BigDecimal value ) throws Exception
       {
          final String  stringRepresentation = value.toString();
    
          if( value.compareTo( BigDecimal.ZERO ) < 0 ){
             String result = "-00000000000000";
             return result.substring( 0, result.length() - stringRepresentation.length() + 1 ) + stringRepresentation.substring( 1 );
          }
          String result = "000000000000000";
          return result.substring( 0, result.length() - stringRepresentation.length() ) + stringRepresentation;
       }
    
       ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    
       @Override
       public BigDecimal unmarshal( String value ) throws Exception
       {
          if( value.equals( "000000000000000" ) ){
             return BigDecimal.ZERO;
          }   
          if( value.startsWith( "-")  ){
             return new BigDecimal( value.replaceFirst( "^-0*", "-" ) );         
          }
          return new BigDecimal( value.replaceFirst( "^0*", "" ) );         
       }
    }