| 33 | import org.apache.commons.io.input.ClassLoaderObjectInputStream; |
| 34 | |
| 35 | public class ObjectSerializer { |
| 36 | |
| 37 | public static String serialize(Serializable obj) throws IOException { |
| 38 | if (obj == null) |
| 39 | return ""; |
| 40 | try { |
| 41 | ByteArrayOutputStream serialObj = new ByteArrayOutputStream(); |
| 42 | Deflater def = new Deflater(Deflater.BEST_COMPRESSION); |
| 43 | ObjectOutputStream objStream = new ObjectOutputStream(new DeflaterOutputStream( |
| 44 | serialObj, def)); |
| 45 | objStream.writeObject(obj); |
| 46 | objStream.close(); |
| 47 | return encodeBytes(serialObj.toByteArray()); |
| 48 | } catch (Exception e) { |
| 49 | throw new IOException("Serialization error: " + e.getMessage(), e); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | public static Object deserialize(String str) throws IOException { |
| 54 | if (str == null || str.length() == 0) |
| 55 | return null; |
| 56 | ObjectInputStream objStream = null; |
| 57 | try { |
| 58 | ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str)); |
| 59 | objStream = new ClassLoaderObjectInputStream(Thread.currentThread().getContextClassLoader(), new InflaterInputStream(serialObj)); |
| 60 | return objStream.readObject(); |
| 61 | } catch (Exception e) { |
| 62 | throw new IOException("Deserialization error: " + e.getMessage(), e); |
| 63 | } finally { |
| 64 | IOUtils.closeQuietly(objStream); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | public static String encodeBytes(byte[] bytes) throws UnsupportedEncodingException { |
| 69 | return bytes == null ? null : new String(Base64.encodeBase64(bytes), Charset.forName("UTF-8")); |
| 70 | } |
| 71 | |
| 72 | public static byte[] decodeBytes(String str) throws UnsupportedEncodingException { |
| 73 | return Base64.decodeBase64(str.getBytes(Charset.forName("UTF-8"))); |
| 74 | } |
| 75 | } |
nothing calls this directly
no outgoing calls
no test coverage detected