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  import java.net.URLEncoder;
43  
44  import java.util.ArrayList;
45  import java.util.StringTokenizer;
46  import java.util.Vector;
47  import java.util.logging.Logger;
48  
49  import com.levelonelabs.aim.AIMBuddy;
50  import com.levelonelabs.aimbot.AIMBot;
51  import com.levelonelabs.aimbot.BotModule;
52  
53  
54  /***
55   * Creates Babel poetry from user input
56   *
57   * @author Scott Oster
58   *
59   * @created February 3, 2002
60   */
61  public class BabelModule extends BotModule {
62      /*** Maximum number of trails to run */
63      public static final int MAX_TRIALS=8;
64      private static ArrayList services;
65      private static Vector langs;
66      private static Logger logger=Logger.getLogger(BabelModule.class.getName());
67  
68      /***
69       * Initialize the service commands.
70       */
71      static {
72          //init the services
73          services=new ArrayList();
74          services.add("babel");
75  
76          //init the langs
77          langs=new Vector();
78          langs.add("de");
79          langs.add("it");
80          langs.add("pt");
81          langs.add("fr");
82          langs.add("es");
83      }
84  
85      /***
86       * Constructor for the BabelModule object
87       *
88       * @param bot
89       */
90      public BabelModule(AIMBot bot) {
91          super(bot);
92      }
93  
94      /***
95       * Talk to babel fish
96       *
97       * @param passage
98       * @param translation
99       *
100      * @return the resulting translation
101      */
102     private static String runQuery(String passage, String translation) {
103         try {
104             String marker="XXXXX";
105 
106             //build the query
107             String base="http://world.altavista.com/babelfish/tr";
108             String query=base+"?"+"doit=done"+"&intl=1"+"&tt=urltext"+"&urltext="+
109                 URLEncoder.encode(marker+" "+passage, "ISO-8859-1")+"&lp="+translation;
110             URL url=new URL(query);
111 
112             //setup the connection (do POST)
113             URLConnection connection=url.openConnection();
114             connection.setDoOutput(true);
115             connection.connect();
116 
117             //read the results page
118             BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
119             String line;
120             StringBuffer sb=new StringBuffer();
121             while((line=br.readLine()) != null) {
122                 sb.append(line+"\n");
123             }
124             br.close();
125 
126             logger.finest("THE HTML IS:\n"+sb);
127             //extract the results
128             String result=sb.toString();
129             if(result.indexOf("BabelFish Error") > -1) {
130                 //use a custom exception here instead
131                 logger.severe("#####ERROR#####:BabelFish puked\n");
132                 logger.fine(result);
133                 return "ERROR";
134             }
135 
136             int index=result.indexOf(marker);
137             int error=0;
138             if(index >= 0) {
139                 result=result.substring(index+marker.length());
140                 int end=result.indexOf("</");
141                 if(end >= 0) {
142                     result=result.substring(0, end);
143                 } else {
144                     error=1;
145                 }
146             } else {
147                 error=2;
148             }
149 
150             if(error != 0) {
151                 logger.severe("There was a parsing error("+error+")!");
152                 logger.fine("HERE IS THE HTML:\n"+sb);
153                 return null;
154             } else {
155                 return result.trim();
156             }
157         } catch(Exception e) {
158             logger.severe("Got an error:"+e);
159             e.printStackTrace();
160             return null;
161         }
162     }
163 
164 
165     /***
166      * Runs a sentance thru another language and resturns the convolution
167      *
168      * @param passage
169      * @param lang
170      *
171      * @return convoluted english
172      */
173     private static String convolute(String passage, String lang) {
174         String result=passage;
175         result=runQuery(result, "en_"+lang);
176 
177         logger.finest("In "+lang+": "+result);
178         result=runQuery(result, lang+"_en");
179         logger.finest("[English]:"+result);
180         return result;
181     }
182 
183 
184     /***
185      * Turn text into poetry
186      *
187      * @param input text
188      * @param numtrials
189      *
190      * @return babel poetry
191      */
192     private static String makePoetry(String input, int numtrials) {
193         String result=input.trim();
194         logger.fine("Running "+numtrials+" trials.");
195 
196         for(int i=0, actual_count=0; (i < numtrials) && (actual_count <= MAX_TRIALS);
197                 i++, actual_count++) {
198             int ind=(int) (Math.random()*langs.size());
199             String old=result;
200             result=convolute(result, (String) langs.get(ind));
201             if(old.equals(result)) {
202                 i--;
203             }
204 
205             if(result.equals("ERROR") || result.trim().equals("")) {
206                 return old;
207             }
208         }
209 
210         return result;
211     }
212 
213 
214     /***
215      * Gets the services attribute of the BabelModule object
216      *
217      * @return The services value
218      */
219     public ArrayList getServices() {
220         return services;
221     }
222 
223 
224     /***
225      * Gets the name attribute of the BabelModule object
226      *
227      * @return The name value
228      */
229     public String getName() {
230         return "Babel Poetry Module";
231     }
232 
233 
234     /***
235      * Describes the usage of the module
236      *
237      * @return the usage of the module
238      */
239     public String help() {
240         StringBuffer sb=new StringBuffer();
241         sb.append(
242             "<B>babel [-n <i>DISTORTION</i>] <i>TEXT</i></B> (creates poetry from <TEXT>, this may take several seconds)\n");
243         sb.append("NOTE: Using -n optionally specifies amount to distort meaning (MAX:"+MAX_TRIALS+
244             ")");
245         sb.append("\n\n<b>EXAMPLE: babel Today is a great day to talk to a robot.</b>");
246         return sb.toString();
247     }
248 
249 
250     /***
251      * Create poetry
252      *
253      * @param buddy
254      * @param query
255      */
256     public void performService(AIMBuddy buddy, String query) {
257         if(query.trim().toLowerCase().startsWith("babel")) {
258             StringTokenizer st=new StringTokenizer(query, " ");
259 
260             //check for enough args
261             if(st.countTokens() < 2) {
262                 super.sendMessage(buddy, "ERROR:\n"+help());
263                 return;
264             }
265 
266             String imcommand=st.nextToken();
267 
268             //check for distortion modifier
269             int distortion=5+(int) (Math.random()*5);
270             String temp="";
271             if(st.hasMoreTokens()) {
272                 temp=st.nextToken();
273                 //look for -n
274                 if(temp.toLowerCase().equals("-n")) {
275                     //if we got -n we need an int next
276                     if(st.hasMoreTokens()) {
277                         temp=st.nextToken();
278                         //set the distortion level (within max) or error out
279                         try {
280                             distortion=Integer.parseInt(temp);
281                             if(distortion > MAX_TRIALS) {
282                                 distortion=MAX_TRIALS;
283                             }
284 
285                             temp="";
286                         } catch(NumberFormatException nfe) {
287                             super.sendMessage(buddy, "ERROR:\n"+help());
288                             return;
289                         }
290                     } else {
291                         super.sendMessage(buddy, "ERROR:\n"+help());
292                         return;
293                     }
294                 }
295             }
296 
297             //grab the rest of the message and make poetry with it
298             String imcommandText=temp;
299             while(st.hasMoreTokens()) {
300                 imcommandText=imcommandText+" "+st.nextToken();
301             }
302 
303             //only send a message if there is somethign there.
304             if(!imcommandText.equals("")) {
305                 String result=makePoetry(imcommandText, distortion);
306                 super.sendMessage(buddy, result);
307                 return;
308             }
309         }
310     }
311 }