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 org.apache.harmony.luni.tests.java.io;
19
20import java.io.BufferedReader;
21import java.io.ByteArrayInputStream;
22import java.io.CharArrayReader;
23import java.io.IOException;
24import java.io.InputStreamReader;
25import java.io.PipedReader;
26import java.io.Reader;
27import java.io.StringReader;
28
29import junit.framework.TestCase;
30import tests.support.Support_StringReader;
31
32public class BufferedReaderTest extends TestCase {
33
34	BufferedReader br;
35
36	String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
37
38        /**
39         * The spec says that BufferedReader.readLine() considers only "\r", "\n"
40         * and "\r\n" to be line separators. We must not permit additional separator
41         * characters.
42        */
43        public void test_readLine_IgnoresEbcdic85Characters() throws IOException {
44            assertLines("A\u0085B", "A\u0085B");
45        }
46
47        public void test_readLine_Separators() throws IOException {
48            assertLines("A\nB\nC", "A", "B", "C");
49            assertLines("A\rB\rC", "A", "B", "C");
50            assertLines("A\r\nB\r\nC", "A", "B", "C");
51            assertLines("A\n\rB\n\rC", "A", "", "B", "", "C");
52            assertLines("A\n\nB\n\nC", "A", "", "B", "", "C");
53            assertLines("A\r\rB\r\rC", "A", "", "B", "", "C");
54            assertLines("A\n\n", "A", "");
55            assertLines("A\n\r", "A", "");
56            assertLines("A\r\r", "A", "");
57            assertLines("A\r\n", "A");
58            assertLines("A\r\n\r\n", "A", "");
59        }
60
61        private void assertLines(String in, String... lines) throws IOException {
62            BufferedReader bufferedReader
63                = new BufferedReader(new Support_StringReader(in));
64            for (String line : lines) {
65                assertEquals(line, bufferedReader.readLine());
66            }
67            assertNull(bufferedReader.readLine());
68        }
69
70	/**
71	 * @tests java.io.BufferedReader#BufferedReader(java.io.Reader)
72	 */
73	public void test_ConstructorLjava_io_Reader() {
74		// Test for method java.io.BufferedReader(java.io.Reader)
75		assertTrue("Used in tests", true);
76	}
77
78	/**
79	 * @tests java.io.BufferedReader#BufferedReader(java.io.Reader, int)
80	 */
81	public void test_ConstructorLjava_io_ReaderI() {
82		// Test for method java.io.BufferedReader(java.io.Reader, int)
83		assertTrue("Used in tests", true);
84	}
85
86	/**
87	 * @tests java.io.BufferedReader#close()
88	 */
89	public void test_close() {
90		// Test for method void java.io.BufferedReader.close()
91		try {
92			br = new BufferedReader(new Support_StringReader(testString));
93			br.close();
94			br.read();
95			fail("Read on closed stream");
96		} catch (IOException x) {
97			return;
98		}
99	}
100
101	/**
102	 * @tests java.io.BufferedReader#mark(int)
103	 */
104	public void test_markI() throws IOException {
105		// Test for method void java.io.BufferedReader.mark(int)
106		char[] buf = null;
107		br = new BufferedReader(new Support_StringReader(testString));
108		br.skip(500);
109		br.mark(1000);
110		br.skip(250);
111		br.reset();
112		buf = new char[testString.length()];
113		br.read(buf, 0, 500);
114		assertTrue("Failed to set mark properly", testString.substring(500,
115				1000).equals(new String(buf, 0, 500)));
116
117		try {
118			br = new BufferedReader(new Support_StringReader(testString), 800);
119			br.skip(500);
120			br.mark(250);
121			br.read(buf, 0, 1000);
122			br.reset();
123			fail("Failed to invalidate mark properly");
124		} catch (IOException x) {
125		    // Expected
126		}
127
128		char[] chars = new char[256];
129		for (int i = 0; i < 256; i++)
130			chars[i] = (char) i;
131		Reader in = new BufferedReader(new Support_StringReader(new String(
132				chars)), 12);
133
134		in.skip(6);
135		in.mark(14);
136		in.read(new char[14], 0, 14);
137		in.reset();
138		assertTrue("Wrong chars", in.read() == (char) 6
139				&& in.read() == (char) 7);
140
141		in = new BufferedReader(new Support_StringReader(new String(chars)), 12);
142		in.skip(6);
143		in.mark(8);
144		in.skip(7);
145		in.reset();
146		assertTrue("Wrong chars 2", in.read() == (char) 6
147				&& in.read() == (char) 7);
148
149        BufferedReader br = new BufferedReader(new StringReader("01234"), 2);
150        br.mark(3);
151        char[] carray = new char[3];
152        int result = br.read(carray);
153        assertEquals(3, result);
154        assertEquals("Assert 0:", '0', carray[0]);
155        assertEquals("Assert 1:", '1', carray[1]);
156        assertEquals("Assert 2:", '2', carray[2]);
157        assertEquals("Assert 3:", '3', br.read());
158
159        br = new BufferedReader(new StringReader("01234"), 2);
160        br.mark(3);
161        carray = new char[4];
162        result = br.read(carray);
163        assertEquals("Assert 4:", 4, result);
164        assertEquals("Assert 5:", '0', carray[0]);
165        assertEquals("Assert 6:", '1', carray[1]);
166        assertEquals("Assert 7:", '2', carray[2]);
167        assertEquals("Assert 8:", '3', carray[3]);
168        assertEquals("Assert 9:", '4', br.read());
169        assertEquals("Assert 10:", -1, br.read());
170
171        BufferedReader reader = new BufferedReader(new StringReader("01234"));
172        reader.mark(Integer.MAX_VALUE);
173        reader.read();
174        reader.close();
175	}
176
177	/**
178	 * @tests java.io.BufferedReader#markSupported()
179	 */
180	public void test_markSupported() {
181		// Test for method boolean java.io.BufferedReader.markSupported()
182		br = new BufferedReader(new Support_StringReader(testString));
183		assertTrue("markSupported returned false", br.markSupported());
184	}
185
186	/**
187	 * @tests java.io.BufferedReader#read()
188	 */
189	public void test_read() throws IOException {
190		// Test for method int java.io.BufferedReader.read()
191		try {
192			br = new BufferedReader(new Support_StringReader(testString));
193			int r = br.read();
194			assertTrue("Char read improperly", testString.charAt(0) == r);
195			br = new BufferedReader(new Support_StringReader(new String(
196					new char[] { '\u8765' })));
197			assertTrue("Wrong double byte character", br.read() == '\u8765');
198		} catch (java.io.IOException e) {
199			fail("Exception during read test");
200		}
201
202		char[] chars = new char[256];
203		for (int i = 0; i < 256; i++)
204			chars[i] = (char) i;
205		Reader in = new BufferedReader(new Support_StringReader(new String(
206				chars)), 12);
207		try {
208			assertEquals("Wrong initial char", 0, in.read()); // Fill the
209			// buffer
210			char[] buf = new char[14];
211			in.read(buf, 0, 14); // Read greater than the buffer
212			assertTrue("Wrong block read data", new String(buf)
213					.equals(new String(chars, 1, 14)));
214			assertEquals("Wrong chars", 15, in.read()); // Check next byte
215		} catch (IOException e) {
216			fail("Exception during read test 2:" + e);
217		}
218
219		// regression test for HARMONY-841
220		assertTrue(new BufferedReader(new CharArrayReader(new char[5], 1, 0), 2).read() == -1);
221	}
222
223	/**
224	 * @tests java.io.BufferedReader#read(char[], int, int)
225	 */
226	public void test_read$CII() throws Exception{
227		char[] ca = new char[2];
228		BufferedReader toRet = new BufferedReader(new InputStreamReader(
229				new ByteArrayInputStream(new byte[0])));
230
231		/* Null buffer should throw NPE even when len == 0 */
232		try {
233			toRet.read(null, 1, 0);
234			fail("null buffer reading zero bytes should throw NPE");
235		} catch (NullPointerException e) {
236			//expected
237		}
238
239		try {
240			toRet.close();
241		} catch (IOException e) {
242			fail("unexpected 1: " + e);
243		}
244
245		try {
246			toRet.read(null, 1, 0);
247			fail("null buffer reading zero bytes on closed stream should throw IOException");
248		} catch (IOException e) {
249			//expected
250		}
251
252		/* Closed reader should throw IOException reading zero bytes */
253		try {
254			toRet.read(ca, 0, 0);
255			fail("Reading zero bytes on a closed reader should not work");
256		} catch (IOException e) {
257			// expected
258		}
259
260		/*
261		 * Closed reader should throw IOException in preference to index out of
262		 * bounds
263		 */
264		try {
265			// Read should throw IOException before
266			// ArrayIndexOutOfBoundException
267			toRet.read(ca, 1, 5);
268			fail("IOException should have been thrown");
269		} catch (IOException e) {
270			// expected
271		}
272
273		// Test to ensure that a drained stream returns 0 at EOF
274		toRet = new BufferedReader(new InputStreamReader(
275				new ByteArrayInputStream(new byte[2])));
276		try {
277			assertEquals("Emptying the reader should return two bytes", 2,
278					toRet.read(ca, 0, 2));
279			assertEquals("EOF on a reader should be -1", -1, toRet.read(ca, 0,
280					2));
281			assertEquals("Reading zero bytes at EOF should work", 0, toRet
282					.read(ca, 0, 0));
283		} catch (IOException ex) {
284			fail("Unexpected IOException : " + ex.getLocalizedMessage());
285		}
286
287		// Test for method int java.io.BufferedReader.read(char [], int, int)
288		try {
289			char[] buf = new char[testString.length()];
290			br = new BufferedReader(new Support_StringReader(testString));
291			br.read(buf, 50, 500);
292			assertTrue("Chars read improperly", new String(buf, 50, 500)
293					.equals(testString.substring(0, 500)));
294		} catch (java.io.IOException e) {
295			fail("Exception during read test");
296		}
297
298		BufferedReader bufin = new BufferedReader(new Reader() {
299			int size = 2, pos = 0;
300
301			char[] contents = new char[size];
302
303			public int read() throws IOException {
304				if (pos >= size)
305					throw new IOException("Read past end of data");
306				return contents[pos++];
307			}
308
309			public int read(char[] buf, int off, int len) throws IOException {
310				if (pos >= size)
311					throw new IOException("Read past end of data");
312				int toRead = len;
313				if (toRead > (size - pos))
314					toRead = size - pos;
315				System.arraycopy(contents, pos, buf, off, toRead);
316				pos += toRead;
317				return toRead;
318			}
319
320			public boolean ready() throws IOException {
321				return size - pos > 0;
322			}
323
324			public void close() throws IOException {
325			}
326		});
327		try {
328			bufin.read();
329			int result = bufin.read(new char[2], 0, 2);
330			assertTrue("Incorrect result: " + result, result == 1);
331		} catch (IOException e) {
332			fail("Unexpected: " + e);
333		}
334
335        //regression for HARMONY-831
336        try{
337            new BufferedReader(new PipedReader(), 9).read(new char[] {}, 7, 0);
338            fail("should throw IndexOutOfBoundsException");
339        }catch(IndexOutOfBoundsException e){
340        }
341
342        // Regression for HARMONY-54
343        char[] ch = {};
344        BufferedReader reader = new BufferedReader(new CharArrayReader(ch));
345        try {
346            // Check exception thrown when the reader is open.
347            reader.read(null, 1, 0);
348            fail("Assert 0: NullPointerException expected");
349        } catch (NullPointerException e) {
350            // Expected
351        }
352
353        // Now check IOException is thrown in preference to
354        // NullPointerexception when the reader is closed.
355        reader.close();
356        try {
357            reader.read(null, 1, 0);
358            fail("Assert 1: IOException expected");
359        } catch (IOException e) {
360            // Expected
361        }
362
363        try {
364            // And check that the IOException is thrown before
365            // ArrayIndexOutOfBoundException
366            reader.read(ch, 0, 42);
367            fail("Assert 2: IOException expected");
368        } catch (IOException e) {
369            // expected
370        }
371	}
372
373	/**
374	 * @tests java.io.BufferedReader#read(char[], int, int)
375	 */
376	public void test_read_$CII_Exception() throws IOException {
377		br = new BufferedReader(new Support_StringReader(testString));
378		char[] nullCharArray = null;
379		char[] charArray = testString.toCharArray();
380
381		try {
382			br.read(nullCharArray, -1, -1);
383			fail();
384		} catch (NullPointerException expected) {
385		} catch (IndexOutOfBoundsException expected) {
386		}
387
388		try {
389			br.read(nullCharArray, -1, 0);
390			fail();
391		} catch (NullPointerException expected) {
392		} catch (IndexOutOfBoundsException expected) {
393		}
394
395		try {
396			br.read(nullCharArray, 0, -1);
397			fail("should throw NullPointerException");
398		} catch (NullPointerException e) {
399			// expected
400		}
401
402		try {
403			br.read(nullCharArray, 0, 0);
404			fail("should throw NullPointerException");
405		} catch (NullPointerException e) {
406			// expected
407		}
408
409		try {
410			br.read(nullCharArray, 0, 1);
411			fail("should throw NullPointerException");
412		} catch (NullPointerException e) {
413			// expected
414		}
415
416		try {
417			br.read(charArray, -1, -1);
418			fail("should throw IndexOutOfBoundsException");
419		} catch (IndexOutOfBoundsException e) {
420			// expected
421		}
422
423		try {
424			br.read(charArray, -1, 0);
425			fail("should throw IndexOutOfBoundsException");
426		} catch (IndexOutOfBoundsException e) {
427			// expected
428		}
429
430		br.read(charArray, 0, 0);
431        br.read(charArray, 0, charArray.length);
432        br.read(charArray, charArray.length, 0);
433
434		try {
435			br.read(charArray, charArray.length + 1, 0);
436			fail("should throw IndexOutOfBoundsException");
437		} catch (IndexOutOfBoundsException e) {
438			//expected
439		}
440
441		try {
442			br.read(charArray, charArray.length + 1, 1);
443			fail("should throw IndexOutOfBoundsException");
444		} catch (IndexOutOfBoundsException e) {
445			//expected
446		}
447
448		br.close();
449
450		try {
451			br.read(nullCharArray, -1, -1);
452			fail("should throw IOException");
453		} catch (IOException e) {
454			// expected
455		}
456
457		try {
458			br.read(charArray, -1, 0);
459			fail("should throw IOException");
460		} catch (IOException e) {
461			// expected
462		}
463
464		try {
465			br.read(charArray, 0, -1);
466			fail("should throw IOException");
467		} catch (IOException e) {
468			// expected
469		}
470	}
471	/**
472	 * @tests java.io.BufferedReader#readLine()
473	 */
474	public void test_readLine() {
475		// Test for method java.lang.String java.io.BufferedReader.readLine()
476		try {
477			br = new BufferedReader(new Support_StringReader(testString));
478			String r = br.readLine();
479			assertEquals("readLine returned incorrect string", "Test_All_Tests", r
480					);
481		} catch (java.io.IOException e) {
482			fail("Exception during readLine test");
483		}
484	}
485
486	/**
487	 * @tests java.io.BufferedReader#ready()
488	 */
489	public void test_ready() {
490		// Test for method boolean java.io.BufferedReader.ready()
491		try {
492			br = new BufferedReader(new Support_StringReader(testString));
493			assertTrue("ready returned false", br.ready());
494		} catch (java.io.IOException e) {
495			fail("Exception during ready test" + e.toString());
496		}
497	}
498
499	/**
500	 * @tests java.io.BufferedReader#reset()
501	 */
502	public void test_reset() {
503		// Test for method void java.io.BufferedReader.reset()
504		try {
505			br = new BufferedReader(new Support_StringReader(testString));
506			br.skip(500);
507			br.mark(900);
508			br.skip(500);
509			br.reset();
510			char[] buf = new char[testString.length()];
511			br.read(buf, 0, 500);
512			assertTrue("Failed to reset properly", testString.substring(500,
513					1000).equals(new String(buf, 0, 500)));
514		} catch (java.io.IOException e) {
515			fail("Exception during reset test");
516		}
517		try {
518			br = new BufferedReader(new Support_StringReader(testString));
519			br.skip(500);
520			br.reset();
521			fail("Reset succeeded on unmarked stream");
522		} catch (IOException x) {
523			return;
524
525		}
526	}
527
528    public void test_reset_IOException() throws Exception {
529        int[] expected = new int[] { '1', '2', '3', '4', '5', '6', '7', '8',
530                '9', '0', -1 };
531        br = new BufferedReader(new Support_StringReader("1234567890"), 9);
532        br.mark(9);
533        for (int i = 0; i < 11; i++) {
534            assertEquals(expected[i], br.read());
535        }
536        try {
537            br.reset();
538            fail("should throw IOException");
539        } catch (IOException e) {
540            // Expected
541        }
542        for (int i = 0; i < 11; i++) {
543            assertEquals(-1, br.read());
544        }
545
546        br = new BufferedReader(new Support_StringReader("1234567890"));
547        br.mark(10);
548        for (int i = 0; i < 10; i++) {
549            assertEquals(expected[i], br.read());
550        }
551        br.reset();
552        for (int i = 0; i < 11; i++) {
553            assertEquals(expected[i], br.read());
554        }
555    }
556
557	/**
558	 * @tests java.io.BufferedReader#skip(long)
559	 */
560	public void test_skipJ() {
561		// Test for method long java.io.BufferedReader.skip(long)
562		try {
563			br = new BufferedReader(new Support_StringReader(testString));
564			br.skip(500);
565			char[] buf = new char[testString.length()];
566			br.read(buf, 0, 500);
567			assertTrue("Failed to set skip properly", testString.substring(500,
568					1000).equals(new String(buf, 0, 500)));
569		} catch (java.io.IOException e) {
570			fail("Exception during skip test");
571		}
572
573	}
574
575	/**
576	 * Sets up the fixture, for example, open a network connection. This method
577	 * is called before a test is executed.
578	 */
579	protected void setUp() {
580	}
581
582	/**
583	 * Tears down the fixture, for example, close a network connection. This
584	 * method is called after a test is executed.
585	 */
586	protected void tearDown() {
587		try {
588			br.close();
589		} catch (Exception e) {
590		}
591	}
592}
593