1 /*
2 * Copyright (C) 2012-2025 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 org.rribbit.dispatching.HttpRequestDispatcher;
19 import org.rribbit.processing.HttpRequestProcessorServlet;
20
21 import java.io.*;
22 import java.util.Base64;
23
24 /**
25 * 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.
26 *
27 * @author G.J. Schouten
28 *
29 */
30 public final class Base64Util {
31
32 /**
33 * This class should not be instantiated.
34 */
35 private Base64Util() {}
36 /**
37 * Encodes a Java {@link Object} to a Base64 encoded String.
38 *
39 * @param object The {@link Object} to be encoded
40 * @return The Base64 encoded {@link String} that represents the {@link Object}
41 */
42 public static String encodeObject(Object object) throws IOException {
43
44 ByteArrayOutputStream baos = new ByteArrayOutputStream();
45 OutputStream b64os = Base64.getEncoder().wrap(baos);
46 ObjectOutputStream oos = new ObjectOutputStream(b64os);
47 oos.writeObject(object);
48
49 oos.flush();
50 b64os.flush();
51 baos.flush();
52
53 //Try - finally not necessary, because once this Thread has ended, all these objects will be garbage collected anyway
54 oos.close();
55 b64os.close();
56 baos.close();
57
58 return baos.toString();
59 }
60
61 /**
62 * Decodes an {@link InputStream} that contains a Base64 encoded String to a Java {@link Object}.
63 *
64 * @param inputStream The {@link InputStream} that contains a Base64 encoded {@link String}
65 * @return The {@link Object} represented by the Base64 encoded {@link String}
66 */
67 public static <T> T decodeInputStream(InputStream inputStream) throws IOException, ClassNotFoundException {
68
69 InputStream b64is = Base64.getDecoder().wrap(inputStream);
70 ObjectInputStream ois = new ObjectInputStream(b64is);
71 return (T) ois.readObject();
72 }
73 }