ObjectOutputStreamTest.java revision 89c1feb0a69a7707b271086e749975b3f7acacf7
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package tests.api.java.io;
19
20import dalvik.annotation.TestInfo;
21import dalvik.annotation.TestLevel;
22import dalvik.annotation.TestTarget;
23import dalvik.annotation.TestTargetClass;
24
25import java.io.ByteArrayInputStream;
26import java.io.ByteArrayOutputStream;
27import java.io.Externalizable;
28import java.io.FileInputStream;
29import java.io.FileOutputStream;
30import java.io.IOException;
31import java.io.NotActiveException;
32import java.io.NotSerializableException;
33import java.io.ObjectInput;
34import java.io.ObjectInputStream;
35import java.io.ObjectOutput;
36import java.io.ObjectOutputStream;
37import java.io.ObjectStreamClass;
38import java.io.ObjectStreamException;
39import java.io.ObjectStreamField;
40import java.io.OutputStream;
41import java.io.Serializable;
42import java.io.SerializablePermission;
43import java.io.WriteAbortedException;
44import java.security.Permission;
45import java.util.Arrays;
46
47@TestTargetClass(ObjectOutputStream.class)
48public class ObjectOutputStreamTest extends junit.framework.TestCase implements
49        Serializable {
50
51    java.io.File f;
52
53    public class SerializableTestHelper implements Serializable {
54        public String aField1;
55
56        public String aField2;
57
58        SerializableTestHelper() {
59            aField1 = null;
60            aField2 = null;
61        }
62
63        SerializableTestHelper(String s, String t) {
64            aField1 = s;
65            aField2 = t;
66        }
67
68        private void readObject(ObjectInputStream ois) throws IOException {
69            // note aField2 is not read
70            try {
71                ObjectInputStream.GetField fields = ois.readFields();
72                aField1 = (String) fields.get("aField1", "Zap");
73            } catch (Exception e) {
74            }
75        }
76
77        private void writeObject(ObjectOutputStream oos) throws IOException {
78            // note aField2 is not written
79            ObjectOutputStream.PutField fields = oos.putFields();
80            fields.put("aField1", aField1);
81            oos.writeFields();
82        }
83
84        public String getText1() {
85            return aField1;
86        }
87
88        public void setText1(String s) {
89            aField1 = s;
90        }
91
92        public String getText2() {
93            return aField2;
94        }
95
96        public void setText2(String s) {
97            aField2 = s;
98        }
99    }
100
101    private static class SerializationTest implements java.io.Serializable {
102        int anInt = INIT_INT_VALUE;
103
104        public SerializationTest() {
105            super();
106        }
107    }
108
109    private static class SerializationTestSubclass1 extends SerializationTest
110            implements Serializable {
111        String aString = INIT_STR_VALUE;
112
113        public SerializationTestSubclass1() {
114            super();
115            // Just to change default superclass init value
116            anInt = INIT_INT_VALUE / 2;
117        }
118    }
119
120    private static class SpecTestSuperClass implements Runnable, Serializable {
121        protected java.lang.String instVar;
122
123        public void run() {
124        }
125    }
126
127    private static class SpecTest extends SpecTestSuperClass implements
128            Cloneable, Serializable {
129        public java.lang.String instVar1;
130
131        public static java.lang.String staticVar1;
132
133        public static java.lang.String staticVar2;
134        {
135            instVar1 = "NonStaticInitialValue";
136        }
137        static {
138            staticVar1 = "StaticInitialValue";
139            staticVar1 = new String(staticVar1);
140        }
141
142        public Object method(Object objParam, Object objParam2) {
143            return new Object();
144        }
145
146        public boolean method(boolean bParam, Object objParam) {
147            return true;
148        }
149
150        public boolean method(boolean bParam, Object objParam, Object objParam2) {
151            return true;
152        }
153
154    }
155
156    private static class SpecTestSubclass extends SpecTest implements
157            Serializable {
158        public transient java.lang.String transientInstVar = "transientValue";
159    }
160
161    private static class ReadWriteObject implements java.io.Serializable {
162        public boolean calledWriteObject = false;
163
164        public boolean calledReadObject = false;
165
166        public ReadWriteObject() {
167            super();
168        }
169
170        private void readObject(java.io.ObjectInputStream in)
171                throws java.io.IOException, ClassNotFoundException {
172            calledReadObject = true;
173            in.readObject();
174        }
175
176        private void writeObject(java.io.ObjectOutputStream out)
177                throws java.io.IOException {
178            calledWriteObject = true;
179            out.writeObject(FOO);
180        }
181    }
182
183    private static class PublicReadWriteObject implements java.io.Serializable {
184        public boolean calledWriteObject = false;
185
186        public boolean calledReadObject = false;
187
188        public PublicReadWriteObject() {
189            super();
190        }
191
192        public void readObject(java.io.ObjectInputStream in)
193                throws java.io.IOException, ClassNotFoundException {
194            calledReadObject = true;
195            in.readObject();
196        }
197
198        public void writeObject(java.io.ObjectOutputStream out)
199                throws java.io.IOException {
200            calledWriteObject = true;
201            out.writeObject(FOO);
202        }
203    }
204
205    private static class FieldOrder implements Serializable {
206        String aaa1NonPrimitive = "aaa1";
207
208        int bbb1PrimitiveInt = 5;
209
210        boolean aaa2PrimitiveBoolean = true;
211
212        String bbb2NonPrimitive = "bbb2";
213    }
214
215    private static class JustReadObject implements java.io.Serializable {
216        public boolean calledReadObject = false;
217
218        public JustReadObject() {
219            super();
220        }
221
222        private void readObject(java.io.ObjectInputStream in)
223                throws java.io.IOException, ClassNotFoundException {
224            calledReadObject = true;
225            in.defaultReadObject();
226        }
227    }
228
229    private static class JustWriteObject implements java.io.Serializable {
230        public boolean calledWriteObject = false;
231
232        public JustWriteObject() {
233            super();
234        }
235
236        private void writeObject(java.io.ObjectOutputStream out)
237                throws java.io.IOException, ClassNotFoundException {
238            calledWriteObject = true;
239            out.defaultWriteObject();
240        }
241    }
242
243    private static class ClassBasedReplacementWhenDumping implements
244            java.io.Serializable {
245        public boolean calledReplacement = false;
246
247        public ClassBasedReplacementWhenDumping() {
248            super();
249        }
250
251        private Object writeReplace() {
252            calledReplacement = true;
253            return FOO; // Replacement is a String
254        }
255    }
256
257    private static class MultipleClassBasedReplacementWhenDumping implements
258            java.io.Serializable {
259        private static class C1 implements java.io.Serializable {
260            private Object writeReplace() {
261                return new C2();
262            }
263        }
264
265        private static class C2 implements java.io.Serializable {
266            private Object writeReplace() {
267                return new C3();
268            }
269        }
270
271        private static class C3 implements java.io.Serializable {
272            private Object writeReplace() {
273                return FOO;
274            }
275        }
276
277        public MultipleClassBasedReplacementWhenDumping() {
278            super();
279        }
280
281        private Object writeReplace() {
282            return new C1();
283        }
284    }
285
286    private static class ClassBasedReplacementWhenLoading implements
287            java.io.Serializable {
288        public ClassBasedReplacementWhenLoading() {
289            super();
290        }
291
292        private Object readResolve() {
293            return FOO; // Replacement is a String
294        }
295    }
296
297    private static class ClassBasedReplacementWhenLoadingViolatesFieldType
298            implements java.io.Serializable {
299        public ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
300
301        public ClassBasedReplacementWhenLoadingViolatesFieldType() {
302            super();
303        }
304    }
305
306    private static class MyExceptionWhenDumping implements java.io.Serializable {
307        private static class MyException extends java.io.IOException {
308        };
309
310        public boolean anInstanceVar = false;
311
312        public MyExceptionWhenDumping() {
313            super();
314        }
315
316        private void readObject(java.io.ObjectInputStream in)
317                throws java.io.IOException, ClassNotFoundException {
318            in.defaultReadObject();
319        }
320
321        private void writeObject(java.io.ObjectOutputStream out)
322                throws java.io.IOException, ClassNotFoundException {
323            throw new MyException();
324        }
325    }
326
327    private static class NonSerializableExceptionWhenDumping implements
328            java.io.Serializable {
329        public Object anInstanceVar = new Object();
330
331        public NonSerializableExceptionWhenDumping() {
332            super();
333        }
334    }
335
336    private static class MyUnserializableExceptionWhenDumping implements
337            java.io.Serializable {
338        private static class MyException extends java.io.IOException {
339            private Object notSerializable = new Object();
340        };
341
342        public boolean anInstanceVar = false;
343
344        public MyUnserializableExceptionWhenDumping() {
345            super();
346        }
347
348        private void readObject(java.io.ObjectInputStream in)
349                throws java.io.IOException, ClassNotFoundException {
350            in.defaultReadObject();
351        }
352
353        private void writeObject(java.io.ObjectOutputStream out)
354                throws java.io.IOException, ClassNotFoundException {
355            throw new MyException();
356        }
357    }
358
359    private static class WithUnmatchingSerialPersistentFields implements
360            java.io.Serializable {
361        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
362                "value", String.class) };
363
364        public int anInstanceVar = 5;
365
366        public WithUnmatchingSerialPersistentFields() {
367            super();
368        }
369    }
370
371    private static class WithMatchingSerialPersistentFields implements
372            java.io.Serializable {
373        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
374                "anInstanceVar", String.class) };
375
376        public String anInstanceVar = FOO + FOO;
377
378        public WithMatchingSerialPersistentFields() {
379            super();
380        }
381    }
382
383    private static class SerialPersistentFields implements java.io.Serializable {
384        private static final String SIMULATED_FIELD_NAME = "text";
385
386        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
387                SIMULATED_FIELD_NAME, String.class) };
388
389        public int anInstanceVar = 5;
390
391        public SerialPersistentFields() {
392            super();
393        }
394
395        private void readObject(java.io.ObjectInputStream in)
396                throws java.io.IOException, ClassNotFoundException {
397            ObjectInputStream.GetField fields = in.readFields();
398            anInstanceVar = Integer.parseInt((String) fields.get(
399                    SIMULATED_FIELD_NAME, "-5"));
400        }
401
402        private void writeObject(java.io.ObjectOutputStream out)
403                throws java.io.IOException, ClassNotFoundException {
404            ObjectOutputStream.PutField fields = out.putFields();
405            fields.put(SIMULATED_FIELD_NAME, Integer.toString(anInstanceVar));
406            out.writeFields();
407        }
408    }
409
410    private static class WriteFieldsWithoutFetchingPutFields implements
411            java.io.Serializable {
412        private static final String SIMULATED_FIELD_NAME = "text";
413
414        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
415                SIMULATED_FIELD_NAME, String.class) };
416
417        public int anInstanceVar = 5;
418
419        public WriteFieldsWithoutFetchingPutFields() {
420            super();
421        }
422
423        private void readObject(java.io.ObjectInputStream in)
424                throws java.io.IOException, ClassNotFoundException {
425            in.readFields();
426        }
427
428        private void writeObject(java.io.ObjectOutputStream out)
429                throws java.io.IOException, ClassNotFoundException {
430            out.writeFields();
431        }
432    }
433
434    private static class SerialPersistentFieldsWithoutField implements
435            java.io.Serializable {
436        public int anInstanceVar = 5;
437
438        public SerialPersistentFieldsWithoutField() {
439            super();
440        }
441
442        private void readObject(java.io.ObjectInputStream in)
443                throws java.io.IOException, ClassNotFoundException {
444            in.readFields();
445        }
446
447        private void writeObject(java.io.ObjectOutputStream out)
448                throws java.io.IOException, ClassNotFoundException {
449            out.putFields();
450            out.writeFields();
451        }
452    }
453
454    private static class NotSerializable {
455        private int foo;
456
457        public NotSerializable() {
458        }
459
460        protected Object writeReplace() throws ObjectStreamException {
461            return new Integer(42);
462        }
463    }
464
465    private static class WriteReplaceObject implements Serializable {
466        private Object replaceObject;
467
468        private static enum Color {
469            red, blue, green
470        };
471
472        public WriteReplaceObject(Object o) {
473            replaceObject = o;
474        }
475
476        protected Object writeReplace() throws ObjectStreamException {
477            return replaceObject;
478        }
479    }
480
481    private static class ExternalizableWithReplace implements Externalizable {
482        private int foo;
483
484        public ExternalizableWithReplace() {
485        }
486
487        protected Object writeReplace() throws ObjectStreamException {
488            return new Integer(42);
489        }
490
491        public void writeExternal(ObjectOutput out) {
492        }
493
494        public void readExternal(ObjectInput in) {
495        }
496    }
497
498    private static class ObjectOutputStreamWithReplace extends ObjectOutputStream {
499        public ObjectOutputStreamWithReplace(OutputStream out) throws IOException {
500            super(out);
501            enableReplaceObject(true);
502        }
503
504        protected Object replaceObject(Object obj) throws IOException {
505            if (obj instanceof NotSerializable) {
506                return new Long(10);
507            } else if (obj instanceof Integer) {
508                return new Long(((Integer) obj).longValue());
509            } else {
510                return obj;
511            }
512        }
513    }
514
515    private static class ObjectOutputStreamWithReplace2 extends
516            ObjectOutputStream {
517        public ObjectOutputStreamWithReplace2(OutputStream out)
518                throws IOException {
519            super(out);
520            enableReplaceObject(true);
521        }
522
523        protected Object replaceObject(Object obj) throws IOException {
524            return new Long(10);
525        }
526    }
527
528    protected static final String MODE_XLOAD = "xload";
529
530    protected static final String MODE_XDUMP = "xdump";
531
532    static final String FOO = "foo";
533
534    static final String MSG_WITE_FAILED = "Failed to write: ";
535
536    private static final boolean DEBUG = false;
537
538    protected static boolean xload = false;
539
540    protected static boolean xdump = false;
541
542    protected static String xFileName = null;
543
544    protected ObjectInputStream ois;
545
546    protected ObjectOutputStream oos;
547
548    protected ByteArrayOutputStream bao;
549
550    static final int INIT_INT_VALUE = 7;
551
552    static final String INIT_STR_VALUE = "a string that is blortz";
553
554    /**
555     * @tests java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
556     */
557    @TestInfo(
558            level = TestLevel.PARTIAL,
559            purpose = "Exceptions checking missed.",
560            targets = { @TestTarget(methodName = "ObjectOutputStream",
561                                    methodArgs = {java.io.OutputStream.class})
562            }
563        )
564    public void test_ConstructorLjava_io_OutputStream() throws IOException {
565        // Test for method java.io.ObjectOutputStream(java.io.OutputStream)
566        oos.close();
567        oos = new ObjectOutputStream(new ByteArrayOutputStream());
568        oos.close();
569    }
570
571    /**
572     * @tests java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
573     */
574    @TestInfo(
575            level = TestLevel.PARTIAL,
576            purpose = "Checks SecurityException. IOException & NullPointerException checking missed.",
577            targets = { @TestTarget(methodName = "ObjectOutputStream",
578                                    methodArgs = {java.io.OutputStream.class})
579            }
580        )
581    public void test_ConstructorLjava_io_OutputStream_subtest0() throws IOException {
582
583        // custom security manager
584        SecurityManager sm = new SecurityManager() {
585
586            final SerializablePermission forbidenPermission =
587                new SerializablePermission("enableSubclassImplementation");
588
589            public void checkPermission(Permission perm) {
590                if (forbidenPermission.equals(perm)) {
591                    throw new SecurityException();
592                }
593            }
594        };
595
596        SecurityManager oldSm = System.getSecurityManager();
597        System.setSecurityManager(sm);
598        try {
599            ByteArrayOutputStream out = new ByteArrayOutputStream();
600            // should not cause SecurityException
601            new ObjectOutputStream(out);
602            // should not cause SecurityException
603            class SubTest1 extends ObjectOutputStream {
604                SubTest1(OutputStream out) throws IOException {
605                    super(out);
606                }
607            }
608
609            // should not cause SecurityException
610            new SubTest1(out);
611            class SubTest2 extends ObjectOutputStream {
612                SubTest2(OutputStream out) throws IOException {
613                    super(out);
614                }
615
616                public void writeUnshared(Object obj) throws IOException {
617                }
618            }
619
620            try {
621                new SubTest2(out);
622                fail("should throw SecurityException 1");
623            } catch (SecurityException e) {
624            }
625            class SubTest3 extends ObjectOutputStream {
626                SubTest3(OutputStream out) throws IOException {
627                    super(out);
628                }
629
630                public PutField putFields() throws IOException {
631                    return null;
632                }
633            }
634
635            try {
636                new SubTest3(out);
637                fail("should throw SecurityException 2");
638            } catch (SecurityException e) {
639            }
640        } finally {
641            System.setSecurityManager(oldSm);
642        }
643    }
644
645    /**
646     * @tests java.io.ObjectOutputStream#close()
647     */
648    @TestInfo(
649            level = TestLevel.PARTIAL,
650            purpose = "IOException checking missed. See tearDown",
651            targets = { @TestTarget(methodName = "close",
652                                    methodArgs = {})
653            }
654        )
655    public void test_close() {
656        // Test for method void java.io.ObjectOutputStream.close()
657    }
658
659    /**
660     * @tests java.io.ObjectOutputStream#defaultWriteObject()
661     */
662    @TestInfo(
663            level = TestLevel.PARTIAL,
664            purpose = "",
665            targets = { @TestTarget(methodName = "defaultWriteObject",
666                                    methodArgs = {})
667            }
668        )
669    public void test_defaultWriteObject() throws IOException {
670        // Test for method void java.io.ObjectOutputStream.defaultWriteObject()
671        try {
672            oos.defaultWriteObject();
673            fail("Failed to throw NotActiveException");
674        } catch (NotActiveException e) {
675            // Correct
676        }
677    }
678
679    /**
680     * @tests java.io.ObjectOutputStream#flush()
681     */
682    @TestInfo(
683            level = TestLevel.PARTIAL,
684            purpose = "IOException checking missed.",
685            targets = { @TestTarget(methodName = "flush",
686                                    methodArgs = {})
687            }
688        )
689    public void test_flush() throws Exception {
690        // Test for method void java.io.ObjectOutputStream.flush()
691        int size = bao.size();
692        oos.writeByte(127);
693        assertTrue("Data flushed already", bao.size() == size);
694        oos.flush();
695        assertTrue("Failed to flush data", bao.size() > size);
696        // we don't know how many bytes are actually written for 1
697        // byte, so we test > <before>
698        oos.close();
699        oos = null;
700    }
701
702    /**
703     * @tests java.io.ObjectOutputStream#putFields()
704     */
705    @TestInfo(
706            level = TestLevel.PARTIAL,
707            purpose = "IOException checking missed.",
708            targets = { @TestTarget(methodName = "putFields",
709                                    methodArgs = {})
710            }
711        )
712    public void test_putFields() throws Exception {
713        // Test for method java.io.ObjectOutputStream$PutField
714        // java.io.ObjectOutputStream.putFields()
715
716        SerializableTestHelper sth;
717
718        /*
719         * "SerializableTestHelper" is an object created for these tests with
720         * two fields (Strings) and simple implementations of readObject and
721         * writeObject which simply read and write the first field but not the
722         * second
723         */
724
725        oos.writeObject(new SerializableTestHelper("Gabba", "Jabba"));
726        oos.flush();
727        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
728        sth = (SerializableTestHelper) (ois.readObject());
729        assertEquals("readFields / writeFields failed--first field not set",
730                "Gabba", sth.getText1());
731        assertNull(
732                "readFields / writeFields failed--second field should not have been set",
733                sth.getText2());
734    }
735
736    /**
737     * @tests java.io.ObjectOutputStream#reset()
738     */
739    @TestInfo(
740            level = TestLevel.PARTIAL,
741            purpose = "IOException checking missed.",
742            targets = { @TestTarget(methodName = "reset",
743                                    methodArgs = {})
744            }
745        )
746    public void test_reset() throws Exception {
747        // Test for method void java.io.ObjectOutputStream.reset()
748        String o = "HelloWorld";
749        oos.writeObject(o);
750        oos.writeObject(o);
751        oos.reset();
752        oos.writeObject(o);
753        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
754        ois.close();
755    }
756
757    private static class ExternalTest implements Externalizable {
758        public String value;
759
760        public ExternalTest() {
761        }
762
763        public void setValue(String val) {
764            value = val;
765        }
766
767        public String getValue() {
768            return value;
769        }
770
771        public void writeExternal(ObjectOutput output) {
772            try {
773                output.writeUTF(value);
774            } catch (IOException e) {
775                e.printStackTrace();
776            }
777        }
778
779        public void readExternal(ObjectInput input) {
780            try {
781                value = input.readUTF();
782            } catch (IOException e) {
783                e.printStackTrace();
784            }
785        }
786    }
787
788    /**
789     * @tests java.io.ObjectOutputStream#useProtocolVersion(int)
790     */
791    @TestInfo(
792            level = TestLevel.PARTIAL,
793            purpose = "Exceptions checking missed.",
794            targets = { @TestTarget(methodName = "useProtocolVersion",
795                                    methodArgs = {int.class})
796            }
797        )
798    public void test_useProtocolVersionI() throws Exception {
799        // Test for method void
800        // java.io.ObjectOutputStream.useProtocolVersion(int)
801        oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
802        ExternalTest t1 = new ExternalTest();
803        t1.setValue("hello1");
804        oos.writeObject(t1);
805        oos.close();
806        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
807        ExternalTest t2 = (ExternalTest) ois.readObject();
808        ois.close();
809        assertTrue(
810                "Cannot read/write PROTOCAL_VERSION_1 Externalizable objects: "
811                        + t2.getValue(), t1.getValue().equals(t2.getValue()));
812    }
813
814    /**
815     * @tests java.io.ObjectOutputStream#write(byte[])
816     */
817    @TestInfo(
818            level = TestLevel.PARTIAL,
819            purpose = "IOException checking missed.",
820            targets = { @TestTarget(methodName = "write",
821                                    methodArgs = {byte[].class})
822            }
823        )
824    public void test_write$B() throws Exception {
825        // Test for method void java.io.ObjectOutputStream.write(byte [])
826        byte[] buf = new byte[10];
827        oos.write("HelloWorld".getBytes());
828        oos.close();
829        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
830        ois.read(buf, 0, 10);
831        ois.close();
832        assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
833                10));
834    }
835
836    /**
837     * @tests java.io.ObjectOutputStream#write(byte[], int, int)
838     */
839    @TestInfo(
840            level = TestLevel.PARTIAL,
841            purpose = "IOException checking missed.",
842            targets = { @TestTarget(methodName = "write",
843                                    methodArgs = {byte[].class, int.class, int.class})
844            }
845        )
846    public void test_write$BII() throws Exception {
847        // Test for method void java.io.ObjectOutputStream.write(byte [], int,
848        // int)
849        byte[] buf = new byte[10];
850        oos.write("HelloWorld".getBytes(), 0, 10);
851        oos.close();
852        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
853        ois.read(buf, 0, 10);
854        ois.close();
855        assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
856                10));
857    }
858
859    /**
860     * @tests java.io.ObjectOutputStream#write(int)
861     */
862    @TestInfo(
863            level = TestLevel.PARTIAL,
864            purpose = "IOException checking missed.",
865            targets = { @TestTarget(methodName = "write",
866                                    methodArgs = {int.class})
867            }
868        )
869    public void test_writeI() throws Exception {
870        // Test for method void java.io.ObjectOutputStream.write(int)
871        oos.write('T');
872        oos.close();
873        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
874        assertEquals("Read incorrect byte", 'T', ois.read());
875        ois.close();
876    }
877
878    /**
879     * @tests java.io.ObjectOutputStream#writeBoolean(boolean)
880     */
881    @TestInfo(
882            level = TestLevel.PARTIAL,
883            purpose = "IOException checking missed.",
884            targets = { @TestTarget(methodName = "writeBoolean",
885                                    methodArgs = {boolean.class})
886            }
887        )
888    public void test_writeBooleanZ() throws Exception {
889        // Test for method void java.io.ObjectOutputStream.writeBoolean(boolean)
890        oos.writeBoolean(true);
891        oos.close();
892        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
893        assertTrue("Wrote incorrect byte value", ois.readBoolean());
894    }
895
896    /**
897     * @tests java.io.ObjectOutputStream#writeByte(int)
898     */
899    @TestInfo(
900            level = TestLevel.PARTIAL,
901            purpose = "IOException checking missed.",
902            targets = { @TestTarget(methodName = "writeByte",
903                                    methodArgs = {int.class})
904            }
905        )
906    public void test_writeByteI() throws Exception {
907        // Test for method void java.io.ObjectOutputStream.writeByte(int)
908        oos.writeByte(127);
909        oos.close();
910        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
911        assertEquals("Wrote incorrect byte value", 127, ois.readByte());
912    }
913
914    /**
915     * @tests java.io.ObjectOutputStream#writeBytes(java.lang.String)
916     */
917    @TestInfo(
918            level = TestLevel.PARTIAL,
919            purpose = "IOException checking missed.",
920            targets = { @TestTarget(methodName = "writeBytes",
921                                    methodArgs = {java.lang.String.class})
922            }
923        )
924    public void test_writeBytesLjava_lang_String() throws Exception {
925        // Test for method void
926        // java.io.ObjectOutputStream.writeBytes(java.lang.String)
927        byte[] buf = new byte[10];
928        oos.writeBytes("HelloWorld");
929        oos.close();
930        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
931        ois.readFully(buf);
932        ois.close();
933        assertEquals("Wrote incorrect bytes value", "HelloWorld", new String(
934                buf, 0, 10));
935    }
936
937    /**
938     * @tests java.io.ObjectOutputStream#writeChar(int)
939     */
940    @TestInfo(
941            level = TestLevel.PARTIAL,
942            purpose = "IOException checking missed.",
943            targets = { @TestTarget(methodName = "writeChar",
944                                    methodArgs = {int.class})
945            }
946        )
947    public void test_writeCharI() throws Exception {
948        // Test for method void java.io.ObjectOutputStream.writeChar(int)
949        oos.writeChar('T');
950        oos.close();
951        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
952        assertEquals("Wrote incorrect char value", 'T', ois.readChar());
953    }
954
955    /**
956     * @tests java.io.ObjectOutputStream#writeChars(java.lang.String)
957     */
958    @TestInfo(
959            level = TestLevel.PARTIAL,
960            purpose = "IOException checking missed.",
961            targets = { @TestTarget(methodName = "writeChars",
962                                    methodArgs = {java.lang.String.class})
963            }
964        )
965    public void test_writeCharsLjava_lang_String() throws Exception {
966        // Test for method void
967        // java.io.ObjectOutputStream.writeChars(java.lang.String)
968        int avail = 0;
969        char[] buf = new char[10];
970        oos.writeChars("HelloWorld");
971        oos.close();
972        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
973        // Number of prim data bytes in stream / 2 to give char index
974        avail = ois.available() / 2;
975        for (int i = 0; i < avail; ++i)
976            buf[i] = ois.readChar();
977        ois.close();
978        assertEquals("Wrote incorrect chars", "HelloWorld", new String(buf, 0,
979                10));
980    }
981
982    /**
983     * @tests java.io.ObjectOutputStream#writeDouble(double)
984     */
985    @TestInfo(
986            level = TestLevel.PARTIAL,
987            purpose = "IOException checking missed.",
988            targets = { @TestTarget(methodName = "writeDouble",
989                                    methodArgs = {double.class})
990            }
991        )
992    public void test_writeDoubleD() throws Exception {
993        // Test for method void java.io.ObjectOutputStream.writeDouble(double)
994        oos.writeDouble(Double.MAX_VALUE);
995        oos.close();
996        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
997        assertTrue("Wrote incorrect double value",
998                ois.readDouble() == Double.MAX_VALUE);
999    }
1000
1001    /**
1002     * @tests java.io.ObjectOutputStream#writeFields()
1003     */
1004    @TestInfo(
1005            level = TestLevel.TODO,
1006            purpose = "Dummy test.",
1007            targets = { @TestTarget(methodName = "writeFields",
1008                                    methodArgs = {})
1009            }
1010        )
1011    public void test_writeFields() {
1012        // Test for method void java.io.ObjectOutputStream.writeFields()
1013        assertTrue("Used to test", true);
1014    }
1015
1016    /**
1017     * @tests java.io.ObjectOutputStream#writeFloat(float)
1018     */
1019    @TestInfo(
1020            level = TestLevel.PARTIAL,
1021            purpose = "IOException checking missed.",
1022            targets = { @TestTarget(methodName = "writeFloat",
1023                                    methodArgs = {float.class})
1024            }
1025        )
1026    public void test_writeFloatF() throws Exception {
1027        // Test for method void java.io.ObjectOutputStream.writeFloat(float)
1028        oos.writeFloat(Float.MAX_VALUE);
1029        oos.close();
1030        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
1031        assertTrue("Wrote incorrect double value",
1032                ois.readFloat() == Float.MAX_VALUE);
1033        ois.close();
1034        ois = null;
1035    }
1036
1037    /**
1038     * @tests java.io.ObjectOutputStream#writeInt(int)
1039     */
1040    @TestInfo(
1041            level = TestLevel.PARTIAL,
1042            purpose = "IOException checking missed.",
1043            targets = { @TestTarget(methodName = "writeInt",
1044                                    methodArgs = {int.class})
1045            }
1046        )
1047    public void test_writeIntI() throws Exception {
1048        // Test for method void java.io.ObjectOutputStream.writeInt(int)
1049        oos.writeInt(Integer.MAX_VALUE);
1050        oos.close();
1051        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
1052        assertTrue("Wrote incorrect double value",
1053                ois.readInt() == Integer.MAX_VALUE);
1054        ois.close();
1055    }
1056
1057    /**
1058     * @tests java.io.ObjectOutputStream#writeLong(long)
1059     */
1060    @TestInfo(
1061            level = TestLevel.PARTIAL,
1062            purpose = "IOException checking missed.",
1063            targets = { @TestTarget(methodName = "writeLong",
1064                                    methodArgs = {long.class})
1065            }
1066        )
1067    public void test_writeLongJ() throws Exception {
1068        // Test for method void java.io.ObjectOutputStream.writeLong(long)
1069        oos.writeLong(Long.MAX_VALUE);
1070        oos.close();
1071        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
1072        assertTrue("Wrote incorrect double value",
1073                ois.readLong() == Long.MAX_VALUE);
1074    }
1075
1076    /**
1077     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
1078     */
1079    @TestInfo(
1080            level = TestLevel.COMPLETE,
1081            purpose = "",
1082            targets = { @TestTarget(methodName = "writeObject",
1083                                    methodArgs = {java.lang.Object.class})
1084            }
1085        )
1086    public void test_writeObjectLjava_lang_Object() throws Exception {
1087        // Test for method void
1088        // java.io.ObjectOutputStream.writeObject(java.lang.Object)
1089
1090        Object objToSave = null;
1091        Object objLoaded;
1092
1093        SerialPersistentFieldsWithoutField spf = new SerialPersistentFieldsWithoutField();
1094        final int CONST = -500;
1095        spf.anInstanceVar = CONST;
1096        objToSave = spf;
1097        if (DEBUG)
1098            System.out.println("Obj = " + objToSave);
1099        objLoaded = dumpAndReload(objToSave);
1100        assertTrue(
1101                "serialPersistentFields do not work properly in this implementation",
1102                ((SerialPersistentFieldsWithoutField) objLoaded).anInstanceVar != CONST);
1103
1104    }
1105
1106    /**
1107     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
1108     */
1109    @TestInfo(
1110            level = TestLevel.COMPLETE,
1111            purpose = "",
1112            targets = { @TestTarget(methodName = "writeObject",
1113                                    methodArgs = {java.lang.Object.class})
1114            }
1115        )
1116    public void test_writeObject_NotSerializable() throws Exception {
1117        ObjectOutput out = null;
1118        try {
1119            out = new ObjectOutputStream(new ByteArrayOutputStream());
1120            out.writeObject(new NotSerializable());
1121            fail("Expected NotSerializableException");
1122        } catch (NotSerializableException e) {}
1123        out.writeObject(new ExternalizableWithReplace());
1124    }
1125
1126    /**
1127     * @tests java.io.ObjectOutputStream#writeShort(int)
1128     */
1129    @TestInfo(
1130            level = TestLevel.PARTIAL,
1131            purpose = "IOException checking missed.",
1132            targets = { @TestTarget(methodName = "writeShort",
1133                                    methodArgs = {int.class})
1134            }
1135        )
1136    public void test_writeShortI() throws Exception {
1137        // Test for method void java.io.ObjectOutputStream.writeShort(int)
1138        oos.writeShort(127);
1139        oos.close();
1140        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
1141        assertEquals("Wrote incorrect short value", 127, ois.readShort());
1142    }
1143
1144    /**
1145     * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
1146     */
1147    @TestInfo(
1148            level = TestLevel.PARTIAL,
1149            purpose = "IOException checking missed.",
1150            targets = { @TestTarget(methodName = "writeUTF",
1151                                    methodArgs = {java.lang.String.class})
1152            }
1153        )
1154    public void test_writeUTFLjava_lang_String() throws Exception {
1155        // Test for method void
1156        // java.io.ObjectOutputStream.writeUTF(java.lang.String)
1157        oos.writeUTF("HelloWorld");
1158        oos.close();
1159        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
1160        assertEquals("Wrote incorrect UTF value", "HelloWorld", ois.readUTF());
1161    }
1162
1163    /**
1164     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
1165     */
1166    @TestInfo(
1167            level = TestLevel.COMPLETE,
1168            purpose = "",
1169            targets = { @TestTarget(methodName = "writeObject",
1170                                    methodArgs = {java.lang.Object.class})
1171            }
1172        )
1173    public void test_writeObject_Exception() throws ClassNotFoundException, IOException {
1174        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
1175        ObjectOutputStream oos = new ObjectOutputStream(baos);
1176
1177        try {
1178            oos.writeObject(new Object());
1179            fail("should throw ObjectStreamException");
1180        } catch (ObjectStreamException e) {
1181            // expected
1182        } finally {
1183            oos.close();
1184            baos.close();
1185        }
1186
1187        byte[] bytes = baos.toByteArray();
1188        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
1189                bytes));
1190        try {
1191            ois.readObject();
1192            fail("should throw WriteAbortedException");
1193        } catch (WriteAbortedException e) {
1194            // expected
1195        } finally {
1196            ois.close();
1197        }
1198    }
1199
1200    /**
1201     * Sets up the fixture, for example, open a network connection. This method
1202     * is called before a test is executed.
1203     */
1204    protected void setUp() throws Exception {
1205        super.setUp();
1206        oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
1207    }
1208
1209    /**
1210     * Tears down the fixture, for example, close a network connection. This
1211     * method is called after a test is executed.
1212     */
1213    protected void tearDown() throws Exception {
1214        super.tearDown();
1215        if (oos != null) {
1216            try {
1217                oos.close();
1218            } catch (Exception e) {}
1219        }
1220        if (f != null && f.exists()) {
1221            if (!f.delete()) {
1222                fail("Error cleaning up files during teardown");
1223            }
1224        }
1225    }
1226
1227    protected Object reload() throws IOException, ClassNotFoundException {
1228
1229        // Choose the load stream
1230        if (xload || xdump) {
1231            // Load from pre-existing file
1232            ois = new ObjectInputStream(new FileInputStream(xFileName + "-"
1233                    + getName() + ".ser"));
1234        } else {
1235            // Just load from memory, we dumped to memory
1236            ois = new ObjectInputStream(new ByteArrayInputStream(bao
1237                    .toByteArray()));
1238        }
1239
1240        try {
1241            return ois.readObject();
1242        } finally {
1243            ois.close();
1244        }
1245    }
1246
1247    protected void dump(Object o) throws IOException, ClassNotFoundException {
1248
1249        // Choose the dump stream
1250        if (xdump) {
1251            oos = new ObjectOutputStream(new FileOutputStream(
1252                    f = new java.io.File(xFileName + "-" + getName() + ".ser")));
1253        } else {
1254            oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
1255        }
1256
1257        // Dump the object
1258        try {
1259            oos.writeObject(o);
1260        } finally {
1261            oos.close();
1262        }
1263    }
1264
1265    /**
1266     * @tests java.io.ObjectOutputStream#writeInt(int)
1267     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
1268     * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
1269     */
1270    @TestInfo(
1271            level = TestLevel.PARTIAL,
1272            purpose = "",
1273            targets = { @TestTarget(methodName = "writeInt",
1274                                    methodArgs = {int.class}),
1275                        @TestTarget(methodName = "writeObject",
1276                                            methodArgs = {java.lang.Object.class}),
1277                        @TestTarget(methodName = "writeUTF",
1278                                    methodArgs = {java.lang.String.class})
1279            }
1280        )
1281    public void testMixPrimitivesAndObjects() throws Exception {
1282        int i = 7;
1283        String s1 = "string 1";
1284        String s2 = "string 2";
1285        byte[] bytes = { 1, 2, 3 };
1286        try {
1287            oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
1288            oos.writeInt(i);
1289            oos.writeObject(s1);
1290            oos.writeUTF(s2);
1291            oos.writeObject(bytes);
1292            oos.close();
1293
1294            ois = new ObjectInputStream(new ByteArrayInputStream(bao
1295                    .toByteArray()));
1296
1297            int j = ois.readInt();
1298            assertTrue("Wrong int :" + j, i == j);
1299
1300            String l1 = (String) ois.readObject();
1301            assertTrue("Wrong obj String :" + l1, s1.equals(l1));
1302
1303            String l2 = ois.readUTF();
1304            assertTrue("Wrong UTF String :" + l2, s2.equals(l2));
1305
1306            byte[] bytes2 = (byte[]) ois.readObject();
1307            assertTrue("Wrong byte[]", Arrays.equals(bytes, bytes2));
1308        } finally {
1309            try {
1310                if (oos != null)
1311                    oos.close();
1312                if (ois != null)
1313                    ois.close();
1314            } catch (IOException e) {}
1315        }
1316    }
1317
1318    /**
1319     * @tests java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
1320     */
1321    @TestInfo(
1322            level = TestLevel.COMPLETE,
1323            purpose = "",
1324            targets = { @TestTarget(methodName = "writeUnshared",
1325                                    methodArgs = {java.lang.Object.class})
1326            }
1327        )
1328    public void test_writeUnshared() throws Exception {
1329        //Regression for HARMONY-187
1330        ByteArrayOutputStream baos = new ByteArrayOutputStream();
1331        ObjectOutputStream oos = new ObjectOutputStream(baos);
1332
1333        Object o = "foobar";
1334        oos.writeObject(o);
1335        oos.writeUnshared(o);
1336        oos.writeObject(o);
1337        oos.flush();
1338
1339        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
1340
1341        Object[] oa = new Object[3];
1342        for (int i = 0; i < oa.length; i++) {
1343            oa[i] = ois.readObject();
1344        }
1345
1346        oos.close();
1347        ois.close();
1348
1349        // All three conditions must be met
1350        assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
1351        assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
1352        assertSame("oa[0] == oa[2]", oa[0], oa[2]);
1353    }
1354
1355    /**
1356     * @tests java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
1357     */
1358    @TestInfo(
1359            level = TestLevel.COMPLETE,
1360            purpose = "",
1361            targets = { @TestTarget(methodName = "writeUnshared",
1362                                    methodArgs = {java.lang.Object.class})
1363            }
1364        )
1365    public void test_writeUnshared2() throws Exception {
1366        //Regression for HARMONY-187
1367        ByteArrayOutputStream baos = new ByteArrayOutputStream();
1368        ObjectOutputStream oos = new ObjectOutputStream(baos);
1369
1370        Object o = new Object[1];
1371        oos.writeObject(o);
1372        oos.writeUnshared(o);
1373        oos.writeObject(o);
1374        oos.flush();
1375
1376        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
1377
1378        Object[] oa = new Object[3];
1379        for (int i = 0; i < oa.length; i++) {
1380            oa[i] = ois.readObject();
1381        }
1382
1383        oos.close();
1384        ois.close();
1385
1386        // All three conditions must be met
1387        assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
1388        assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
1389        assertSame("oa[0] == oa[2]", oa[0], oa[2]);
1390    }
1391
1392    protected Object dumpAndReload(Object o) throws IOException,
1393            ClassNotFoundException {
1394        dump(o);
1395        return reload();
1396    }
1397
1398    /**
1399     * @tests java.io.ObjectOutputStream#useProtocolVersion(int)
1400     */
1401    @TestInfo(
1402            level = TestLevel.PARTIAL,
1403            purpose = "IOException & IllegalStateException checking missed.",
1404            targets = { @TestTarget(methodName = "useProtocolVersion",
1405                                    methodArgs = {int.class})
1406            }
1407        )
1408    public void test_useProtocolVersionI_2() throws Exception {
1409        ObjectOutputStream oos = new ObjectOutputStream(
1410                new ByteArrayOutputStream());
1411
1412        oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
1413        oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_2);
1414        try {
1415            oos.useProtocolVersion(3);
1416            fail("Protocol 3 should not be accepted");
1417        } catch (IllegalArgumentException e) {
1418            // expected
1419        } finally {
1420            oos.close();
1421        }
1422    }
1423
1424    /**
1425     * @tests java.io.ObjectOutputStream#replaceObject(java.lang.Object)
1426     */
1427    @TestInfo(
1428            level = TestLevel.COMPLETE,
1429            purpose = "",
1430            targets = { @TestTarget(methodName = "replaceObject",
1431                                    methodArgs = {java.lang.Object.class})
1432            }
1433        )
1434    public void test_replaceObject() throws Exception {
1435        //Regression for HARMONY-1429
1436        ByteArrayOutputStream baos = new ByteArrayOutputStream();
1437        ObjectOutputStreamWithReplace oos = new ObjectOutputStreamWithReplace(baos);
1438
1439        oos.writeObject(new NotSerializable());
1440        oos.flush();
1441        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
1442        Object obj = ois.readObject();
1443        oos.close();
1444        ois.close();
1445        assertTrue("replaceObject has not been called", (obj instanceof Long));
1446
1447        //Regression for HARMONY-2239
1448        Object replaceObject = int.class;
1449        baos = new ByteArrayOutputStream();
1450        ObjectOutputStreamWithReplace2 oos2 = new ObjectOutputStreamWithReplace2(
1451                baos);
1452        oos2.writeObject(new WriteReplaceObject(replaceObject));
1453        oos2.flush();
1454        ois = new ObjectInputStream(
1455                new ByteArrayInputStream(baos.toByteArray()));
1456        obj = ois.readObject();
1457        oos.close();
1458        ois.close();
1459        assertTrue("replaceObject has not been called", (obj instanceof Long));
1460
1461        replaceObject = ObjectStreamClass.lookup(Integer.class);
1462        baos = new ByteArrayOutputStream();
1463        oos2 = new ObjectOutputStreamWithReplace2(baos);
1464        oos2.writeObject(new WriteReplaceObject(replaceObject));
1465        oos2.flush();
1466        ois = new ObjectInputStream(
1467                new ByteArrayInputStream(baos.toByteArray()));
1468        obj = ois.readObject();
1469        oos.close();
1470        ois.close();
1471        assertTrue("replaceObject has not been called", (obj instanceof Long));
1472
1473        replaceObject = WriteReplaceObject.Color.red;
1474        baos = new ByteArrayOutputStream();
1475        oos2 = new ObjectOutputStreamWithReplace2(baos);
1476        oos2.writeObject(new WriteReplaceObject(replaceObject));
1477        oos2.flush();
1478        ois = new ObjectInputStream(
1479                new ByteArrayInputStream(baos.toByteArray()));
1480        obj = ois.readObject();
1481        oos.close();
1482        ois.close();
1483        assertTrue("replaceObject has not been called", (obj instanceof Long));
1484
1485        // Regression for HARMONY-3158
1486        Object obj1;
1487        Object obj2;
1488        Object obj3;
1489
1490        baos = new ByteArrayOutputStream();
1491        oos = new ObjectOutputStreamWithReplace(baos);
1492
1493        oos.writeObject(new Integer(99));
1494        oos.writeObject(Integer.class);
1495        oos.writeObject(ObjectStreamClass.lookup(Integer.class));
1496        oos.flush();
1497
1498        ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
1499        obj1 = ois.readObject();
1500        obj2 = ois.readObject();
1501        obj3 = ois.readObject();
1502        oos.close();
1503        ois.close();
1504
1505        assertTrue("1st replaceObject worked incorrectly", obj1 instanceof Long);
1506        assertEquals("1st replaceObject worked incorrectly",
1507                99, ((Long) obj1).longValue());
1508        assertEquals("2nd replaceObject worked incorrectly", Integer.class, obj2);
1509        assertEquals("3rd replaceObject worked incorrectly",
1510                ObjectStreamClass.class, obj3.getClass());
1511    }
1512}
1513