1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. 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 */
18
19 package org.apache.commons.net.nntp;
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.util.Iterator;
24 import java.util.NoSuchElementException;
25
26 import org.apache.commons.net.io.DotTerminatedMessageReader;
27 import org.apache.commons.net.io.Util;
28
29 /**
30 * Wraps a {@link BufferedReader} and returns an {@code Iterable<String>}
31 * which returns the individual lines from the reader.
32 * @since 3.0
33 */
34 class ReplyIterator implements Iterator<String>, Iterable<String> {
35
36 private final BufferedReader reader;
37
38 private String line;
39
40 private Exception savedException;
41
42 /**
43 *
44 * @param _reader the reader to wrap
45 * @param addDotReader whether to additionally wrap the reader in a DotTerminatedMessageReader
46 * @throws IOException
47 */
48 ReplyIterator(BufferedReader _reader, boolean addDotReader) throws IOException {
49 reader = addDotReader ? new DotTerminatedMessageReader(_reader) : _reader;
50 line = reader.readLine(); // prime the iterator
51 if (line == null) {
52 Util.closeQuietly(reader);
53 }
54 }
55
56 ReplyIterator(BufferedReader _reader) throws IOException {
57 this(_reader, true);
58 }
59
60 // @Override
61 public boolean hasNext() {
62 if (savedException != null){
63 throw new NoSuchElementException(savedException.toString());
64 }
65 return line != null;
66 }
67
68 // @Override
69 public String next() throws NoSuchElementException {
70 if (savedException != null){
71 throw new NoSuchElementException(savedException.toString());
72 }
73 String prev = line;
74 if (prev == null) {
75 throw new NoSuchElementException();
76 }
77 try {
78 line = reader.readLine(); // save next line
79 if (line == null) {
80 Util.closeQuietly(reader);
81 }
82 } catch (IOException ex) {
83 savedException = ex; // if it fails, save the exception, as it does not apply to this call
84 Util.closeQuietly(reader);
85 }
86 return prev;
87 }
88
89 // @Override
90 public void remove() {
91 throw new UnsupportedOperationException();
92 }
93
94 // @Override
95 public Iterator<String> iterator() {
96 return this;
97 }
98 }