KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > matuschek > jobo > JoBoSwing


1 package net.matuschek.jobo;
2
3 import java.awt.*;
4 import java.net.MalformedURLException JavaDoc;
5 import java.net.URL JavaDoc;
6 import java.text.DecimalFormat JavaDoc;
7 import java.util.Date JavaDoc;
8 import javax.swing.*;
9
10 import net.matuschek.http.HttpTool;
11 import net.matuschek.http.HttpToolCallback;
12 import net.matuschek.http.cookie.Cookie;
13 import net.matuschek.http.cookie.CookieException;
14 import net.matuschek.spider.WebRobotCallback;
15 import net.matuschek.swing.OptionPanel;
16 import net.matuschek.swing.VerticalAlignPanel;
17
18 import org.apache.log4j.BasicConfigurator;
19
20 /**
21  * The JoBo interface with Swing GUI.
22  *
23  * @author Daniel Matuschek
24  * @version $Revision: 1.52 $
25  */

26 public class JoBoSwing
27   extends JFrame
28   implements HttpToolCallback,
29          WebRobotCallback
30 {
31   /** JoBo version */
32   final static String JavaDoc VERSION="1.4";
33   
34 //private static Category log = Category.getInstance("");
35
private static LogFrame logFrame;
36   private static LogFrameAppender lfAppend=null;
37   private JoBoBase jobobase = null;
38   private Thread JavaDoc robotThread=null;
39   private Date JavaDoc docDownloadStarted=new Date JavaDoc();
40
41   private long httpToolDocSize = 0;
42   private int robotCount = 0;
43   private long robotSize = 0;
44   private int robotQueueSize = 0;
45   
46   // Swing variables declaration
47
private JTextField urlField;
48   private JTextField directoryField;
49   private JProgressBar progressBar;
50   private JTextField currentUrlField;
51   private JTextField queuedField;
52   private JTextField retrievedField;
53
54   private JButton runStopButton;
55   private JButton sleepButton;
56   // End of Swing variables
57

58
59   // Other frames
60

61   private RobotConfigFrame robotConfigFrame = null;
62   private URLCheckConfigFrame urlCheckConfigFrame = null;
63   private FilterConfigFrame filterConfigFrame = null;
64   private AllowedListFrame allowedURLsFrame = null;
65   // End of other frames
66

67
68   /** Creates new form JoBoSwing */
69   public JoBoSwing() {
70
71     try {
72       jobobase = JoBoBase.createFromXML();
73     } catch (ClassNotFoundException JavaDoc e) {
74       System.out.println("Could not initialize WebRobot: "+e);
75       System.exit(1);
76     }
77
78     jobobase.registerHttpToolCallback(this);
79     jobobase.registerWebRobotCallback(this);
80
81     initComponents ();
82     pack ();
83
84     updateDialogFromRobot();
85   }
86
87
88   private void initComponents() {
89     getContentPane().setLayout(new BorderLayout());
90
91     setTitle("JoBo/Swing: http://www.matuschek.net/jobo/");
92     addWindowListener(new java.awt.event.WindowAdapter JavaDoc() {
93     public void windowClosing(java.awt.event.WindowEvent JavaDoc evt) {
94       exitApp();
95     }
96       }
97               );
98     
99     /** Heading **/
100     VerticalAlignPanel headPanel = new VerticalAlignPanel();
101
102     JLabel heading1 = new JLabel();
103     heading1.setText("JoBo "+VERSION);
104     heading1.setHorizontalAlignment(JTextField.CENTER);
105     heading1.setFont(new java.awt.Font JavaDoc ("Dialog", 0, 24));
106     
107     JLabel heading2 = new JLabel();
108     heading2.setText("look at http://www.matuschek.net/jobo/");
109     heading2.setHorizontalAlignment(JTextField.CENTER);
110     heading2.setFont(new java.awt.Font JavaDoc ("Dialog", 0, 12));
111     
112     JLabel heading3 = new JLabel();
113     heading3.setText("for more details");
114     heading3.setHorizontalAlignment(JTextField.CENTER);
115     heading3.setFont(new java.awt.Font JavaDoc ("Dialog", 0, 12));
116     
117     headPanel.add(heading1);
118     headPanel.add(heading2);
119     headPanel.add(heading3);
120
121     getContentPane().add(headPanel,BorderLayout.NORTH);
122
123     
124     /* fields */
125     OptionPanel optPanel = new OptionPanel(2);
126
127     urlField = new JTextField();
128     urlField.setColumns(40);
129     urlField.setText("http://");
130     optPanel.add("URL:",urlField);
131
132     directoryField = new JTextField();
133     directoryField.setText(jobobase.getStorageDirectory());
134     directoryField.setColumns(40);
135     optPanel.add("Storage directory:",directoryField);
136       
137     currentUrlField = new JTextField();
138     currentUrlField.setEditable(false);
139     currentUrlField.setColumns(40);
140     currentUrlField.setText("-");
141     optPanel.add("Current URL:",currentUrlField);
142           
143     retrievedField = new JTextField();
144     retrievedField.setEditable(false);
145     retrievedField.setColumns(40);
146     optPanel.add("Retrieved:",retrievedField);
147       
148     queuedField = new JTextField();
149     queuedField.setEditable(false);
150     queuedField.setColumns(40);
151     optPanel.add("Queued:",queuedField);
152       
153     progressBar = new JProgressBar();
154     progressBar.setStringPainted(true);
155     optPanel.add("Progress:",progressBar,GridBagConstraints.HORIZONTAL);
156
157     getContentPane().add(optPanel);
158
159     /** Buttons **/
160     JPanel buttonPanel = new JPanel();
161     JButton butt = null;
162             
163     runStopButton = new JButton();
164     runStopButton.setText("Run");
165     runStopButton.addActionListener(new java.awt.event.ActionListener JavaDoc() {
166     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
167       runStopButtonActionPerformed();
168     }
169       }
170                     );
171     buttonPanel.add(runStopButton);
172              
173     sleepButton = new JButton();
174     sleepButton.setText("Sleep");
175     sleepButton.addActionListener(new java.awt.event.ActionListener JavaDoc() {
176     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
177       sleepButtonActionPerformed();
178     }
179       }
180                   );
181     buttonPanel.add(sleepButton);
182       
183     butt = new JButton();
184     butt.setText("Robot settings");
185     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
186     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
187       doRobotSettingsDialog();
188     }
189       }
190                   );
191     buttonPanel.add(butt);
192       
193     butt = new JButton();
194     butt.setText("Save");
195     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
196     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
197       saveSettings();
198     }
199       }
200                   );
201     // buttonPanel.add(butt);
202

