01: package gnu.mapping;
02:
03: import java.io.*;
04: import gnu.text.*;
05: import gnu.lists.Consumer;
06:
07: public class InPort extends gnu.text.LineBufferedReader implements
08: Printable {
09: public InPort(Reader in) {
10: super (in);
11: }
12:
13: public InPort(Reader in, Path path) {
14: this (in);
15: setPath(path);
16: }
17:
18: public InPort(InputStream in) {
19: super (in);
20: }
21:
22: public InPort(InputStream in, Path path) {
23: this (in);
24: setPath(path);
25: }
26:
27: public static Reader convertToReader(InputStream in, Object conv) {
28: if (conv != null && conv != Boolean.TRUE) {
29: String enc = (conv == Boolean.FALSE ? "8859_1" : conv
30: .toString());
31: try {
32: return new java.io.InputStreamReader(in, enc);
33: } catch (java.io.UnsupportedEncodingException ex) {
34: throw new RuntimeException(
35: "unknown character encoding: " + enc);
36: }
37: }
38: return new java.io.InputStreamReader(in);
39: }
40:
41: public InPort(InputStream in, Path path, Object conv)
42: throws java.io.UnsupportedEncodingException {
43: this (convertToReader(in, conv), path);
44: if (conv == Boolean.FALSE) {
45: // Use a fixed-size buffer. This prevents really-long "lines"
46: // from causing the buffer to grow to accomodate them.
47: try {
48: setBuffer(new char[2048]);
49: } catch (java.io.IOException ex) { /* ignored */
50: }
51: } else
52: setConvertCR(true);
53: }
54:
55: private static InPort systemInPort = new TtyInPort(System.in, Path
56: .valueOf("/dev/stdin"), OutPort.outInitial);
57: public static final ThreadLocation inLocation = new ThreadLocation(
58: "in-default");
59: static {
60: inLocation.setGlobal(systemInPort);
61: }
62:
63: static public InPort inDefault() {
64: return (InPort) inLocation.get();
65: }
66:
67: static public void setInDefault(InPort in) {
68: inLocation.set(in);
69: }
70:
71: public static InPort openFile(Object fname)
72: throws java.io.IOException {
73: Path path = Path.valueOf(fname);
74: java.io.InputStream strm = path.openInputStream();
75: strm = new java.io.BufferedInputStream(strm);
76: return openFile(strm, path);
77: }
78:
79: public static InPort openFile(InputStream strm, Object fname)
80: throws java.io.UnsupportedEncodingException {
81: return new InPort(strm, Path.valueOf(fname), Environment.user()
82: .get("port-char-encoding"));
83: }
84:
85: public void print(Consumer out) {
86: out.write("#<input-port");
87: String name = getName();
88: if (name != null) {
89: out.write(' ');
90: out.write(name);
91: }
92: out.write('>');
93: }
94: }
|