1 /**
2 *
3 * Copyright 2006 The Apache Software Foundation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * 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 package org.apache.geronimo.javamail.transport.nntp;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.UnsupportedEncodingException;
22 import java.util.List;
23
24 /**
25 * @version $Rev: 432884 $ $Date: 2006-08-19 14:53:20 -0700 (Sat, 19 Aug 2006) $
26 */
27 public class StringListInputStream extends InputStream {
28
29 protected List lines;
30
31
32 protected int nextLine = 0;
33
34
35 byte[] buffer;
36
37
38 int offset;
39
40
41
42 boolean atLineBreak = false;
43
44 public StringListInputStream(List lines) throws IOException {
45 this.lines = lines;
46 nextLine = 0;
47 buffer = null;
48 offset = 0;
49 atLineBreak = false;
50
51
52 if (lines.size() > 0) {
53 nextBuffer();
54 }
55 }
56
57 /**
58 * Just override the single byte read version, which handles all of the
59 * lineend markers correctly.
60 *
61 * @return The next byte from the stream or -1 if we've hit the EOF.
62 */
63 public int read() throws IOException {
64
65 if (atLineBreak) {
66
67
68 atLineBreak = false;
69 nextBuffer();
70 return '\n';
71 }
72
73 if (buffer == null) {
74 return -1;
75 }
76
77
78 if (offset >= buffer.length) {
79
80 atLineBreak = true;
81 return '\r';
82 }
83
84 return buffer[offset++];
85
86 }
87
88 /**
89 * Step to the next buffer of string data.
90 *
91 * @exception IOException
92 */
93 protected void nextBuffer() throws IOException {
94
95 if (nextLine >= lines.size()) {
96 buffer = null;
97 } else {
98 try {
99 String next = (String) lines.get(nextLine++);
100 buffer = next.getBytes("US-ASCII");
101
102 } catch (UnsupportedEncodingException e) {
103 throw new IOException("Invalid string encoding");
104 }
105 }
106
107 offset = 0;
108 }
109 }