All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kz.greetgo.security.session.Serializer Maven / Gradle / Ivy

There is a newer version: 0.0.12
Show newest version
package kz.greetgo.security.session;

import kz.greetgo.security.errors.SerializedClassChanged;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import static kz.greetgo.security.util.Base64Util.base64ToBytes;
import static kz.greetgo.security.util.Base64Util.bytesToBase64;

public class Serializer {
  public static byte[] serialize(Object object) {
    try {

      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      ObjectOutputStream out = new ObjectOutputStream(bOut);

      out.writeObject(object);

      return bOut.toByteArray();

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static  T deserialize(byte[] bytes) {
    try {

      if (bytes == null) {
        return null;
      }

      ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
      ObjectInputStream in = new ObjectInputStream(bIn);
      //noinspection unchecked
      return (T) in.readObject();

    } catch (RuntimeException e) {
      throw e;
    } catch (InvalidClassException e) {
      throw new SerializedClassChanged(e);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }


  public static String serializeToStr(Object object) {
    return bytesToBase64(serialize(object));
  }

  public static  T deserializeFromStr(String serializedStr) {
    return deserialize(base64ToBytes(serializedStr));
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy