Java XML Base64 Encode Decode base64FromString(String value)

Here you can find the source of base64FromString(String value)

Description

Convert the given String to UTF-8, encode the result with Base64, and return the encoded value as a string.

License

Apache License

Parameter

Parameter Description
value Unicode String value.

Return

Base64 encoding of UTF-8 encoded String value.

Declaration

public static String base64FromString(String value) 

Method Source Code

//package com.java2s;
/*/*w ww .j a  va 2  s  . com*/
 * Copyright (C) 2014 Dell, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import javax.xml.bind.DatatypeConverter;

public class Main {
    /**
     * The Charset object for the UTF-8 character set.
     */
    public static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

    /**
     * Convert the given String to UTF-8, encode the result with Base64, and return the
     * encoded value as a string. The result string will only contain valid Base64
     * characters.
     * 
     * @param   value   Unicode String value.
     * @return          Base64 encoding of UTF-8 encoded String value.
     */
    public static String base64FromString(String value) {
        return DatatypeConverter.printBase64Binary(toBytes(value));
    }

    /**
     * Convert the given string to a byte[] in using the {@link #UTF8_CHARSET} encoder.
     * This is the inverse of {@link #toString(byte[])}. A null value is allowed, which
     * begets a null result.
     *
     * @param str   String value to be converted.
     * @return      Lossless, encoded value as a byte[], or null if str is null.
     */
    public static byte[] toBytes(String str) {
        if (str == null) {
            return null;
        }
        //optimization for ascii strings
        byte[] ascii = toAsciiBytes(str);
        if (ascii != null)
            return ascii;

        ByteBuffer bb = UTF8_CHARSET.encode(str);
        return getBytes(bb);
    }

    /**
     * Convert a long to a byte[] using the format Cassandra wants for a column or
     * supercolumn name. The antimethod for this one is {@link #toLong(byte[])}.
     *
     * @param value Long value to be converted.
     * @return      Same value encoded into an byte[8] array.
     */
    public static byte[] toBytes(long value) {
        byte[] bytes = new byte[8];
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.putLong(value);
        return bytes;
    }

    private static byte[] toAsciiBytes(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) > 127)
                return null;
        }
        byte[] bytes = new byte[str.length()];
        for (int i = 0; i < str.length(); i++) {
            bytes[i] = (byte) str.charAt(i);
        }
        return bytes;
    }

    /**
     * Extract the bytes in the given ByteBuffer and return it as a byte[]. CAUTION: this
     * method calls ByteBuffer.get(), which <i>transfers</i> bytes from the ByteBuffer to
     * the result buffer. Hence, it is "destructive" in the sense that the value cannot be
     * examined again without calling ByteBuffer.rewind() or something else. 
     *
     * @param   bytes   ByteBuffer.
     * @return          Contents between 'position' and 'limit' (aka 'remaining') as a
     *                  byte[].
     * @see     #copyBytes(ByteBuffer)
     */
    public static byte[] getBytes(ByteBuffer bytes) {
        byte[] result = new byte[bytes.remaining()]; // bytes between position and limit
        bytes.get(result);
        return result;
    }
}

Related

  1. base64Encode(byte[] bytes)
  2. base64encode(byte[] bytes, boolean pad)
  3. base64Encode(String data)
  4. base64EncodeBasicCredentials(String username, String password)
  5. base64FromBinary(byte[] value)
  6. base64ToByte(String data)
  7. byteArrayToBase64String(byte[] data)
  8. BytesToBase64String(final byte[] value)
  9. byteToBase64(byte[] data)