203     butt = new JButton();
204     butt.setText("URLCheck");
205     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
206     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
207       configureURLCheck();
208     }
209       }
210                   );
211     // buttonPanel.add(butt);
212

213     butt = new JButton();
214     butt.setText("Filter configuration");
215     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
216     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
217       configureFilters();
218     }
219       }
220                );
221     
222     // buttonPanel.add(butt);
223

224       
225     butt = new JButton();
226     butt.setText("Allowed URLs");
227     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
228     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
229       configureAllowedURLs();
230     }
231       });
232     buttonPanel.add(butt);
233     
234
235     butt = new JButton();
236     butt.setText("Add cookie");
237     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
238     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
239       addCookie();
240     }
241       });
242     buttonPanel.add(butt);
243     
244
245     
246
247     butt = new JButton();
248     butt.setText("Log");
249     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
250     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
251       logButtonActionPerformed();
252     }
253       });
254     buttonPanel.add(butt);
255       
256         
257     butt = new JButton();
258     butt.setText("Exit");
259     butt.addActionListener(new java.awt.event.ActionListener JavaDoc() {
260     public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
261       exitApp();
262     }
263       });
264     buttonPanel.add(butt);
265         
266     getContentPane().add(buttonPanel,BorderLayout.SOUTH);
267   }
268
269   private void sleepButtonActionPerformed() {
270
271     // is there a robotThread running ?
272
if ((robotThread != null) &&
273     (robotThread.isAlive())) {
274       
275       if (jobobase.getRobot().isSleeping()) {
276     jobobase.getRobot().setSleep(false);
277     sleepButton.setText("Sleep");
278       } else {
279     jobobase.getRobot().setSleep(true);
280     sleepButton.setText("Wake up");
281       }
282     }
283   }
284
285
286   private void logButtonActionPerformed() {
287       logFrame.setVisible(true);
288   }
289
290   private void runStopButtonActionPerformed() {
291
292     // is there another robotThread running ?
293
if ((robotThread != null) &&
294     (robotThread.isAlive())) {
295       jobobase.getRobot().stopRobot();
296     } else {
297       if (updateRobotFromDialog()) {
298     runStopButton.setText("Stop");
299     // clear cookies from last run
300
//jobobase.getRobot().clearCookies();
301
robotThread = new Thread JavaDoc(jobobase.getRobot());
302     robotThread.start();
303       }
304     }
305   }
306
307   /**
308    * open the robot settings dialog
309    */

310   private void doRobotSettingsDialog() {
311     if (robotConfigFrame == null) {
312       robotConfigFrame = new RobotConfigFrame(jobobase);
313     }
314     robotConfigFrame.setVisible(true);
315   }
316
317   /**
318    * configure URLCheck
319    */

