blob: 22a7b6d1795af67ec2c3d9552fb73e5d612ec5f1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
/*
* Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package jline;
import java.io.*;
import java.util.*;
/**
* An {@link InputStream} implementation that wraps a {@link ConsoleReader}.
* It is useful for setting up the {@link System#in} for a generic
* console.
* @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a>
*/
public class ConsoleReaderInputStream extends SequenceInputStream {
private static InputStream systemIn = System.in;
public static void setIn() throws IOException {
setIn(new ConsoleReader());
}
public static void setIn(final ConsoleReader reader) {
System.setIn(new ConsoleReaderInputStream(reader));
}
/**
* Restore the original {@link System#in} input stream.
*/
public static void restoreIn() {
System.setIn(systemIn);
}
public ConsoleReaderInputStream(final ConsoleReader reader) {
super(new ConsoleEnumeration(reader));
}
private static class ConsoleEnumeration implements Enumeration {
private final ConsoleReader reader;
private ConsoleLineInputStream next = null;
private ConsoleLineInputStream prev = null;
public ConsoleEnumeration(final ConsoleReader reader) {
this.reader = reader;
}
public Object nextElement() {
if (next != null) {
InputStream n = next;
prev = next;
next = null;
return n;
}
return new ConsoleLineInputStream(reader);
}
public boolean hasMoreElements() {
// the last line was null
if ((prev != null) && (prev.wasNull == true)) {
return false;
}
if (next == null) {
next = (ConsoleLineInputStream) nextElement();
}
return next != null;
}
}
private static class ConsoleLineInputStream extends InputStream {
private final ConsoleReader reader;
private String line = null;
private int index = 0;
private boolean eol = false;
protected boolean wasNull = false;
public ConsoleLineInputStream(final ConsoleReader reader) {
this.reader = reader;
}
public int read() throws IOException {
if (eol) {
return -1;
}
if (line == null) {
line = reader.readLine();
}
if (line == null) {
wasNull = true;
return -1;
}
if (index >= line.length()) {
eol = true;
return '\n'; // lines are ended with a newline
}
return line.charAt(index++);
}
}
}
|