调试WatchBBS:
去掉swing部分,稍微修改了一下代码。
调试结果:成功!
理解代码程度:中
详细代码:
- import java.util.Date;
- import javax.swing.SwingUtilities;
- import com.heaton.bot.HTMLParser;
- import com.heaton.bot.HTMLTag;
- import com.heaton.bot.HTTPSocket;
- /**
- * This is a simple bot program that is designed
- * to work with one specific site.
- */
- public class WatchBBS implements Runnable {
- Date _latest = null;
- Date _nextPoll;
- Thread _thread;
- String _url="http://bbs.redhome.cc/forumdisplay.php?fid=13";
- String _minutes="1";
- public WatchBBS()
- {
- Start_actionPerformed();
- }
- public static void main(String[]args)
- {
- new WatchBBS();
- }
- void Start_actionPerformed()
- {
- if ( _latest==null ) {
- _latest = getLatestDate();
- if ( _latest==null )
- return;
- }
- if ( !setNextPoll() )
- return;
- _thread = new Thread(this);
- _thread.start();
- }
- /**
- * Called when the stop button is clicked.
- * This method stops the background thread.
- *
- * @param event
- * @throws InterruptedException
- */
- void Stop_actionPerformed(java.awt.event.ActionEvent event) throws InterruptedException
- {
- /*
- * The method stop() from the type Thread is deprecated(弃用)
- */
- //_thread.stop();
- //Thread.yield();
- _thread.join();
- }
- /**
- * Called when the Poll Now button is cliked. Also
- * called when the background thread determines that
- * it is time to poll again.
- * 当时间到,或者按下Poll键,则会执行此函数。
- * 主要方法就是:再一次到网页里面抓取时间,然后与
- * 上一次抓取的时间进行比较,不同则说明有新消息进来。
- *
- * @param event The event.
- */
- void Go_actionPerformed()
- {
- setNextPoll();
- Date update = getLatestDate();
- if ( !update.toString().equalsIgnoreCase(_latest.toString()) ) {
- _latest = update;
- Runnable doit = new Runnable()
- {
- public void run()
- {
- System.out.println("there is a new message");
- }
- };
- SwingUtilities.invokeLater(doit);
- }
- }
- protected Date getLatestDate()
- {
- HTTPSocket http;
- /*
- public Date(int year,
- int month,
- int day)已过时。 使用构造方法 Date(long date) 替代
- */
- Date latest = new Date(0);
- try {
- http = new HTTPSocket();
- http.send(_url,null);
- } catch ( Exception e ) {
- e.printStackTrace();
- return null;
- }
- HTMLParser parse = new HTMLParser();
- /*
- * 开始解析网页。
- */
- parse.source = new StringBuffer(http.getBody());
- int foundTag = 0;
- String date = "";
- // find all the tags
- while ( !parse.eof() )
- {
- char ch = parse.get();
- if ( ch==0 )
- {
- /*
- * 得到tag
- */
- HTMLTag tag = parse.getTag();
- /*
- * 样例如下:
- * <em><a href="redirect.php?tid=347514&goto=lastpost#lastpost">2008-10-4 19:40</a></em>
- */
- if ( tag.getName().equalsIgnoreCase("a") ) {
- foundTag = 2;
- date="";
- //System.out.println(tag.getName());
- }
- /*
- * 执行完tag<a>,继续执行,获得date为2008-10-4 19:40。
- */
- else if ( tag.getName().equalsIgnoreCase("/em") )
- {
- //System.out.println(tag.getName());
- Date d=null;
- foundTag--;
- if ( foundTag==1 )
- {
- /*
- * 除去那些非时间参数。
- */
- if(date.indexOf(":")!=-1)
- {
- d = parseDate(date);
- }
- //System.out.println(d);
- if ( d!=null )
- {
- /*
- * 获得所有时间中最新的时间。
- */
- if ( d.after(latest) )
- latest = d;
- // System.out.println(tag.getName());
- // System.out.println(latest);
- }
- }
- }
- }
- else
- {
- if ( (ch=='/r') || (ch=='/n') )
- ch=' ';
- date+=ch;
- }
- }
- /*
- * 测验最新时间。
- */
- System.out.println(latest);
- return latest;
- }
- /**
- * Parse a date of the form:
- * September 2, 2001 5:30 PM
- * 对find的时间进行规格化。
- * @param str The string form of the date.
- * @return A Date object that was parsed.
- */
- @SuppressWarnings("deprecation")
- Date parseDate(String str)
- {
- String months[] = {"jan","feb","mar","apr","may",
- "jun","jul","aug","sep","oct","nov","dec"};
- Date rtn;
- try {
- rtn = new Date();
- // Year
- String year = str.substring(0,str.indexOf('-'));
- rtn.setYear(Integer.parseInt(year)-1900);
- // month
- str=str.substring(str.indexOf('-')+1);
- String mth = str.substring(0,str.indexOf('-'));
- for ( int i=0;i<months.length;i++ ) {
- if ( mth.toLowerCase().startsWith(months[i]) ) {
- rtn.setMonth(i);
- break;
- }
- }
- // day
- str = str.substring(str.indexOf('-')+1);
- String day = str.substring(0,str.indexOf(' '));
- rtn.setDate(Integer.parseInt(day));
- // Hour
- str = str.substring(str.indexOf(' ')+1).trim();
- String hour = str.substring(0,str.indexOf(':'));
- rtn.setHours(Integer.parseInt(hour));
- // Minute
- str = str.substring(str.indexOf(':')+1).trim();
- String minutes = str.substring(0);
- rtn.setMinutes(Integer.parseInt(minutes));
- rtn.setSeconds(0);
- // AM or PM
- /*
- str = str.substring(str.indexOf(' ')+1).trim();
- if ( str.toUpperCase().charAt(0)=='P' )
- rtn.setHours(rtn.getHours()+12);
- */
- return rtn;
- } catch ( Exception e ) {
- return null;
- }
- }
- /**
- * This run method is called to execute
- * the background thread.
- */
- public void run()
- {
- while ( true ) {
- Runnable doit = new Runnable()
- {
- public void run()
- {
- Date d = new Date();
- /*
- * 计算剩余时间的秒数。
- */
- long milli = (_nextPoll.getTime()-d.getTime())/1000;
- System.out.println("Will poll in " + milli + " seconds.");
- }
- };
- /*
- * 标准解释如下:
- true if and only if the instant of time represented by this
- Date object is strictly earlier than the instant represented
- by when
- 简单来说就是_nextPoll所对应的时间要早于new Date()即此刻时间.也就是规定的
- 时间一过,便执行Go_actionPerformed(null)函数。
- */
- if ( _nextPoll.before(new Date()) ) {
- Go_actionPerformed();
- }
- SwingUtilities.invokeLater(doit);
- try {
- Thread.sleep(1000);
- } catch ( InterruptedException e ) {
- }
- }
- }
- /**
- * Called to determine the next time
- * that a poll will take place.
- * 主要就是设定下一个poll(调查)的时间值。
- * @return True on success, false on failure.
- */
- public boolean setNextPoll()
- {
- try {
- int minutes = Integer.parseInt(_minutes);
- Date d = new Date();
- d.setMinutes(d.getMinutes()+minutes);
- _nextPoll = d;
- return true;
- } catch ( Exception e ) {
- e.printStackTrace();
- return false;
- }
- }
- }
过时的方法还有很多啊!