Java tutorial
/** * Copyright 2012 the project-owners * * 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. */ package inti.util; import static org.junit.Assert.assertEquals; import java.nio.ByteBuffer; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import org.junit.Test; public class Base64OutputByteBufferTest { Charset UTF_8 = Charset.forName("utf-8"); Base64OutputByteBuffer base64OutputByteBuffer; @Test public void writeSmallDataSmallBuffer() throws Exception { writeSmallDataSmallBuffer("0"); writeSmallDataSmallBuffer("01"); writeSmallDataSmallBuffer("012"); writeSmallDataSmallBuffer("0123"); writeSmallDataSmallBuffer("01234"); writeSmallDataSmallBuffer("012345"); writeSmallDataSmallBuffer("0123456"); writeSmallDataSmallBuffer("01234567"); writeSmallDataSmallBuffer("012345678"); writeSmallDataSmallBuffer("0123456789"); } public void writeSmallDataSmallBuffer(String str) throws Exception { byte[] data = new String(str).getBytes(UTF_8); int bufferSize = 32; ByteBuffer buffer; base64OutputByteBuffer = new Base64OutputByteBuffer(Base64OutputByteBuffer.DEFAULT_ALPHABET, Base64OutputByteBuffer.DEFAULT_PADDING, bufferSize); base64OutputByteBuffer.write(data); base64OutputByteBuffer.flush(); buffer = base64OutputByteBuffer.getByteBuffer(); assertEquals(new Base64().encodeAsString(data), new String(buffer.array()).trim()); base64OutputByteBuffer = new Base64OutputByteBuffer(Base64OutputByteBuffer.DEFAULT_ALPHABET, Base64OutputByteBuffer.DEFAULT_PADDING, bufferSize); for (int i = 0; i < data.length; i++) { base64OutputByteBuffer.write(data[i]); } base64OutputByteBuffer.flush(); buffer = base64OutputByteBuffer.getByteBuffer(); assertEquals(new Base64().encodeAsString(data), new String(buffer.array()).trim()); if (data.length % 2 == 0) { base64OutputByteBuffer = new Base64OutputByteBuffer(Base64OutputByteBuffer.DEFAULT_ALPHABET, Base64OutputByteBuffer.DEFAULT_PADDING, bufferSize); for (int i = 0; i < data.length; i += 2) { base64OutputByteBuffer.write(new byte[] { data[i], data[i + 1] }); } base64OutputByteBuffer.flush(); buffer = base64OutputByteBuffer.getByteBuffer(); assertEquals(new Base64().encodeAsString(data), new String(buffer.array()).trim()); } } }