7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24 /**
25 * @test
26 * @bug 4313885 4926319 4927634 5032610 5032622 5049968 5059533 6223711 6277261 6269946 6288823
27 * @summary Basic tests of java.util.Scanner methods
28 * @key randomness
29 * @run main/othervm ScanTest
30 */
31
32 import java.util.*;
33 import java.text.*;
34 import java.io.*;
35 import java.nio.*;
36 import java.util.regex.*;
37 import java.math.*;
38
39 public class ScanTest {
40
41 private static boolean failure = false;
42 private static int failCount = 0;
43 private static int NUM_SOURCE_TYPES = 2;
44
45 public static void main(String[] args) throws Exception {
46 Locale reservedLocale = Locale.getDefault();
47 String lang = reservedLocale.getLanguage();
48 try {
49 if (!"en".equals(lang) &&
50 !"zh".equals(lang) &&
51 !"ko".equals(lang) &&
52 !"ja".equals(lang)) {
53 //Before we have resource to improve the test to be ready for
54 //arbitrary locale, force the default locale to be "English"
55 //for now.
56 Locale.setDefault(Locale.ENGLISH);
57 }
58 skipTest();
59 findInLineTest();
60 findWithinHorizonTest();
61 findInEmptyLineTest();
62 removeTest();
63 fromFileTest();
64 ioExceptionTest();
65 matchTest();
66 delimiterTest();
67 useLocaleTest();
68 closeTest();
69 cacheTest();
70 cacheTest2();
71 nonASCIITest();
72 resetTest();
73
74 for (int j=0; j<NUM_SOURCE_TYPES; j++) {
75 hasNextTest(j);
76 nextTest(j);
77 hasNextPatternTest(j);
78 nextPatternTest(j);
79 booleanTest(j);
80 byteTest(j);
81 shortTest(j);
82 intTest(j);
83 longTest(j);
84 floatTest(j);
85 doubleTest(j);
86 integerPatternTest(j);
87 floatPatternTest(j);
88 bigIntegerPatternTest(j);
89 bigDecimalPatternTest(j);
90 hasNextLineTest(j);
91 nextLineTest(j);
92 singleDelimTest(j);
93 }
94
98 //example3();
99
100 // Usage cases
101 useCase1();
102 useCase2();
103 useCase3();
104 useCase4();
105 useCase5();
106
107 if (failure)
108 throw new RuntimeException("Failure in the scanning tests.");
109 else
110 System.err.println("OKAY: All tests passed.");
111 } finally {
112 // restore the default locale
113 Locale.setDefault(reservedLocale);
114 }
115 }
116
117 public static void useCase1() throws Exception {
118 File f = new File(System.getProperty("test.src", "."), "input.txt");
119 Scanner sc = new Scanner(f);
120 sc.findWithinHorizon("usage case 1", 0);
121 String[] names = new String[4];
122 for (int i=0; i<4; i++) {
123 while(sc.hasNextFloat())
124 sc.nextFloat();
125 names[i] = sc.next();
126 sc.nextLine();
127 }
128 if (!names[0].equals("Frank"))
129 failCount++;
130 if (!names[1].equals("Joe"))
131 failCount++;
132 if (!names[2].equals("Mary"))
133 failCount++;
134 if (!names[3].equals("Michelle"))
135 failCount++;
136 sc.close();
137 report("Use case 1");
138 }
139
140 public static void useCase2() throws Exception {
141 File f = new File(System.getProperty("test.src", "."), "input.txt");
142 Scanner sc = new Scanner(f).useDelimiter("-");
143 String testDataTag = sc.findWithinHorizon("usage case 2\n", 0);
144 if (!testDataTag.equals("usage case 2\n"))
145 failCount++;
146 if (!sc.next().equals("cat"))
147 failCount++;
148 if (sc.nextInt() != 9)
149 failCount++;
150 if (!sc.next().equals("dog"))
151 failCount++;
152 if (sc.nextInt() != 6)
153 failCount++;
154 if (!sc.next().equals("pig"))
155 failCount++;
156 if (sc.nextInt() != 2)
157 failCount++;
158 if (!sc.next().equals(""))
159 failCount++;
160 if (sc.nextInt() != 5)
161 failCount++;
162 sc.close();
163 report("Use case 2");
164 }
165
166 public static void useCase3() throws Exception {
167 File f = new File(System.getProperty("test.src", "."), "input.txt");
168 Scanner sc = new Scanner(f);
169 String testDataTag = sc.findWithinHorizon("usage case 3\n", 0);
170 if (!testDataTag.equals("usage case 3\n"))
171 failCount++;
172 Pattern tagPattern = Pattern.compile("@[a-z]+");
173 Pattern endPattern = Pattern.compile("\\*\\/");
174 String tag;
175 String end = sc.findInLine(endPattern);
176
177 while (end == null) {
178 if ((tag = sc.findInLine(tagPattern)) != null) {
179 String text = sc.nextLine();
180 text = text.substring(0, text.length() - 1);
181 //System.out.println(text);
182 } else {
183 sc.nextLine();
184 }
185 end = sc.findInLine(endPattern);
186 }
187 report("Use case 3");
188 }
189
190 public static void useCase4() throws Exception {
191 File f = new File(System.getProperty("test.src", "."), "input.txt");
192 Scanner sc = new Scanner(f);
193 String testDataTag = sc.findWithinHorizon("usage case 4\n", 0);
194 if (!testDataTag.equals("usage case 4\n"))
195 failCount++;
196
197 // Read some text parts of four hrefs
198 String[] expected = { "Diffs", "Sdiffs", "Old", "New" };
199 for (int i=0; i<4; i++) {
200 sc.findWithinHorizon("<a href", 1000);
201 sc.useDelimiter("[<>\n]+");
202 sc.next();
203 String textOfRef = sc.next();
204 if (!textOfRef.equals(expected[i]))
205 failCount++;
206 }
207 // Read some html tags using < and > as delimiters
208 if (!sc.next().equals("/a"))
209 failCount++;
210 if (!sc.next().equals("b"))
211 failCount++;
212
213 // Scan some html tags using skip and next
214 Pattern nonTagStart = Pattern.compile("[^<]+");
215 Pattern tag = Pattern.compile("<[^>]+?>");
216 Pattern spotAfterTag = Pattern.compile("(?<=>)");
217 String[] expected2 = { "</b>", "<p>", "<ul>", "<li>" };
218 sc.useDelimiter(spotAfterTag);
219 int tagsFound = 0;
220 while(tagsFound < 4) {
221 if (!sc.hasNext(tag)) {
222 // skip text between tags
223 sc.skip(nonTagStart);
224 }
225 String tagContents = sc.next(tag);
226 if (!tagContents.equals(expected2[tagsFound]))
227 failCount++;
228 tagsFound++;
229 }
230
231 report("Use case 4");
232 }
233
234 public static void useCase5() throws Exception {
235 File f = new File(System.getProperty("test.src", "."), "input.txt");
236 Scanner sc = new Scanner(f);
237 String testDataTag = sc.findWithinHorizon("usage case 5\n", 0);
238 if (!testDataTag.equals("usage case 5\n"))
239 failCount++;
240
241 sc.findWithinHorizon("Share Definitions", 0);
242 sc.nextLine();
243 sc.next("\\[([a-z]+)\\]");
244 String shareName = sc.match().group(1);
245 if (!shareName.equals("homes"))
246 failCount++;
247
248 String[] keys = { "comment", "browseable", "writable", "valid users" };
249 String[] vals = { "Home Directories", "no", "yes", "%S" };
250 for (int i=0; i<4; i++) {
251 sc.useDelimiter("=");
252 String key = sc.next().trim();
253 if (!key.equals(keys[i]))
254 failCount++;
255 sc.skip("[ =]+");
256 sc.useDelimiter("\n");
257 String value = sc.next();
258 if (!value.equals(vals[i]))
259 failCount++;
260 sc.nextLine();
261 }
262
263 report("Use case 5");
264 }
265
266 public static void nonASCIITest() throws Exception {
267 String yourBasicTibetanNumberZero = "\u0f20";
268 String yourBasicTibetanFloatingNumber = "\u0f23.\u0f27";
269 String weirdMixtureOfTibetanAndASCII = "\u0f23.7";
270 String weirdMixtureOfASCIIAndTibetan = "3.\u0f27";
271 Scanner sc = new Scanner(yourBasicTibetanNumberZero);
272 int i = sc.nextInt();
273 if (i != 0)
274 failCount++;
275 sc = new Scanner(yourBasicTibetanFloatingNumber);
276 float f = sc.nextFloat();
277 if (f != Float.parseFloat("3.7"))
278 failCount++;
279 sc = new Scanner(weirdMixtureOfTibetanAndASCII);
280 f = sc.nextFloat();
281 if (f != Float.parseFloat("3.7"))
428 if (!sc.hasNextLine()) failCount++;
429 if (sc.nextInt() != 3) failCount++;
430 if (!sc.hasNextLine()) failCount++;
431 if (!sc.nextLine().equals(" 3")) failCount++;
432 if (!sc.hasNextLine()) failCount++;
433 if (sc.nextInt() != 4) failCount++;
434 if (!sc.hasNextLine()) failCount++;
435 if (sc.nextInt() != 4) failCount++;
436 if (!sc.hasNextLine()) failCount++;
437 if (!sc.nextLine().equals(" 4")) failCount++;
438 if (!sc.hasNextLine()) failCount++;
439 if (!sc.nextLine().equals("5")) failCount++;
440 if (sc.hasNextLine()) failCount++;
441 sc = new Scanner("blah blah blah blah blah blah");
442 if (!sc.hasNextLine()) failCount++;
443 if (!sc.nextLine().equals("blah blah blah blah blah blah"))
444 failCount++;
445 if (sc.hasNextLine()) failCount++;
446
447 // Go through all the lines in a file
448 File f = new File(System.getProperty("test.src", "."), "input.txt");
449 sc = new Scanner(f);
450 String lastLine = "blah";
451 while(sc.hasNextLine())
452 lastLine = sc.nextLine();
453 if (!lastLine.equals("# Data for usage case 6")) failCount++;
454
455 report("Has next line test");
456 }
457
458 public static void nextLineTest(int sourceType) throws Exception {
459 Scanner sc = scannerFor("1\n2\n3 3\r\n4 4 4\r5", sourceType);
460 if (!sc.nextLine().equals("1"))
461 failCount++;
462 if (sc.nextInt() != 2)
463 failCount++;
464 if (!sc.nextLine().equals(""))
465 failCount++;
466 if (sc.nextInt() != 3)
467 failCount++;
468 if (!sc.nextLine().equals(" 3"))
469 failCount++;
470 if (sc.nextInt() != 4)
471 failCount++;
472 if (sc.nextInt() != 4)
473 failCount++;
612 System.out.println("wrong radix cache is used");
613 failCount++;
614 }
615 scanner = new Scanner("10");
616 scanner.hasNextBigInteger(16);
617 if (scanner.nextBigInteger(10).intValue() != 10) {
618 System.out.println("wrong radix cache is used");
619 failCount++;
620 }
621 report("Cache test2");
622 }
623
624
625 public static void closeTest() throws Exception {
626 Scanner sc = new Scanner("testing");
627 sc.close();
628 sc.ioException();
629 sc.delimiter();
630 sc.useDelimiter("blah");
631 sc.useDelimiter(Pattern.compile("blah"));
632 for (int i=0; i<NUM_METHODS; i++) {
633 try {
634 methodCall(sc, i);
635 failCount++;
636 } catch (IllegalStateException ise) {
637 // Correct
638 }
639 }
640 report("Close test");
641 }
642
643 private static int NUM_METHODS = 23;
644
645 private static void methodCall(Scanner sc, int i) {
646 switch(i) {
647 case 0: sc.hasNext(); break;
648 case 1: sc.next(); break;
649 case 2: sc.hasNext(Pattern.compile("blah")); break;
650 case 3: sc.next(Pattern.compile("blah")); break;
651 case 4: sc.hasNextBoolean(); break;
652 case 5: sc.nextBoolean(); break;
653 case 6: sc.hasNextByte(); break;
654 case 7: sc.nextByte(); break;
655 case 8: sc.hasNextShort(); break;
656 case 9: sc.nextShort(); break;
657 case 10: sc.hasNextInt(); break;
658 case 11: sc.nextInt(); break;
659 case 12: sc.hasNextLong(); break;
660 case 13: sc.nextLong(); break;
661 case 14: sc.hasNextFloat(); break;
662 case 15: sc.nextFloat(); break;
663 case 16: sc.hasNextDouble(); break;
664 case 17: sc.nextDouble(); break;
665 case 18: sc.hasNextBigInteger(); break;
666 case 19: sc.nextBigInteger(); break;
667 case 20: sc.hasNextBigDecimal(); break;
668 case 21: sc.nextBigDecimal(); break;
669 case 22: sc.hasNextLine(); break;
670 default:
671 break;
672 }
673 }
674
675 public static void removeTest() throws Exception {
676 Scanner sc = new Scanner("testing");
677 try {
678 sc.remove();
679 failCount++;
680 } catch (UnsupportedOperationException uoe) {
681 // Correct result
682 }
683 report("Remove test");
684 }
685
686 public static void delimiterTest() throws Exception {
687 Scanner sc = new Scanner("blah");
688 Pattern test = sc.delimiter();
689 if (!test.toString().equals("\\p{javaWhitespace}+"))
690 failCount++;
691 sc.useDelimiter("a");
692 test = sc.delimiter();
693 if (!test.toString().equals("a"))
847 failCount++;
848 } catch (NoSuchElementException nse) {
849 // Correct result
850 }
851 try {
852 sc.nextDouble();
853 failCount++;
854 } catch (NoSuchElementException nse) {
855 // Correct result
856 }
857 try {
858 sc.nextDouble();
859 failCount++;
860 } catch (NoSuchElementException nse) {
861 // Correct result
862 }
863 }
864
865 public static void fromFileTest() throws Exception {
866 File f = new File(System.getProperty("test.src", "."), "input.txt");
867 Scanner sc = new Scanner(f).useDelimiter("\n+");
868 String testDataTag = sc.findWithinHorizon("fromFileTest", 0);
869 if (!testDataTag.equals("fromFileTest"))
870 failCount++;
871
872 int count = 0;
873 while (sc.hasNextLong()) {
874 long blah = sc.nextLong();
875 count++;
876 }
877 if (count != 7)
878 failCount++;
879 sc.close();
880 report("From file");
881 }
882
883 private static void example1() throws Exception {
884 Scanner s = new Scanner("1 fish 2 fish red fish blue fish");
885 s.useDelimiter("\\s*fish\\s*");
886 List <String> results = new ArrayList<String>();
887 while(s.hasNext())
888 results.add(s.next());
889 System.out.println(results);
890 }
891
892 private static void example2() throws Exception {
893 Scanner s = new Scanner("1 fish 2 fish red fish blue fish");
894 s.useDelimiter("\\s*fish\\s*");
895 System.out.println(s.nextInt());
896 System.out.println(s.nextInt());
897 System.out.println(s.next());
898 System.out.println(s.next());
899 }
1455 sc.useDelimiter(a);
1456 Locale dummy = new Locale("en", "US", "dummy");
1457 sc.useLocale(dummy);
1458 sc.useRadix(16);
1459 if (sc.radix() != 16 ||
1460 !sc.locale().equals(dummy) ||
1461 !sc.delimiter().pattern().equals(a.pattern())) {
1462 failCount++;
1463 } else {
1464 sc.reset();
1465 if (sc.radix() != radix ||
1466 !sc.locale().equals(locale) ||
1467 !sc.delimiter().pattern().equals(delimiter.pattern())) {
1468 failCount++;
1469 }
1470 }
1471 sc.close();
1472 report("Reset test");
1473 }
1474
1475 private static void report(String testName) {
1476 int spacesToAdd = 30 - testName.length();
1477 StringBuffer paddedNameBuffer = new StringBuffer(testName);
1478 for (int i=0; i<spacesToAdd; i++)
1479 paddedNameBuffer.append(" ");
1480 String paddedName = paddedNameBuffer.toString();
1481 System.err.println(paddedName + ": " +
1482 (failCount==0 ? "Passed":"Failed("+failCount+")"));
1483 if (failCount > 0)
1484 failure = true;
1485 failCount = 0;
1486 }
1487
1488 static Scanner scannerFor(String input, int sourceType) {
1489 if (sourceType == 1)
1490 return new Scanner(input);
1491 else
1492 return new Scanner(new StutteringInputStream(input));
1493 }
1494
1495 static class ThrowingReadable implements Readable {
1496 ThrowingReadable() {
1497 }
1498 public int read(java.nio.CharBuffer cb) throws IOException {
1499 throw new IOException("ThrowingReadable always throws");
1500 }
1501 }
1502 }
|
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24 /**
25 * @test
26 * @bug 4313885 4926319 4927634 5032610 5032622 5049968 5059533 6223711 6277261 6269946 6288823
27 * 8072722
28 * @summary Basic tests of java.util.Scanner methods
29 * @key randomness
30 * @run main/othervm ScanTest
31 */
32
33 import java.io.*;
34 import java.math.*;
35 import java.nio.*;
36 import java.text.*;
37 import java.util.*;
38 import java.util.function.Consumer;
39 import java.util.regex.*;
40 import java.util.stream.*;
41
42 public class ScanTest {
43
44 private static boolean failure = false;
45 private static int failCount = 0;
46 private static int NUM_SOURCE_TYPES = 2;
47 private static File inputFile = new File(System.getProperty("test.src", "."), "input.txt");
48
49 public static void main(String[] args) throws Exception {
50
51 Locale reservedLocale = Locale.getDefault();
52 String lang = reservedLocale.getLanguage();
53 try {
54 if (!"en".equals(lang) &&
55 !"zh".equals(lang) &&
56 !"ko".equals(lang) &&
57 !"ja".equals(lang)) {
58 //Before we have resource to improve the test to be ready for
59 //arbitrary locale, force the default locale to be "English"
60 //for now.
61 Locale.setDefault(Locale.ENGLISH);
62 }
63 skipTest();
64 findInLineTest();
65 findWithinHorizonTest();
66 findInEmptyLineTest();
67 removeTest();
68 fromFileTest();
69 ioExceptionTest();
70 matchTest();
71 delimiterTest();
72 useLocaleTest();
73 closeTest();
74 cacheTest();
75 cacheTest2();
76 nonASCIITest();
77 resetTest();
78 tokensTest();
79 findAllTest();
80 streamCloseTest();
81
82 for (int j = 0; j < NUM_SOURCE_TYPES; j++) {
83 hasNextTest(j);
84 nextTest(j);
85 hasNextPatternTest(j);
86 nextPatternTest(j);
87 booleanTest(j);
88 byteTest(j);
89 shortTest(j);
90 intTest(j);
91 longTest(j);
92 floatTest(j);
93 doubleTest(j);
94 integerPatternTest(j);
95 floatPatternTest(j);
96 bigIntegerPatternTest(j);
97 bigDecimalPatternTest(j);
98 hasNextLineTest(j);
99 nextLineTest(j);
100 singleDelimTest(j);
101 }
102
106 //example3();
107
108 // Usage cases
109 useCase1();
110 useCase2();
111 useCase3();
112 useCase4();
113 useCase5();
114
115 if (failure)
116 throw new RuntimeException("Failure in the scanning tests.");
117 else
118 System.err.println("OKAY: All tests passed.");
119 } finally {
120 // restore the default locale
121 Locale.setDefault(reservedLocale);
122 }
123 }
124
125 public static void useCase1() throws Exception {
126 try (Scanner sc = new Scanner(inputFile)) {
127 sc.findWithinHorizon("usage case 1", 0);
128 String[] names = new String[4];
129 for (int i=0; i<4; i++) {
130 while(sc.hasNextFloat())
131 sc.nextFloat();
132 names[i] = sc.next();
133 sc.nextLine();
134 }
135 if (!names[0].equals("Frank"))
136 failCount++;
137 if (!names[1].equals("Joe"))
138 failCount++;
139 if (!names[2].equals("Mary"))
140 failCount++;
141 if (!names[3].equals("Michelle"))
142 failCount++;
143 }
144 report("Use case 1");
145 }
146
147 public static void useCase2() throws Exception {
148 try (Scanner sc = new Scanner(inputFile).useDelimiter("-")) {
149 String testDataTag = sc.findWithinHorizon("usage case 2\n", 0);
150 if (!testDataTag.equals("usage case 2\n"))
151 failCount++;
152 if (!sc.next().equals("cat"))
153 failCount++;
154 if (sc.nextInt() != 9)
155 failCount++;
156 if (!sc.next().equals("dog"))
157 failCount++;
158 if (sc.nextInt() != 6)
159 failCount++;
160 if (!sc.next().equals("pig"))
161 failCount++;
162 if (sc.nextInt() != 2)
163 failCount++;
164 if (!sc.next().equals(""))
165 failCount++;
166 if (sc.nextInt() != 5)
167 failCount++;
168 }
169 report("Use case 2");
170 }
171
172 public static void useCase3() throws Exception {
173 try (Scanner sc = new Scanner(inputFile)) {
174 String testDataTag = sc.findWithinHorizon("usage case 3\n", 0);
175 if (!testDataTag.equals("usage case 3\n"))
176 failCount++;
177 Pattern tagPattern = Pattern.compile("@[a-z]+");
178 Pattern endPattern = Pattern.compile("\\*\\/");
179 String tag;
180 String end = sc.findInLine(endPattern);
181
182 while (end == null) {
183 if ((tag = sc.findInLine(tagPattern)) != null) {
184 String text = sc.nextLine();
185 text = text.substring(0, text.length() - 1);
186 //System.out.println(text);
187 } else {
188 sc.nextLine();
189 }
190 end = sc.findInLine(endPattern);
191 }
192 }
193 report("Use case 3");
194 }
195
196 public static void useCase4() throws Exception {
197 try (Scanner sc = new Scanner(inputFile)) {
198 String testDataTag = sc.findWithinHorizon("usage case 4\n", 0);
199 if (!testDataTag.equals("usage case 4\n"))
200 failCount++;
201
202 // Read some text parts of four hrefs
203 String[] expected = { "Diffs", "Sdiffs", "Old", "New" };
204 for (int i=0; i<4; i++) {
205 sc.findWithinHorizon("<a href", 1000);
206 sc.useDelimiter("[<>\n]+");
207 sc.next();
208 String textOfRef = sc.next();
209 if (!textOfRef.equals(expected[i]))
210 failCount++;
211 }
212 // Read some html tags using < and > as delimiters
213 if (!sc.next().equals("/a"))
214 failCount++;
215 if (!sc.next().equals("b"))
216 failCount++;
217
218 // Scan some html tags using skip and next
219 Pattern nonTagStart = Pattern.compile("[^<]+");
220 Pattern tag = Pattern.compile("<[^>]+?>");
221 Pattern spotAfterTag = Pattern.compile("(?<=>)");
222 String[] expected2 = { "</b>", "<p>", "<ul>", "<li>" };
223 sc.useDelimiter(spotAfterTag);
224 int tagsFound = 0;
225 while(tagsFound < 4) {
226 if (!sc.hasNext(tag)) {
227 // skip text between tags
228 sc.skip(nonTagStart);
229 }
230 String tagContents = sc.next(tag);
231 if (!tagContents.equals(expected2[tagsFound]))
232 failCount++;
233 tagsFound++;
234 }
235 }
236
237 report("Use case 4");
238 }
239
240 public static void useCase5() throws Exception {
241 try (Scanner sc = new Scanner(inputFile)) {
242 String testDataTag = sc.findWithinHorizon("usage case 5\n", 0);
243 if (!testDataTag.equals("usage case 5\n"))
244 failCount++;
245
246 sc.findWithinHorizon("Share Definitions", 0);
247 sc.nextLine();
248 sc.next("\\[([a-z]+)\\]");
249 String shareName = sc.match().group(1);
250 if (!shareName.equals("homes"))
251 failCount++;
252
253 String[] keys = { "comment", "browseable", "writable", "valid users" };
254 String[] vals = { "Home Directories", "no", "yes", "%S" };
255 for (int i=0; i<4; i++) {
256 sc.useDelimiter("=");
257 String key = sc.next().trim();
258 if (!key.equals(keys[i]))
259 failCount++;
260 sc.skip("[ =]+");
261 sc.useDelimiter("\n");
262 String value = sc.next();
263 if (!value.equals(vals[i]))
264 failCount++;
265 sc.nextLine();
266 }
267 }
268
269 report("Use case 5");
270 }
271
272 public static void nonASCIITest() throws Exception {
273 String yourBasicTibetanNumberZero = "\u0f20";
274 String yourBasicTibetanFloatingNumber = "\u0f23.\u0f27";
275 String weirdMixtureOfTibetanAndASCII = "\u0f23.7";
276 String weirdMixtureOfASCIIAndTibetan = "3.\u0f27";
277 Scanner sc = new Scanner(yourBasicTibetanNumberZero);
278 int i = sc.nextInt();
279 if (i != 0)
280 failCount++;
281 sc = new Scanner(yourBasicTibetanFloatingNumber);
282 float f = sc.nextFloat();
283 if (f != Float.parseFloat("3.7"))
284 failCount++;
285 sc = new Scanner(weirdMixtureOfTibetanAndASCII);
286 f = sc.nextFloat();
287 if (f != Float.parseFloat("3.7"))
434 if (!sc.hasNextLine()) failCount++;
435 if (sc.nextInt() != 3) failCount++;
436 if (!sc.hasNextLine()) failCount++;
437 if (!sc.nextLine().equals(" 3")) failCount++;
438 if (!sc.hasNextLine()) failCount++;
439 if (sc.nextInt() != 4) failCount++;
440 if (!sc.hasNextLine()) failCount++;
441 if (sc.nextInt() != 4) failCount++;
442 if (!sc.hasNextLine()) failCount++;
443 if (!sc.nextLine().equals(" 4")) failCount++;
444 if (!sc.hasNextLine()) failCount++;
445 if (!sc.nextLine().equals("5")) failCount++;
446 if (sc.hasNextLine()) failCount++;
447 sc = new Scanner("blah blah blah blah blah blah");
448 if (!sc.hasNextLine()) failCount++;
449 if (!sc.nextLine().equals("blah blah blah blah blah blah"))
450 failCount++;
451 if (sc.hasNextLine()) failCount++;
452
453 // Go through all the lines in a file
454 try (Scanner sc2 = new Scanner(inputFile)) {
455 String lastLine = "blah";
456 while(sc2.hasNextLine())
457 lastLine = sc2.nextLine();
458 if (!lastLine.equals("# Data for usage case 6")) failCount++;
459 }
460
461 report("Has next line test");
462 }
463
464 public static void nextLineTest(int sourceType) throws Exception {
465 Scanner sc = scannerFor("1\n2\n3 3\r\n4 4 4\r5", sourceType);
466 if (!sc.nextLine().equals("1"))
467 failCount++;
468 if (sc.nextInt() != 2)
469 failCount++;
470 if (!sc.nextLine().equals(""))
471 failCount++;
472 if (sc.nextInt() != 3)
473 failCount++;
474 if (!sc.nextLine().equals(" 3"))
475 failCount++;
476 if (sc.nextInt() != 4)
477 failCount++;
478 if (sc.nextInt() != 4)
479 failCount++;
618 System.out.println("wrong radix cache is used");
619 failCount++;
620 }
621 scanner = new Scanner("10");
622 scanner.hasNextBigInteger(16);
623 if (scanner.nextBigInteger(10).intValue() != 10) {
624 System.out.println("wrong radix cache is used");
625 failCount++;
626 }
627 report("Cache test2");
628 }
629
630
631 public static void closeTest() throws Exception {
632 Scanner sc = new Scanner("testing");
633 sc.close();
634 sc.ioException();
635 sc.delimiter();
636 sc.useDelimiter("blah");
637 sc.useDelimiter(Pattern.compile("blah"));
638
639 for (Consumer<Scanner> method : methodList) {
640 try {
641 method.accept(sc);
642 failCount++;
643 } catch (IllegalStateException ise) {
644 // Correct
645 }
646 }
647
648 report("Close test");
649 }
650
651 static List<Consumer<Scanner>> methodList = Arrays.asList(
652 Scanner::hasNext,
653 Scanner::next,
654 sc -> sc.hasNext(Pattern.compile("blah")),
655 sc -> sc.next(Pattern.compile("blah")),
656 Scanner::hasNextBoolean,
657 Scanner::nextBoolean,
658 Scanner::hasNextByte,
659 Scanner::nextByte,
660 Scanner::hasNextShort,
661 Scanner::nextShort,
662 Scanner::hasNextInt,
663 Scanner::nextInt,
664 Scanner::hasNextLong,
665 Scanner::nextLong,
666 Scanner::hasNextFloat,
667 Scanner::nextFloat,
668 Scanner::hasNextDouble,
669 Scanner::nextDouble,
670 Scanner::hasNextBigInteger,
671 Scanner::nextBigInteger,
672 Scanner::hasNextBigDecimal,
673 Scanner::nextBigDecimal,
674 Scanner::hasNextLine,
675 Scanner::tokens,
676 sc -> sc.findAll(Pattern.compile("blah")),
677 sc -> sc.findAll("blah")
678 );
679
680 public static void removeTest() throws Exception {
681 Scanner sc = new Scanner("testing");
682 try {
683 sc.remove();
684 failCount++;
685 } catch (UnsupportedOperationException uoe) {
686 // Correct result
687 }
688 report("Remove test");
689 }
690
691 public static void delimiterTest() throws Exception {
692 Scanner sc = new Scanner("blah");
693 Pattern test = sc.delimiter();
694 if (!test.toString().equals("\\p{javaWhitespace}+"))
695 failCount++;
696 sc.useDelimiter("a");
697 test = sc.delimiter();
698 if (!test.toString().equals("a"))
852 failCount++;
853 } catch (NoSuchElementException nse) {
854 // Correct result
855 }
856 try {
857 sc.nextDouble();
858 failCount++;
859 } catch (NoSuchElementException nse) {
860 // Correct result
861 }
862 try {
863 sc.nextDouble();
864 failCount++;
865 } catch (NoSuchElementException nse) {
866 // Correct result
867 }
868 }
869
870 public static void fromFileTest() throws Exception {
871 File f = new File(System.getProperty("test.src", "."), "input.txt");
872 try (Scanner sc = new Scanner(f)) {
873 sc.useDelimiter("\n+");
874 String testDataTag = sc.findWithinHorizon("fromFileTest", 0);
875 if (!testDataTag.equals("fromFileTest"))
876 failCount++;
877
878 int count = 0;
879 while (sc.hasNextLong()) {
880 long blah = sc.nextLong();
881 count++;
882 }
883 if (count != 7)
884 failCount++;
885 }
886 report("From file");
887 }
888
889 private static void example1() throws Exception {
890 Scanner s = new Scanner("1 fish 2 fish red fish blue fish");
891 s.useDelimiter("\\s*fish\\s*");
892 List <String> results = new ArrayList<String>();
893 while(s.hasNext())
894 results.add(s.next());
895 System.out.println(results);
896 }
897
898 private static void example2() throws Exception {
899 Scanner s = new Scanner("1 fish 2 fish red fish blue fish");
900 s.useDelimiter("\\s*fish\\s*");
901 System.out.println(s.nextInt());
902 System.out.println(s.nextInt());
903 System.out.println(s.next());
904 System.out.println(s.next());
905 }
1461 sc.useDelimiter(a);
1462 Locale dummy = new Locale("en", "US", "dummy");
1463 sc.useLocale(dummy);
1464 sc.useRadix(16);
1465 if (sc.radix() != 16 ||
1466 !sc.locale().equals(dummy) ||
1467 !sc.delimiter().pattern().equals(a.pattern())) {
1468 failCount++;
1469 } else {
1470 sc.reset();
1471 if (sc.radix() != radix ||
1472 !sc.locale().equals(locale) ||
1473 !sc.delimiter().pattern().equals(delimiter.pattern())) {
1474 failCount++;
1475 }
1476 }
1477 sc.close();
1478 report("Reset test");
1479 }
1480
1481 public static void tokensTest() {
1482 List<String> result = new Scanner("abc def ghi").tokens().collect(Collectors.toList());
1483 if (! result.equals(Arrays.asList("abc", "def", "ghi"))) {
1484 System.out.println("not equals, failed");
1485 failCount++;
1486 }
1487
1488 result = new Scanner("###abc##def###ghi###j").useDelimiter("#+")
1489 .tokens().collect(Collectors.toList());
1490 if (! result.equals(Arrays.asList("abc", "def", "ghi", "j"))) {
1491 failCount++;
1492 }
1493
1494 result = new Scanner("abc,def,,ghi").useDelimiter(",")
1495 .tokens().collect(Collectors.toList());
1496 if (! result.equals(Arrays.asList("abc", "def", "", "ghi"))) {
1497 failCount++;
1498 }
1499
1500 report("Tokens test");
1501 }
1502
1503 public static void findAllTest() throws Exception {
1504 try (Stream<MatchResult> str = new Scanner(inputFile).findAll("[A-Z]{7,}")) {
1505 List<String> result = str.map(MatchResult::group).collect(Collectors.toList());
1506 if (! result.equals(Arrays.asList("MYGROUP", "NODELAY", "ENCRYPTION"))) {
1507 failCount++;
1508 }
1509 }
1510
1511 report("FindAll test");
1512 }
1513
1514 /*
1515 * Test that closing the stream also closes the underlying Scanner.
1516 * The cases of attempting to open streams on a closed Scanner are
1517 * covered by closeTest().
1518 */
1519 public static void streamCloseTest() throws Exception {
1520 Scanner sc;
1521
1522 sc = new Scanner("xyzzy");
1523 sc.tokens().close();
1524 try {
1525 sc.hasNext();
1526 failCount++;
1527 } catch (IllegalStateException ise) {
1528 // Correct result
1529 }
1530
1531 sc = new Scanner("xyzzy");
1532 sc.findAll("q").close();
1533 try {
1534 sc.hasNext();
1535 failCount++;
1536 } catch (IllegalStateException ise) {
1537 // Correct result
1538 }
1539
1540 report("Streams Close test");
1541 }
1542
1543 private static void report(String testName) {
1544 System.err.printf("%-30s: %s%n", testName,
1545 (failCount == 0) ? "Passed" : String.format("Failed(%d)", failCount));
1546
1547 if (failCount > 0)
1548 failure = true;
1549 failCount = 0;
1550 }
1551
1552 static Scanner scannerFor(String input, int sourceType) {
1553 if (sourceType == 1)
1554 return new Scanner(input);
1555 else
1556 return new Scanner(new StutteringInputStream(input));
1557 }
1558
1559 static class ThrowingReadable implements Readable {
1560 ThrowingReadable() {
1561 }
1562 public int read(java.nio.CharBuffer cb) throws IOException {
1563 throw new IOException("ThrowingReadable always throws");
1564 }
1565 }
1566 }
|