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;
022
023/**
024 * A Base 64 encoding implementation.
025 * @author Florian Schmaus
026 */
027public final class Java7Base64Encoder implements org.jivesoftware.smack.util.stringencoder.Base64.Encoder {
028
029    private static final Java7Base64Encoder instance = new Java7Base64Encoder();
030
031    private static final int BASE64_ENCODER_FLAGS =  Base64.DONT_BREAK_LINES;
032
033    private Java7Base64Encoder() {
034        // Use getInstance()
035    }
036
037    public static Java7Base64Encoder getInstance() {
038        return instance;
039    }
040
041    @Override
042    public byte[] decode(String string) {
043        return Base64.decode(string);
044    }
045
046    @Override
047    public byte[] decode(byte[] input, int offset, int len) {
048        return Base64.decode(input, offset, len, 0);
049    }
050
051    @Override
052    public String encodeToString(byte[] input, int offset, int len) {
053        return Base64.encodeBytes(input, offset, len, BASE64_ENCODER_FLAGS);
054    }
055
056    @Override
057    public byte[] encode(byte[] input, int offset, int len) {
058        String string = encodeToString(input, offset, len);
059        try {
060            return string.getBytes(StringUtils.USASCII);
061        } catch (UnsupportedEncodingException e) {
062            throw new AssertionError(e);
063        }
064    }
065
066}