320   private void configureURLCheck() {
321     if (urlCheckConfigFrame == null) {
322       urlCheckConfigFrame = new URLCheckConfigFrame(jobobase.getURLCheck());
323     }
324     urlCheckConfigFrame.setVisible(true);
325   }
326
327   /**
328    * configure URLCheck
329    */

330   private void addCookie() {
331     String JavaDoc cookieStr = JOptionPane.showInputDialog(this, "Cookie string:");
332     String JavaDoc domain = JOptionPane.showInputDialog(this, "Domain:");
333     URL JavaDoc url;
334     try {
335         url = new URL JavaDoc("http://"+domain);
336     } catch (MalformedURLException JavaDoc e1) {
337         JOptionPane.showMessageDialog(this, "Domain invalid: "+e1.getMessage());
338         return;
339     }
340     try {
341         if (cookieStr.startsWith("Set-Cookie")) {
342             Cookie cookie;
343             cookie = new Cookie(cookieStr,url);
344             jobobase.getRobot().getCookieManager().add(cookie);
345             JOptionPane.showMessageDialog(this, "Cookie added");
346         } else {
347             Cookie[] cookies = Cookie.cookieStringToCookies(cookieStr, domain);
348             for (int i=0; i<cookies.length; i++) {
349                 System.out.println(cookies[i]);
350                 jobobase.getRobot().getCookieManager().add(cookies[i]);
351             }
352             JOptionPane.showMessageDialog(this, cookies.length+" cookies added");
353         }
354     } catch (CookieException e) {
355         JOptionPane.showMessageDialog(this, "Cookie string invalid: "+e.getMessage());
356     }
357
358   }
359
360   /**
361    * configure document filters
362    */

363   private void configureFilters() {
364     if (filterConfigFrame == null) {
365       filterConfigFrame = new FilterConfigFrame();
366     }
367     filterConfigFrame.setVisible(true);
368   }
369
370   /**
371    * configure allowed URls
372    */

373   private void configureAllowedURLs() {
374     if (allowedURLsFrame == null) {
375       allowedURLsFrame =
376     new AllowedListFrame(jobobase.getRobot().getAllowedURLs());
377     }
378     allowedURLsFrame.setVisible(true);
379   }
380
381   
382   /**
383    * store current settings
384    */

385   private void saveSettings() {
386     jobobase.saveConfig("test.xml");
387   }
388
389   
390   /**
391    * Exit the Application
392    */

393   private void exitApp() {
394     System.exit(0);
395   }
396
397
398   
399   /**
400    * @param args the command line arguments
401    */

402   public static void main (String JavaDoc[] args) {
403
404     // create a new frame for logging
405
logFrame = new LogFrame();
406     logFrame.addMsg("Starting ...");
407
408     // configure Log4J subsystem
409
lfAppend = new LogFrameAppender(logFrame);
410     BasicConfigurator.configure(lfAppend);
411
412     // other command line arguments
413
for (int i=0; i<args.length; i++) {
414       if (args[i].equals("-debug")) {
415     // send all log output to standard out (including level debug)
416
BasicConfigurator.configure();
417       }
418     }
419
420     new JoBoSwing().setVisible(true);
421   }
422
423   /**
424    * update the WebRobot setting using the values of the input fields
425    * @return true if everything is ok, false otherwise
426    */

427   private boolean updateRobotFromDialog() {
428
429     // start URL
430
String JavaDoc startUrl = urlField.getText();
431     try {
432       URL JavaDoc u = new URL JavaDoc(startUrl);
433       jobobase.getRobot().setStartURL(u);
434     } catch (MalformedURLException JavaDoc e) {
435       JOptionPane.showMessageDialog(this,"URL "+startUrl+" is invalid");
436       return false;
437     }
438
439     // storage directory
440
String JavaDoc storageDir = directoryField.getText();
441     jobobase.setStorageDirectory(storageDir);
442       
443     return true;
444   }
445
446
447   /**
448    * update the dialog field from the current setting in the webrobot
449    * will only be called on startup !
450    */

451   private void updateDialogFromRobot() {
452
453     // start URL
454
URL JavaDoc u = jobobase.getRobot().getStartURL();
455     if (u != null) {
456       urlField.setText(u.toString());
457     } else {
458       urlField.setText("");
459     }
460
461   }
462
463
464   /***********************************************************************
465    ***********************************************************************
466    
467    Callback interface for httpTool
468
469    ***********************************************************************
470    ***********************************************************************/

