Tuesday, February 12, 2013

Base 64 Encoding with Java without Apache Commons

I cannot take credit for this very useful hack, which I saw in concept several years ago. Any project dealing with web development will eventually find itself needing to pass on base authentication headers, which must be encoded in Base64 format.

Apache Commons Base64 is widely adopted as the de-facto Java standard for that kind of encoding, but for various reasons, I prefer to avoid adding new dependencies unless absolutely necessary or beneficial.

In that sense, here is the technique, with the key aspects highlighted in bold:

---

package com.blogspot.sourcepatch;

import java.util.prefs.AbstractPreferences;
import java.util.prefs.BackingStoreException;

public class Base64 {

    private static final Base64 instance = new Base64();
    private static final Base64Encoder encoder = instance.new Base64Encoder();

    /**
     * @return the base64String
     */
    public static String encode(String s) {
        encoder.putByteArray("akey", s.getBytes());
        String result = encoder.getBase64String();
        return result;
    }

    public class Base64Encoder extends AbstractPreferences {

        private String base64String = null;

        public Base64Encoder() {
            super(null, "");
        }

        protected Base64Encoder(AbstractPreferences parent, String name) {
            super(parent, name);
        }

        @Override
        protected void putSpi(String key, String value) {
            base64String = value;
        }

        /**
         * @return the base64String
         */
        public String getBase64String() {
            return base64String;
        }

        @Override
        protected String getSpi(String key) {
            return null;
        }

        @Override
        protected void removeSpi(String key) {
        }

        @Override
        protected void removeNodeSpi() throws BackingStoreException {
        }

        @Override
        protected String[] keysSpi() throws BackingStoreException {
            return null;
        }

        @Override
        protected String[] childrenNamesSpi() throws BackingStoreException {
            return null;
        }

        @Override
        protected AbstractPreferences childSpi(String name) {
            return null;
        }

        protected void syncSpi() throws BackingStoreException {
        }

        @Override
        protected void flushSpi() throws BackingStoreException {
        }

    }

}

No comments:

Post a Comment