新闻组

How to Install and Configure INN under RedHat Linux by netkiller

news://news.9812.net

Example 4. NNTP JavaBean

package netkiller.network;

/**
 * @Author 陈景峰(Netkiller)
 *@version 
 **/

import java.net.*;
import java.io.*;
import java.util.*;
import sun.misc.*;

import javax.servlet.http.*;
import netkiller.security.*;

//javadoc -private -d doc -author -version NNTP.java

public class NNTP 
{
	private boolean debug = false;
	private boolean isConnected = false;
	private static Socket sock 		= null;
	private BufferedReader reader	= null;
	private PrintWriter writer 		= null;	
	private static int port 		= 119;
	
 	public final static String GB18030 	= "GB18030";
 	public final static String UTF8 	= "UTF-8";
 	public final static String GBK 		= "GBK";	
	
	private static final String encode = GB18030;
	//private static final String encode = "UTF-8";
	
	//private static String host	= "news.cdut.edu.cn";
	private static String host	= "news.newsfan.net";
	
	//private static String host	= "news.cn99.com";
	//private static String server	= "news.webking.com.cn";
	
	
	private static int retryTimes 	= 0;
	private StringTokenizer	st		= null;
	//private Vector v = new Vector();
	//private ArrayList al = new ArrayList();
	private String buf = null;
	
