01: package examples.nntp;
02:
03: import java.io.BufferedReader;
04: import java.io.IOException;
05: import java.io.Reader;
06: import java.util.StringTokenizer;
07:
08: import org.apache.commons.net.io.DotTerminatedMessageReader;
09: import org.apache.commons.net.nntp.Article;
10: import org.apache.commons.net.nntp.NNTPClient;
11:
12: /**
13: *
14: * Some convenience methods for NNTP example classes.
15: *
16: * @author Rory Winston <rwinston@checkfree.com>
17: */
18: public class NNTPUtils {
19:
20: /**
21: * Given an {@link NNTPClient} instance, and an integer range of messages, return
22: * an array of {@link Article} instances.
23: * @param client
24: * @param lowArticleNumber
25: * @param highArticleNumber
26: * @return Article[] An array of Article
27: * @throws IOException
28: */
29: public static Article[] getArticleInfo(NNTPClient client,
30: int lowArticleNumber, int highArticleNumber)
31: throws IOException {
32: Reader reader = null;
33: Article[] articles = null;
34: reader = (DotTerminatedMessageReader) client
35: .retrieveArticleInfo(lowArticleNumber,
36: highArticleNumber);
37:
38: if (reader != null) {
39: String theInfo = readerToString(reader);
40: StringTokenizer st = new StringTokenizer(theInfo, "\n");
41:
42: // Extract the article information
43: // Mandatory format (from NNTP RFC 2980) is :
44: // Subject\tAuthor\tDate\tID\tReference(s)\tByte Count\tLine Count
45:
46: int count = st.countTokens();
47: articles = new Article[count];
48: int index = 0;
49:
50: while (st.hasMoreTokens()) {
51: StringTokenizer stt = new StringTokenizer(st
52: .nextToken(), "\t");
53: Article article = new Article();
54: article.setArticleNumber(Integer.parseInt(stt
55: .nextToken()));
56: article.setSubject(stt.nextToken());
57: article.setFrom(stt.nextToken());
58: article.setDate(stt.nextToken());
59: article.setArticleId(stt.nextToken());
60: article.addHeaderField("References", stt.nextToken());
61: articles[index++] = article;
62: }
63: } else {
64: return null;
65: }
66:
67: return articles;
68: }
69:
70: /**
71: * Convert a {@link Reader} instance to a String
72: * @param reader The Reader instance
73: * @return String
74: */
75: public static String readerToString(Reader reader) {
76: String temp = null;
77: StringBuffer sb = null;
78: BufferedReader bufReader = new BufferedReader(reader);
79:
80: sb = new StringBuffer();
81: try {
82: temp = bufReader.readLine();
83: while (temp != null) {
84: sb.append(temp);
85: sb.append("\n");
86: temp = bufReader.readLine();
87: }
88: } catch (IOException e) {
89: e.printStackTrace();
90: }
91:
92: return sb.toString();
93: }
94: }
|