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