1 /* 2 * Copyright (C) 2012-2024 RRiBbit.org 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package org.rribbit.util; 17 18 import java.io.ByteArrayOutputStream; 19 import java.io.IOException; 20 import java.io.InputStream; 21 import java.io.ObjectInputStream; 22 import java.io.ObjectOutputStream; 23 import java.io.OutputStream; 24 import java.util.Base64; 25 26 import org.rribbit.dispatching.HttpRequestDispatcher; 27 import org.rribbit.processing.HttpRequestProcessorServlet; 28 29 /** 30 * 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. 31 * 32 * @author G.J. Schouten 33 * 34 */ 35 public final class Base64Util { 36 37 /** 38 * This class should not be instantiated. 39 */ 40 private Base64Util() {} 41 /** 42 * Encodes a Java {@link Object} to a Base64 encoded String. 43 * 44 * @param object The {@link Object} to be encoded 45 * @return The Base64 encoded {@link String} that represents the {@link Object} 46 */ 47 public static String encodeObject(Object object) throws IOException { 48 49 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 50 OutputStream b64os = Base64.getEncoder().wrap(baos); 51 ObjectOutputStream oos = new ObjectOutputStream(b64os); 52 oos.writeObject(object); 53 54 oos.flush(); 55 b64os.flush(); 56 baos.flush(); 57 58 //Try - finally not necessary, because once this Thread has ended, all these objects will be garbage collected anyway 59 oos.close(); 60 b64os.close(); 61 baos.close(); 62 63 return baos.toString(); 64 } 65 66 /** 67 * Decodes an {@link InputStream} that contains a Base64 encoded String to a Java {@link Object}. 68 * 69 * @param inputStream The {@link InputStream} that contains a Base64 encoded {@link String} 70 * @return The {@link Object} represented by the Base64 encoded {@link String} 71 */ 72 public static <T> T decodeInputStream(InputStream inputStream) throws IOException, ClassNotFoundException { 73 74 InputStream b64is = Base64.getDecoder().wrap(inputStream); 75 ObjectInputStream ois = new ObjectInputStream(b64is); 76 return (T) ois.readObject(); 77 } 78 }