471
472   public void setHttpToolDocUrl(String JavaDoc url) {
473     try {
474       currentUrlField.setText(urlToString(new URL JavaDoc(url)));
475     } catch (MalformedURLException JavaDoc e) {}
476   }
477
478   public void setHttpToolDocSize(int size) {
479     this.httpToolDocSize = size;
480     progressBar.setMaximum(size);
481   }
482
483   public void setHttpToolDocCurrentSize(int size) {
484     StringBuffer JavaDoc progressStr = new StringBuffer JavaDoc();
485     progressBar.setValue(size);
486     int kB = size / 1024;
487     long longsize = size;
488
489     Date JavaDoc current = new Date JavaDoc();
490
491     long millisecs = (current.getTime()-docDownloadStarted.getTime());
492     long ratio = 0;
493     if (millisecs > 0) {
494       ratio = ((longsize*1000)/millisecs);
495     } else {
496       ratio = 0;
497     }
498
499     progressStr.append(kB);
500     progressStr.append(" kB");
501
502     // document size known ?
503
if ( this.httpToolDocSize > 0) {
504       progressStr.append(" of ");
505       progressStr.append(httpToolDocSize / 1024);
506       progressStr.append(" kB");
507     }
508
509     // ratio
510
DecimalFormat JavaDoc myFormat = new DecimalFormat JavaDoc("####0.000");
511     progressStr.append(", ");
512     progressStr.append(myFormat.format((float)(ratio)/1000));
513     progressStr.append(" kB/s");
514
515     
516     // time left
517
if (this.httpToolDocSize > 0) {
518         long secleft;
519         if (ratio > 0)
520             secleft = (this.httpToolDocSize - longsize)/ratio;
521         else
522             secleft=100000;
523         
524       long min = secleft/60;
525       int sec = (int)(secleft%60);
526       String JavaDoc secStr = Integer.toString(sec);
527       if (secStr.length()<2) {
528     secStr = "0"+secStr;
529       }
530       progressStr.append(", ");
531       progressStr.append(min);
532       progressStr.append(":");
533       progressStr.append(secStr);
534       progressStr.append(" min left");
535     }
536
537     progressBar.setString(progressStr.toString());
538   }
539
540   public void setHttpToolStatus(int status) {
541     if (status == HttpTool.STATUS_CONNECTING) {
542       progressBar.setString("Connecting");
543       this.setHttpToolDocSize(0);
544     } else if (status == HttpTool.STATUS_CONNECTED) {
545       progressBar.setString("Connected");
546       docDownloadStarted=new Date JavaDoc();
547     } else if (status == HttpTool.STATUS_RETRIEVING) {
548       progressBar.setString("Retrieving");
549     } else if (status == HttpTool.STATUS_DONE) {
550       progressBar.setString("Finished");
551     } else if (status == HttpTool.STATUS_DENIEDBYRULE) {
552       progressBar.setString("Denied by rule");
553     } else {
554       progressBar.setString("Unknown status ("+status+")");
555     }
556   }
557
558   /**
559    * converts a URL to a textual representation where the authentication
560    * info is hidden
561    * @param u
562    * @return a textual representation
563    */

564   protected String JavaDoc urlToString(URL JavaDoc u) {
565     if (u==null) {
566       return null;
567     }
568
569     String JavaDoc userInfo=u.getUserInfo();
570     if ((userInfo != null) &&
571     (! userInfo.equals(""))) {
572       userInfo="authenticated@";
573     } else {
574       userInfo="";
575     }
576
577     return u.getProtocol()+"://"+userInfo+u.getHost()+u.getPath();
578   }
579
580
581   /***********************************************************************
582    ***********************************************************************
583    
584    End of callback interface for httpTool
585
586    ***********************************************************************
587    ***********************************************************************/

588
589   public void webRobotRetrievedDoc(String JavaDoc url, int size) {
590     robotCount++;
591     robotSize += size;
592     updateControls();
593   }
594
595   public void webRobotUpdateQueueStatus(int length) {
596     robotQueueSize=length;
597     updateControls();
598   }
599
600   public void webRobotDone() {
601     progressBar.setString("Download completed");
602     robotCount=0;
603     robotSize=0;
604     runStopButton.setText("Run");
605   }
606
607   public void webRobotSleeping(boolean sleeping) {
608     if (sleeping) {
609       progressBar.setString("sleeping");
610     } else {
611       progressBar.setString("");
612     }
613   }
614
615   /***********************************************************************
616    ***********************************************************************
617    
618    End of callback interface for webRobot
619
620    ***********************************************************************
621    ***********************************************************************/

622
623
624   /**
625    * update status of dynamic elements
626    */

627   protected void updateControls() {
628     DecimalFormat JavaDoc myFormat = new DecimalFormat JavaDoc("###,###,###.0");
629     String JavaDoc retrievedContent=
630       robotCount+" files with "
631       +myFormat.format((float)robotSize/1024)
632       +" kB";
633     String JavaDoc queuedContent=robotQueueSize+"";
634     retrievedField.setText(retrievedContent);
635     queuedField.setText(queuedContent);
636   }
637
638
639
640 }
641
642
Popular Tags