	public NNTP(){

	}
	public void setDebug(boolean bool){
		this.debug = bool;	
	}
	private void logs(Object obj){
		System.err.println(obj);	
	}
/**
 * 连接服务器
 **/	
	public void Connect(){
		try{
			sock = new Socket(host,port);
			sock.setSoTimeout(600000);
			//System.out.print(sock);
			reader = new BufferedReader(new InputStreamReader(sock.getInputStream(),encode));
			writer = new PrintWriter(sock.getOutputStream(),true);					
		}catch(Exception e){
			e.printStackTrace();
		}		
	}

/**
 * 连接服务器
 * @param host 服务器地址,ip 或 域名
 * @param port 端口
 * @return boolean false / ture
 **/
	public boolean Connect(String host,int port){
		boolean isConnect = false;
		try{
			sock = new Socket(host,port);
			sock.setSoTimeout(600000);
			//System.out.println(sock);
			reader = new BufferedReader(new InputStreamReader(sock.getInputStream(),encode));
			writer = new PrintWriter(sock.getOutputStream(),true);	
			if(sock != null){
				isConnect = true;
			}				
		}
		
		catch(java.net.UnknownHostException unknown){
			unknown.printStackTrace();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return isConnect;	
	}

/**
 * 连接服务器
 * @param host 服务器地址,ip 或 域名 ,端口默认119
 * @return boolean false / ture
 **/	
	public boolean Connect(String host){
		return Connect(host,119);
		//HttpServletRequest req;
		//HttpSession host = req.getSession().getAttribute();
		//System.out.println((String)host.getAttribute("newshost"));	
		//System.out.println((String)req.getSession().getAttribute("newshost"));	
	}
	
/**
 * 关闭socket and stream (连接与流)
 * @param 
 * @return
 * @exception Cannot complete Session:Too many tries!
 **/	
	public void close()throws Exception{
		try{
			writer.println("QUIT");
			/*
			while((buf = reader.readLine()) != null) {
				System.out.println(buf);
			}
			*/
			if(writer != null)writer.close();
			if(reader != null)reader.close();
			if(sock != null)sock.close();
			if(retryTimes++ == 10) throw new Exception("Cannot complete Session:Too many tries!");
		}catch(Exception ex){
		}		
	}

/**
 * MODE reader
 * @param 
 * @return void
 **/		
	public void setModeReader(){
		//writer.flush();
		writer.println("MODE reader");
		if(debug){
			//System.err.println(reader.readLine());
		}
	}

/**
 * 列出组列表
 * @param 
 * @return Vector
 * cn.comp.linux.development <br>
 * cn.comp.linux.install <br>
 * cn.comp.linux.admin <br>
 * cn.comp.linux.misc <br>
 * cn.comp.linux.application <br>
 * cn.comp.freebsd <br>
 * cn.comp.minix <br>
 * cn.comp.solaris.admin <br>
 * cn.comp.lang.c <br>
 * cn.comp.lang.php <br>
 * cn.comp.lang.perl <br>
 * cn.comp.lang.python <br>
 * cn.comp.lang.java.development <br>
 * cn.comp.lang.java.jsp <br>
 **/		
	public Vector getNewsList(){
		Vector v = new Vector();
		String tmp = null;
		int n = 1;
		try{
			writer.println("LIST");
			while((buf = reader.readLine()) != null) {
				if(debug){
					System.err.println(buf);
				}				
				if(n>2){
					st = new StringTokenizer(buf);
					st.hasMoreTokens();
					tmp = st.nextToken(" ").toString();
					if(tmp.equals("."))break;

					//v.add(this.Base64Encoder(tmp));
					v.add(tmp);
					st.nextToken();
				}	
				n++;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		finally{
			try{
				//this.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		return v;
	}	
	
/**
 * 打开组
 * @param newsgroup 新闻组
 * @return boolean true 组存在,false 组不存在
 * 使用方法: 
 * getNewsList()
 * cn.comp.freebsd <br>
 * cn.comp.solaris.admin <br>
 * cn.comp.lang.c <br>
 *
 * setNewsGroup("cn.comp.freebsd")
 * @see getNewsList()
 **/		
	public boolean setNewsGroup(String newsgroup){
		boolean isSuccess = false;
		try{
			writer.println("GROUP "+newsgroup);
			//writer.println("\r\n");
			//"group cn.comp.lang.c"
			//211 2 6 7 cn.comp.lang.php
			//501 newsgroup
			buf = reader.readLine();
			if(buf.substring(0,3).equals("211")){
				isSuccess = true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return isSuccess;
	}
	
/**
 * 列出当前新闻组内的所有文章ID
 * @return ArrayList 文章ID
 * @see setNewsGroup(String newsgroup)
 **/
	public ArrayList getNewsListGroup(){
		ArrayList al = new ArrayList();
		try{
			writer.println("LISTGROUP");
			//listgroup cn.comp.lang.c
			//211 Article list follows
			while((buf = reader.readLine()) != null) {
				if(buf.equals("."))break;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return al;
	}	
/**
 * 列出 某 新闻组内的所有文章ID
 * @param newsgroup 
 * @return ArrayList 文章ID
 * @see getNewsList()
 * @see setNewsGroup(String newsgroup)
 **/	
	public Vector getNewsListGroup(String newsgroup){
		Vector v = new Vector();
		boolean isAdd = false;
		int i =0;
		try{
			buf = reader.readLine();
			this.logs(buf);
			writer.println("LISTGROUP "+newsgroup);
			
			// writer.flush();
			//System.err.println(writer.checkError());
			
			//listgroup cn.comp.lang.c
			//211 Article list follows
			while((buf = reader.readLine()) != null) {
				//System.err.println("buffer:"+buf);
				if(buf.equals("."))break;
				//211 Article list follows
				//211 list of article numbers follow
				if(buf.length()>3){
					if(buf.substring(0,3).equals("211")){
						isAdd = true;
						continue;
					}
					if(buf.substring(0,3).equals("412")){
						isAdd = false;
						System.err.println(buf +":"+ newsgroup);
						break;
					}
					if(buf.substring(0,3).equals("500")){
						isAdd = false;
						System.err.println(buf);
						break;
					}					
				}
				if(isAdd)v.add(buf);
				if(i++>50)break;
			}			

		}catch(Exception e){
			e.printStackTrace();
		}
		return v;
	}

/**
 * 通过文章ID取得Subject(标题)
 * @param Number 文章ID 
 * @return String 文章标题
 * @see getNewsListGroup()
 * @see getNewsListGroup(String newsgroup)
 **/
	public String getNewsTitle(String Number){
		String strTitle = "";
		try{
			writer.println("HEAD "+Number);
			//listgroup cn.comp.lang.c
			//211 Article list follows
			//buf = reader.readLine();
			while((buf = reader.readLine()) != null) {
				if(buf.equals("."))break;
				if(buf.length()>8){
					if(buf.substring(0,8).equals("Subject:")){
						strTitle = buf.substring(9);
					}
				}
			}			

		}catch(Exception e){
			e.printStackTrace();
		}
		return strTitle;	
	}

	public HashMap getNewsTitle(Vector vector){
		HashMap newsSubject = new HashMap();
		try{
			Enumeration enum = vector.elements();
			while(enum.hasMoreElements()){
				String id = (String)enum.nextElement();
				reader.reset();
				writer.println("HEAD "+id);
				while((buf = reader.readLine()) != null) {
					if(buf.equals("."))break;
					if(buf.length()>8){
						if(buf.substring(0,8).equals("Subject:")){
							newsSubject.put(id,buf.substring(9));
						}
					}
				}
			}			

		}catch(Exception e){
			e.printStackTrace();
		}
		return newsSubject;	
	}

/**
 * 返回文章信息头内容
 * @param Number 文章ID 
 * @return Vector 信息头
 * <br>
 * Path: octopus!not-for-mail <br>
 * From: [email protected]<br>
 * Newsgroups: cn.comp.lang.c<br>
 * Subject: ■ web news 测试■<br>
 * Date: 3 Jul 2003 10:09:55 GMT<br>
 * Organization: Chengdu Univ. of Technology.<br>
 * Lines: 394<br>
 * Message-ID: <[email protected]><br>
 * NNTP-Posting-Host: 202.103.190.130<br>
 * X-Trace: octopus.cdut.edu.cn 1057226995 27398 202.103.190.130 (3 Jul 2003 10:09:55 GMT)<br>
 * X-Complaints-To: [email protected]<br>
 * NNTP-Posting-Date: 3 Jul 2003 10:09:55 GMT<br>
 * Xref: octopus cn.comp.lang.c:29 <br>
 *
 * @see getNewsListGroup()
 * @see getNewsListGroup(String newsgroup)
 **/	
	public Vector getNewsHead(String Number){
		Vector vector 			= new Vector();
		boolean sw = true;
		try{
			writer.println("HEAD "+Number);
			buf = reader.readLine();
			buf = reader.readLine();
			while((buf = reader.readLine()) != null) {
				if(buf.equals("."))break;
				/*
				if(buf.length()>4 && !buf.substring(0,4).equals("Path") && sw){
					sw = false;
					continue;	
				}*/
				vector.add(buf);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return vector;		
	}
/*		
	public String[][] getNewsHead(String Number){
		Vector vector 			= new Vector();
		String arrNewsHead[][]	= new String[64][2];
		StringTokenizer token 	= null;
		boolean sw = true;
		try{
			writer.println("HEAD");
			//listgroup cn.comp.lang.c
			for(int i=0;(buf = reader.readLine()) != null;i++) {
				if(buf.length()>4 && !buf.substring(0,4).equals("Path") && sw){
					sw = false;
					continue;	
				}
				if(buf.length()<3)break;
				token = new StringTokenizer(buf);
				//if(!token.hasMoreTokens())break;
				arrNewsHead[i][0] = token.hasMoreTokens()?(String)token.nextToken():"";
				arrNewsHead[i][1] = token.hasMoreTokens()?(String)token.nextToken():"";
				//System.out.print(arrNewsHead[i][0]);
				//System.out.println(arrNewsHead[i][1]);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return arrNewsHead;		
	}
*/

/**
 * 返回文章内容
 * @param Number 文章ID 
 * @return Vector 文章内容
 *
 * @see getNewsListGroup()
 * @see getNewsListGroup(String newsgroup)
 **/	
	private Vector getNewsBody(String Number){
		Vector v = new Vector();
		String strTitle = "";
		boolean isAdd = false;
		try{
			writer.println("BODY "+Number);
			while((buf = reader.readLine()) != null) {
				if(buf.length()>3){
					if(buf.substring(0,3).equals("222")){
						isAdd = true;
						continue;
					}
				}
				if(buf.equals("."))break;
				if(isAdd)v.add(buf);			
			}			

		}catch(Exception e){
			e.printStackTrace();
		}
		return v;
	}

/**
 * 返回文章内容
 * @param Number 文章ID 
 * @return Vector 文章内容
 *
 * @see getNewsContent(String Number)
 * @see getNewsArticle(String Number)
 **/	
	public Vector getNewsContent(String Number){
		return this.getNewsBody(Number);
	}
	
/**
 * 返回文章全文内容
 * @param Number 文章ID 
 * @return Vector 文章全文内容
 *
 * @see getNewsContent(String Number)
 **/			
	public Vector getNewsArticle(String Number){
		Vector v = new Vector();
		//article <[email protected]>
		//article 6
		try{
			writer.println("ARTICLE "+Number);
			buf = reader.readLine();
			while((buf = reader.readLine()) != null) {
				if(buf.equals("."))break;
				//if(buf.equals("211 Article list follows")){}
				v.add(buf);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return v;
	}
/**
 * 下一篇文章
 * @param 
 * @return 
 **/	
	public void setNewsNext(){
		//223 6 <[email protected]> Article retrieved; request text separately.
		//421 No next to retrieve.
		try{
			writer.println("NEXT");
			//listgroup cn.comp.lang.c
			//while((buf = reader.readLine()) != null) {
			//	buf.substring(0,3);
			//}
		}catch(Exception e){
			e.printStackTrace();
		}
		//return "1";	
	}
	
/**
 * 发表新帖
 * @param from 用户Email,回信地址
 * @param group 组目的地
 * @param subject 标题
 * @param content 内容
 * @return boolean true发贴成功,false 发贴失败
 * <br>setPostNews("[email protected]","cn.comp.linux.admin","hi all test","chen \n chen \n 中国防大学!!!!! \n"); 
 **/	
	public boolean setPostNews(String from,String group,String subject,String content){
		boolean isSuccess = false;
		try{
			setModeReader();
			writer.println("POST");
			writer.println("From: "+from);
			writer.println("Newsgroups: "+group);
			writer.println("Subject: "+subject);
			writer.println("");
			writer.println(content);
			writer.println(".");
			writer.println("QUIT");
			while((buf = reader.readLine()) != null) {
				if(buf.substring(0,3).equals("240"))
				isSuccess = true;
				//System.out.println("Article posted");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return isSuccess;	
	}

/**
 * 回复组 , 回复用户的帖子
 * @param from 用户Email,回信地址
 * @param group 组目的地
 * @param subject 标题
 * @param content 内容
 * @param ref 参考Message-ID,就是原贴Message-ID
 * @return boolean true发贴成功,false 发贴失败
 * <br>setPostNews("[email protected]","cn.comp.linux.admin","hi all test","chen \n chen \n 中国防大学!!!!! <br>","<[email protected]>");
 * Message-ID: <[email protected]><br>
 * References: <[email protected]><br>
 **/	
	public boolean setReNews(String from,String group,String subject,String content,String ref){
		boolean isSuccess = false;
		try{
			setModeReader();
			writer.println("POST");
			writer.println("From: "+from);
			writer.println("Newsgroups: "+group);
			writer.println("Subject: "+subject);
			writer.println("References: "+ref);
			writer.println("");
			writer.println(content);
			writer.println(".");
			writer.println("QUIT");
			while((buf = reader.readLine()) != null) {
				if(buf.substring(0,3).equals("240"))
				isSuccess = true;
				//System.out.println("Article posted");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return isSuccess;	
	}
/**
 * 查看文章状态
 * @param Number 文章ID
 * @return String 文件ID,Message-ID:,status
 **/	
	public String getNewsStat(String Number){
		String stat = null;
		try{
			setModeReader();
			writer.println("STAT "+Number);
			while((buf = reader.readLine()) != null) {
				if(buf.substring(0,3).equals("223")){
					stat = buf;
					System.out.println(buf);
					//System.out.println("Article posted");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return stat;
	}
/**
 * ISO-8859-1 ==> GBK
 **/
 	
	public String toUnicode(String in,String out,String strSource){
		String strTarget = null;
		try{
			strTarget = new String(strSource.getBytes(in),out); 
		}catch(Exception e){
			e.printStackTrace();
		}
		return strTarget;
	}

/**
 * ISO-8859-1 ==> GBK
 * @see toGBK(String strSource)
 **/
	public static String toChinese(String strvalue)
   	{
        try{
            if(strvalue==null)
               return null;
            else
            {
               strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
               return strvalue;
        }
        }catch(Exception e){
              return null;
        }
   	}
/*	
	public static void checkStatus(String msg) throws Exception
	{
		System.out.println(msg);
		if (msg.substring(0,3).equals("+OK"))
		return;
		else 
		throw new Exception("Cannot Complete Session!");
	}

	public static void performSession() throws Exception
	{
			if(retryTimes++ == 10) throw new Exception("Cannot complete Session:Too many tries!");
			performSession();
		}
	}
*/	
	public static String toUnicode(String value){ 
    	try{ 
            if(value!=null) {
                 value = new String(value.getBytes("ISO8859_1"), "UTF-8");
        	}
        }catch(Exception e){ 
              return null; 
        } 
        return value; 
   	}   
	public static final String Base64Encoder(String code) {
		String tmp = null;
		try{
			tmp = new sun.misc.BASE64Encoder().encode(code.getBytes());
		}
		catch(Exception e){
			System.out.println(e.toString());
		}
		return tmp;
	}

	public static final String Base64Decoder(String code) {
		String tmp = null;
		try{

			tmp = new String(new sun.misc.BASE64Decoder().decodeBuffer(code)).toString();

		}
		catch(Exception e){
			System.out.println(e.toString());
		}
		return tmp;
	}	

	public static void main(String[] args) 
	{
		try{
/*			
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter writer = new BufferedWriter((System.out),true);
		//BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out),true);
		writer.print("Enter The POP3 Server:");
		server = reader.readLine();
		writer.print("Enter The Server Port (default is 110):");
		String tmp = reader.readLine();
		try{
		port = Integer.parseInt(tmp);
		}
		catch(Exception e){
		}
		writer.print("Enter Your Username:");
		userid = reader.readLine();
		writer.print("Enter Your Password:");
		passwd = reader.readLine();
		reader.close();
*/		
		//performSession();
			NNTP n = new NNTP();
			n.setDebug(true);
			n.Connect();
			Vector v = new Vector();
			System.out.print(n.Connect("news.newsfan.net",119));
			
			n.setModeReader();
			
			v = n.getNewsList();
			
			for(int i=0;i<v.size();i++){
				System.out.println((String)v.get(i));
			}
			
			
			//n.setNewsGroup("cn.comp.lang.python");
			
			System.out.println(n.setNewsGroup("测试中文"));
			
			//System.out.println(n.getNewsStat("24"));
			//n.getNewsHead("24");
			//ArrayList al = n.getNewsListGroup();
			
			//v = n.getNewsListGroup("精华信区.计算机");
			//v = n.getNewsListGroup("测试中文");
			//v = n.getNewsListGroup("1950");
			
			//Vector v = n.getNewsListGroup("cn.comp.linux.admin");
			/*
			System.out.println(v.size());
			for(int i=0;i<v.size();i++){
				System.out.print(i+">"+(String)v.get(i));
				//System.out.println(n.getNewsTitle((String)v.get(i)));
			}*/
			/*
			for(int i=0;i<v.size();i++){
				
			}
			*/
			//System.out.println(n.getNewsTitle("4370"));
			
			//Vector v = n.getNewsArticle("20");
			
			//Vector v = n.getNewsArticle("24");
			//Vector v = n.getNewsHead("33");
			/*
			for(int i=0;i<v.size();i++){
				System.out.println((String)v.get(i));
			}
			*/
			//n.setPostNews("[email protected]","cn.comp.linux.admin","hi all test","chen \n chen \n 中国防大学!!!!! \n"); 
			/*
			String head[][] =null;
			 head = n.getNewsHead("24");
			for(int i=0;i<head.length;i++){
				System.out.print(head[i][0]);
			}
			*/
			n.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Done");
	}
}