// Copyright (c) Keith D Gregory, all rights reserved
package com.kdgregory.example.serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.File;
import java.util.jar.JarFile;

public class CustomSerializationExample
{
    public static void main(String[] argv)
    throws Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        UnserializableObject obj = new UnserializableObject("example", findRtJar());
        oos.writeObject(obj);
        oos.close();

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);

        UnserializableObject ret = (UnserializableObject)ois.readObject();
        System.out.println("no exception means success: " + ret.getJar().getManifest().getEntries().size());
    }


    /**
     *  Attempts to find rt.jar. This is used because it's available in every
     *  Java installation.
     */
    public static JarFile findRtJar()
    throws IOException
    {
        File javaHome = new File(System.getProperty("java.home"));
        File rtJar = new File(new File(javaHome, "lib"), "rt.jar");
        if (! rtJar.exists())
            throw new RuntimeException("unable to find rt.jar in expected place: " + rtJar);

        return new JarFile(rtJar);
    }
}
