1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.net.nntp;
19
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.util.Iterator;
23 import java.util.NoSuchElementException;
24
25 import org.apache.commons.net.io.DotTerminatedMessageReader;
26 import org.apache.commons.net.io.Util;
27
28
29
30
31
32
33 class ReplyIterator implements Iterator<String>, Iterable<String> {
34
35 private final BufferedReader reader;
36
37 private String line;
38
39 private Exception savedException;
40
41 ReplyIterator(final BufferedReader _reader) throws IOException {
42 this(_reader, true);
43 }
44
45
46
47
48
49
50
51 ReplyIterator(final BufferedReader _reader, final boolean addDotReader) throws IOException {
52 reader = addDotReader ? new DotTerminatedMessageReader(_reader) : _reader;
53 line = reader.readLine();
54 if (line == null) {
55 Util.closeQuietly(reader);
56 }
57 }
58
59 @Override
60 public boolean hasNext() {
61 if (savedException != null) {
62 throw new NoSuchElementException(savedException.toString());
63 }
64 return line != null;
65 }
66
67 @Override
68 public Iterator<String> iterator() {
69 return this;
70 }
71
72 @Override
73 public String next() throws NoSuchElementException {
74 if (savedException != null) {
75 throw new NoSuchElementException(savedException.toString());
76 }
77 final String prev = line;
78 if (prev == null) {
79 throw new NoSuchElementException();
80 }
81 try {
82 line = reader.readLine();
83 if (line == null) {
84 Util.closeQuietly(reader);
85 }
86 } catch (final IOException ex) {
87 savedException = ex;
88 Util.closeQuietly(reader);
89 }
90 return prev;
91 }
92
93 @Override
94 public void remove() {
95 throw new UnsupportedOperationException();
96 }
97 }