1/*
2 * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/* @test
25 * @bug 4217737
26 * @clean NestedReplace A B C D
27 * @build NestedReplace
28 * @run main NestedReplace
29 * @summary Ensure that replacement objects can nominate their own replacements,
30 *          so long as the replacement is not the same class as the
31 *          just-replaced object.
32 *
33 */
34
35import java.io.*;
36
37class A implements Serializable {
38    Object writeReplace() throws ObjectStreamException {
39        return new B();
40    }
41}
42
43class B implements Serializable {
44    Object writeReplace() throws ObjectStreamException {
45        return new C();
46    }
47}
48
49class C implements Serializable {
50
51    static int writeReplaceCalled = 0;
52
53    Object writeReplace() throws ObjectStreamException {
54        writeReplaceCalled++;
55        return new C();
56    }
57
58    Object readResolve() throws ObjectStreamException {
59        return new D();
60    }
61}
62
63class D implements Serializable {
64    Object readResolve() throws ObjectStreamException {
65        throw new Error("readResolve() called more than once");
66    }
67}
68
69public class NestedReplace {
70    public static void main(String[] args) throws Exception {
71        ByteArrayOutputStream bout;
72        ObjectOutputStream oout;
73        ByteArrayInputStream bin;
74        ObjectInputStream oin;
75        Object obj;
76
77        bout = new ByteArrayOutputStream();
78        oout = new ObjectOutputStream(bout);
79        oout.writeObject(new A());
80        oout.flush();
81        bin = new ByteArrayInputStream(bout.toByteArray());
82        oin = new ObjectInputStream(bin);
83        obj = oin.readObject();
84
85        if (! (obj instanceof D))
86            throw new Error("Deserialized object is of wrong class");
87        if (C.writeReplaceCalled != 1)
88            throw new Error("C.writeReplace() should only get called once");
89    }
90}
91