Debian Codegraph @

src/main/java/jnr/netdb/NetDBIterator.java

raw
1 /*
2 * Copyright (C) 2010 Wayne Meissner
3 *
4 * This file is part of jnr.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package jnr.netdb;
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.Reader;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.NoSuchElementException;
28
29 final class NetDBIterator implements java.util.Iterator<NetDBEntry> {
30
31 private final BufferedReader reader;
32 private NetDBEntry next = null;
33
34 public NetDBIterator(Reader r) {
35 this.reader = r instanceof BufferedReader ? (BufferedReader) r : new BufferedReader(r);
36 }
37
38 NetDBEntry readNextEntry() throws IOException {
39 String s = null;
40
41 while ((s = reader.readLine()) != null) {
42
43 String[] line = s.split("#", 2);
44 // Skip empty lines, or lines that are all comment
45 if (line.length < 1 || line[0].length() == 0) {
46 continue;
47 }
48
49 String[] fields = line[0].trim().split("\\s+");
50 if (fields.length < 2 || fields[0] == null || fields[1] == null) {
51 continue;
52 }
53
54 String serviceName = fields[0];
55 String data = fields[1];
56 List<String> aliases;
57 if (fields.length > 2) {
58 aliases = new ArrayList<String>(fields.length - 2);
59 for (int i = 2; i < fields.length; ++i) {
60 if (fields[i] != null) {
61 aliases.add(fields[i]);
62 }
63 }
64 } else {
65 aliases = Collections.emptyList();
66 }
67
68 return new NetDBEntry(serviceName, data, aliases);
69 }
70
71 return null;
72 }
73
74 public boolean hasNext() {
75 try {
76 return next != null || (next = readNextEntry()) != null;
77 } catch (IOException ex) {
78 return false;
79 }
80 }
81
82 public NetDBEntry next() {
83 try {
84 NetDBEntry s = next != null ? next : readNextEntry();
85 if (s == null) {
86 throw new NoSuchElementException("not found");
87 }
88 next = null;
89
90 return s;
91
92 } catch (IOException ex) {
93 throw new NoSuchElementException(ex.getMessage());
94 }
95 }
96
97 public void remove() {
98 throw new UnsupportedOperationException("Not supported yet.");
99 }
100 }