View Javadoc

1   /*------------------------------------------------------------------------------
2    * The contents of this file are subject to the Mozilla Public License Version
3    * 1.1 (the "License"); you may not use this file except in compliance with
4    * the License. You may obtain a copy of the License at
5    * http://www.mozilla.org/MPL/
6    * Software distributed under the License is distributed on an "AS IS" basis,
7    * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
8    * the specific language governing rights and limitations under the License.
9    *
10   * The Original Code is levelonelabs.com code.
11   * The Initial Developer of the Original Code is Level One Labs. Portions
12   * created by the Initial Developer are Copyright (C) 2001 the Initial
13   * Developer. All Rights Reserved.
14   *
15   *         Contributor(s):
16   *             Scott Oster      (ostersc@alum.rpi.edu)
17   *             Steve Zingelwicz (sez@po.cwru.edu)
18   *             William Gorman   (willgorman@hotmail.com)
19   *
20   * Alternatively, the contents of this file may be used under the terms of
21   * either the GNU General Public License Version 2 or later (the "GPL"), or
22   * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
23   * in which case the provisions of the GPL or the LGPL are applicable
24   * instead of those above. If you wish to allow use of your version of this
25   * file only under the terms of either the GPL or the LGPL, and not to allow
26   * others to use your version of this file under the terms of the NPL, indicate
27   * your decision by deleting the provisions above and replace them with the
28   * notice and other provisions required by the GPL or the LGPL. If you do not
29   * delete the provisions above, a recipient may use your version of this file
30   * under the terms of any one of the NPL, the GPL or the LGPL.
31   *----------------------------------------------------------------------------*/
32  
33  
34  package com.levelonelabs.aimbot.modules;
35  
36  
37  import java.io.BufferedReader;
38  import java.io.InputStreamReader;
39  
40  import java.net.URL;
41  import java.net.URLConnection;
42  
43  import java.util.ArrayList;
44  import java.util.StringTokenizer;
45  import java.util.logging.Logger;
46  
47  import javax.swing.text.html.HTMLEditorKit.ParserCallback;
48  import javax.swing.text.html.parser.ParserDelegator;
49  
50  import com.levelonelabs.aim.AIMBuddy;
51  import com.levelonelabs.aimbot.AIMBot;
52  import com.levelonelabs.aimbot.BotModule;
53  
54  
55  /***
56   * Handles requests to get weather
57   *
58   * @author Scott Oster
59   *
60   * @created March 14, 2003
61   */
62  public class WeatherModule extends BotModule {
63      static Logger logger=Logger.getLogger(WeatherModule.class.getName());
64      private static ArrayList services;
65      private static final String TEMP_URL="http://mobile.wunderground.com/cgi-bin/findweather/getForecast?query=";
66      private static final String MAP_URL="http://www.weather.com/weather/map/";
67  
68      /***
69       * Initialize the service commands.
70       */
71      static {
72          services=new ArrayList();
73          services.add("weather");
74      }
75  
76      /***
77       * Constructor for StockModule.
78       *
79       * @param bot
80       */
81      public WeatherModule(AIMBot bot) {
82          super(bot);
83      }
84  
85      /***
86       * @see com.levelonelabs.aimbot.BotModule#getName()
87       */
88      public String getName() {
89          return "Weather Module";
90      }
91  
92  
93      /***
94       * @see com.levelonelabs.aimbot.BotModule#getServices()
95       */
96      public ArrayList getServices() {
97          return services;
98      }
99  
100 
101     /***
102      * @see com.levelonelabs.aimbot.BotModule#help()
103      */
104     public String help() {
105         StringBuffer sb=new StringBuffer();
106         sb.append(
107             "<B>weather <i>ZIPCODE</i></B> (displays the 5 day forcast for the specified zipcode)\n");
108         sb.append(
109             "* If the preference \"zipcode\" is set, you can omit the zipcode to use your default.");
110         return sb.toString();
111     }
112 
113 
114     /***
115      * Return 5 deay forecast
116      *
117      * @param buddy the buddy
118      * @param query the weather request
119      */
120     public void performService(AIMBuddy buddy, String query) {
121         if(query.trim().toLowerCase().startsWith("weather")) {
122             StringTokenizer st=new StringTokenizer(query, " ");
123             String zipPref=buddy.getPreference("zipcode");
124             if((zipPref == null) && (st.countTokens() < 2)) {
125                 super.sendMessage(buddy, "ERROR:\n"+help());
126             } else {
127                 String imcommand=st.nextToken();
128                 String zipcode="";
129                 if(st.hasMoreElements()) {
130                     zipcode=((String) st.nextElement()).trim();
131                 } else if(zipPref != null) {
132                     zipcode=zipPref;
133                 }
134                 String result="Couldn't get weather information";
135                 if(zipcode.length() == 5) {
136                     WeatherScrapper scrapper=new WeatherScrapper();
137                     String temp=scrapper.getWeather(zipcode);
138                     if(!temp.trim().equals("")) {
139                         //seemed to have gotten a decent result, so display it
140                         String mapURL=WeatherModule.MAP_URL+zipcode;
141                         result="Weather for zipcode <a href=\""+mapURL+"\">"+zipcode+"</a>:\n"+temp;
142 
143                         if(zipPref == null) {
144                             //if the buddy didnt have a zippref set, set this one for him
145                             buddy.setPreference("zipcode", zipcode);
146                         }
147                     }
148                 }
149                 super.sendMessage(buddy, result);
150             }
151         }
152     }
153     
154     public static void main(String[] args) {
155         WeatherModule mod= new WeatherModule(null);
156         String zipcode = args[0];
157         String result="Couldn't get weather information";
158         if(zipcode.length() == 5) {
159             WeatherScrapper scrapper=mod.new WeatherScrapper();
160             String temp=scrapper.getWeather(zipcode);
161             if(!temp.trim().equals("")) {
162                 //seemed to have gotten a decent result, so display it
163                 String mapURL=WeatherModule.MAP_URL+zipcode;
164                 result="Weather for zipcode <a href=\""+mapURL+"\">"+zipcode+"</a>:"+temp;
165             }
166         }
167         System.out.println(result);
168     }
169 
170     class WeatherScrapper extends ParserCallback {
171         private boolean grabIt=false;
172         private int count=12;
173         private StringBuffer result=new StringBuffer();
174 
175         public void handleText(char[] data, int pos) {
176             String temp=new String(data);
177             if(temp.startsWith("Forecast as of") && (count > 0)) {
178                 grabIt=true;
179             } else if((count > 0) && grabIt) {
180                 //this bolds every other line (%2 == 0 means even numbers)
181                 result.append((((count%2) == 0) ? "<b>" : "")+temp+
182                     (((count%2) == 0) ? "</b>\n" : "\n"));
183                 count--;
184             }
185         }
186 
187 
188         private String getResult() {
189             return result.toString();
190         }
191 
192 
193         public String getWeather(String zipcode) {
194             String tempResult="";
195             try {
196                 URL url=new URL(WeatherModule.TEMP_URL+zipcode);
197 
198                 //System.out.println("Scrapping URL= " + TEMP_URL);
199                 URLConnection conn=url.openConnection();
200 
201                 BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
202 
203                 ParserDelegator pd=new ParserDelegator();
204                 WeatherScrapper s=new WeatherScrapper();
205                 pd.parse(br, s, true);
206                 tempResult=s.getResult();
207             } catch(Exception e) {
208                 e.printStackTrace();
209                 return "";
210             }
211             return tempResult;
212         }       
213     }
214 }