Base64Util.java

/*
 * Copyright (C) 2012-2024 RRiBbit.org
 *
 * 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
 *
 * https://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 org.rribbit.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Base64;

import org.rribbit.dispatching.HttpRequestDispatcher;
import org.rribbit.processing.HttpRequestProcessorServlet;

/**
 * This class provides utility methods for Base64 encoding. It is used by the {@link HttpRequestDispatcher} and {@link HttpRequestProcessorServlet}, but feel free to use it yourself.
 *
 * @author G.J. Schouten
 *
 */
public final class Base64Util {

	/**
	 * This class should not be instantiated.
	 */
	private Base64Util() {}
	/**
	 * Encodes a Java {@link Object} to a Base64 encoded String.
	 *
	 * @param object	The {@link Object} to be encoded
	 * @return			The Base64 encoded {@link String} that represents the {@link Object}
	 */
	public static String encodeObject(Object object) throws IOException {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		OutputStream b64os = Base64.getEncoder().wrap(baos);
		ObjectOutputStream oos = new ObjectOutputStream(b64os);
		oos.writeObject(object);

		oos.flush();
		b64os.flush();
		baos.flush();

		//Try - finally not necessary, because once this Thread has ended, all these objects will be garbage collected anyway
		oos.close();
		b64os.close();
		baos.close();

		return baos.toString();
	}

	/**
	 * Decodes an {@link InputStream} that contains a Base64 encoded String to a Java {@link Object}.
	 *
	 * @param inputStream	The {@link InputStream} that contains a Base64 encoded {@link String}
	 * @return				The {@link Object} represented by the Base64 encoded {@link String}
	 */
	public static <T> T decodeInputStream(InputStream inputStream) throws IOException, ClassNotFoundException {

		InputStream b64is = Base64.getDecoder().wrap(inputStream);
		ObjectInputStream ois = new ObjectInputStream(b64is);
		return (T) ois.readObject();
	}
}