001/**
002 *
003 * Copyright the original author or authors
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.util.stringencoder.java7;
018
019import java.io.UnsupportedEncodingException;
020
021import org.jivesoftware.smack.util.StringUtils;
022import org.jivesoftware.smack.util.stringencoder.StringEncoder;
023
024
025/**
026 * A Base 64 encoding implementation that generates filename and Url safe encodings.
027 *
028 * <p>
029 * Note: This does NOT produce standard Base 64 encodings, but a variant as defined in
030 * Section 4 of RFC3548:
031 * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
032 * </p>
033 *
034 * @author Robin Collier
035 */
036public final class Java7Base64UrlSafeEncoder implements StringEncoder {
037
038    private static final Java7Base64UrlSafeEncoder instance = new Java7Base64UrlSafeEncoder();
039
040    private static final int BASE64_ENCODER_FLAGS =  Base64.URL_SAFE | Base64.DONT_BREAK_LINES;
041
042    private Java7Base64UrlSafeEncoder() {
043        // Use getInstance()
044    }
045
046    public static Java7Base64UrlSafeEncoder getInstance() {
047        return instance;
048    }
049
050    @Override
051    public String encode(String s) {
052        byte[] bytes;
053        try {
054            bytes = s.getBytes(StringUtils.UTF8);
055        }
056        catch (UnsupportedEncodingException e) {
057            throw new AssertionError(e);
058        }
059        return Base64.encodeBytes(bytes, BASE64_ENCODER_FLAGS);
060    }
061
062    @Override
063    public String decode(String s) {
064        try {
065            return new String(Base64.decode(s, BASE64_ENCODER_FLAGS), StringUtils.UTF8);
066        }
067        catch (UnsupportedEncodingException e) {
068            throw new AssertionError(e);
069        }
070    }
071
072}