Wednesday, August 13, 2014

Web Services and DataTypes, Base64Encoding

I have seen many Web Service implementations where developers created their own classes to convert between different data types or they imported third party library just to base64 encode a bunch of text. Well in case you have to convert between some exotic data types there is no other way, but for the most purposes the javax.xml.bind.DatatypeConverter will be just fine. It has many printXXX and  parseXXX methods - for example:
public static boolean parseBoolean(String lexicalXSDBoolean)
public static String printBoolean(boolean val). 
As documentation says, this class has been available since JAXB 1.0, so you can find it even it Java EE5. May the god bless you if you are still dying with Java 1.4 :).
The DatatypeConverter class has also one very important feature: it "knows" how to base64 encode and decode text - the functions are:
public static byte[] parseBase64Binary(String lexicalXSDBase64Binary)
public static String printBase64Binary(byte[] val)
So with this class you can avoid using  third party libraries (such as Apache Commons) or sun.misc.BASE64Encoder and sun.misc.BASE64Decoder classes which have been deprecated for many years. Not to mention that using deprecated classes is considered as a bad practice. For the end I must mention that JDK 8 have brought us the official base64 encoder class java.util.Base64.
If you strive for the best code possible try to use classes mentioned above and let sun.misc.* class retire. They served us well :).

1 comment: