// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InvalidClassException;
import java.io.IOException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SerTest {
    public static class DataOne implements Serializable {
        private static final long serialVersionUID = 1L;
        private int iv;
        private String sv;
        public DataOne() {
            this(0, "");
        }
        public DataOne(int iv, String sv) {
            this.iv = iv;
            this.sv = sv;
        }
        public int getIv() {
            return iv;
        }
        public void setIv(int iv) {
            this.iv = iv;
        }
        public String getSv() {
            return sv;
        }
        public void setSv(String sv) {
            this.sv = sv;
        }
    }
    public static class DataTwo implements Serializable {
        private static final long serialVersionUID = 1L;
        private byte[] a;
        public DataTwo() {
            this(0);
        }
        public DataTwo(int n) {
            this(new byte[n]);
        }
        public DataTwo(byte[] a) {
            this.a = a;
        }
        public byte[] getA() {
            return a;
        }
        public void setA(byte[] a) {
            this.a = a;
        }
    }
    public static class DataThree implements Serializable {
        private static final long serialVersionUID = 1L;
        private int v;
        public DataThree() {
            this(0);
        }
        public DataThree(int v) {
            this.v = v;
        }
        public int getV() {
            return v;
        }
        public void setV(int v) {
            this.v = v;
        }
        private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException
        {
            System.out.println("Executing DataThree.readObject");
            v = ois.readInt();
        }
        private void writeObject(ObjectOutputStream oos) throws IOException
        {
            System.out.println("Executing DataThree.writeObject");
            oos.writeInt(v);
        }
    }
    public static <T> byte[] serialize(T o) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(o);
        oos.close();
        return baos.toByteArray();
    }
    public static <T> T deserialize(byte[] b) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        ObjectInputStream ois = new ObjectInputStream(bais);
        //ois.setObjectInputFilter(ObjectInputFilter.Config.createFilter("maxarray=1000;maxbytes=10000"));
        ois.setObjectInputFilter(new ObjectInputFilter() {
            public Status checkInput(FilterInfo fi) {
                if(fi.arrayLength() > 1000) {
                    return Status.REJECTED;
                } else if(fi.streamBytes() > 10000) {
                    return Status.REJECTED;
                } else {
                    List<String> methods = new ArrayList<String>();
                    Class<?> clz = fi.serialClass();
                    while(clz != null) {
                        methods.addAll(Arrays.asList(clz.getDeclaredMethods()).stream().map(m -> m.getName()).collect(Collectors.toList()));
                        clz = clz.getSuperclass();
                    }
                    if(methods.contains("readObject")) {
                        return Status.REJECTED;
                    } else {
                        return Status.ALLOWED;
                    }
                }
            }
        });
        @SuppressWarnings("unchecked")
        T o = (T)ois.readObject();
        ois.close();
        return o;
    }
    private static <T> T test(T o) throws ClassNotFoundException, IOException {
        byte[] b = serialize(o);
        byte[] dummy = new byte[50_000_000]; // simulate that serializer has more memory available then deserializer
        return deserialize(b);
    }
    private static void testOne() throws IOException, ClassNotFoundException {
        DataOne one = test(new DataOne(123, "ABC"));
        System.out.println(one.getIv() + " " + one.getSv());
    }
    private static void testTwo(int n) throws IOException, ClassNotFoundException {
        DataTwo two = test(new DataTwo(n));
        System.out.println(two.getA().length);
    }
    private static void testThree() throws IOException, ClassNotFoundException {
        DataThree three = test(new DataThree(123));
        System.out.println(three.getV());
    }
    public static void main(String[] args) throws Exception {
        testOne();
        try {
            testTwo(100);
            testTwo(25_000_000);
        } catch(InvalidClassException ice) {
            System.out.println("Data rejected by deserialization filter");
        } catch(OutOfMemoryError oome) {
            System.out.println("Crashing due to out of memory");
        }
        try {
            testThree();
        } catch(InvalidClassException ice) {
            System.out.println("Data rejected by deserialization filter");
        }
    }
}
