1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.example.lines;
18
19 import java.io.BufferedReader;
20 import java.io.File;
21 import java.io.FileNotFoundException;
22 import java.io.FileReader;
23 import java.io.Reader;
24
25 import org.apache.commons.functor.UnaryProcedure;
26 import org.apache.commons.functor.generator.BaseGenerator;
27
28
29
30
31
32 public class Lines extends BaseGenerator<String> {
33 public static Lines from(Reader reader) {
34 return new Lines(reader);
35 }
36
37 public static Lines from(File file) throws FileNotFoundException {
38 return new Lines(new FileReader(file));
39 }
40
41 public Lines(Reader reader) {
42 if (reader instanceof BufferedReader) {
43 in = (BufferedReader) reader;
44 } else {
45 in = new BufferedReader(reader);
46 }
47 }
48
49 public void run(UnaryProcedure<? super String> proc) {
50 try {
51 for (String line = in.readLine(); line != null; line = in.readLine()) {
52 proc.run(line);
53 }
54 } catch(RuntimeException e) {
55 throw e;
56 } catch(Exception e) {
57 throw new TunneledException(e);
58 } finally {
59 stop();
60 }
61 }
62
63 public void stop() {
64 super.stop();
65 try {
66 in.close();
67 } catch(RuntimeException e) {
68 throw e;
69 } catch(Exception e) {
70 throw new TunneledException(e);
71 }
72 }
73
74 private BufferedReader in = null;
75
76 private class TunneledException extends RuntimeException {
77 private Exception exception = null;
78 TunneledException(Exception exception) {
79 super(exception.toString());
80 this.exception = exception;
81 }
82
83
84
85
86 public Throwable getCause() {
87 return exception;
88 }
89 }
90 }