KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SnowMailClient > MailEngine > transfer > MailTransferDialog


1 package SnowMailClient.MailEngine.transfer;
2
3 import SnowMailClient.MailEngine.*;
4 import SnowMailClient.SnowMailClientApp;
5 import SnowMailClient.model.*;
6 import SnowMailClient.model.accounts.*;
7 import SnowMailClient.model.folders.*;
8 import SnowMailClient.view.*;
9 import SnowMailClient.view.MessagesPreview.*;
10 import SnowMailClient.view.accounts.AccountsEditor;
11 import SnowMailClient.utils.NumberedLineReader;
12 import snow.utils.gui.*;
13 import snow.utils.ArrayUtils;
14
15 import snow.concurrent.*;
16 import snow.sortabletable.*;
17
18 import SnowMailClient.utils.*;
19 import SnowMailClient.view.dialogs.*;
20 import SnowMailClient.Language.Language;
21 import snow.lookandfeel.*;
22
23 import java.awt.*;
24 import java.awt.event.*;
25 import javax.swing.*;
26 import javax.swing.border.*;
27 import javax.swing.event.*;
28 import java.util.Vector JavaDoc;
29 import java.io.*;
30 import java.text.*;
31
32 /** Used to send mails
33 */

34 public class MailTransferDialog extends JDialog
35 {
36   final private CloseControlPanel ccp = new CloseControlPanel(this, true, true, Language.translate("?"));
37   final private MailTransferModel mailDownloadModel;
38   final private SortableTableModel stm;
39   final private JTable table;
40
41   public boolean downloadTerminated = false;
42
43   private final JTextArea errorTA = new JTextArea(3, 40);
44   private MailFolder sentFolder, outboxFolder;
45
46   private final AccountLog transferLog = new AccountLog();
47
48   public MailTransferDialog(JFrame parent, MailTransferModel.TransferType type)
49   {
50      super( parent, Language.translate("Mail transfer"), true);
51      this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
52
53      FolderTreeNode sent = SnowMailClientApp.getInstance().getFoldersModel().getSentFolder();
54      FolderTreeNode outbox = SnowMailClientApp.getInstance().getFoldersModel().getOutboxFolder();
55
56      try
57      {
58         sentFolder = sent.getMailFolder();
59         outboxFolder = outbox.getMailFolder();
60      }
61      catch(Exception JavaDoc ex)
62      {
63         ex.printStackTrace();
64      }
65
66      this.mailDownloadModel = new MailTransferModel(SnowMailClientApp.getInstance().getAccounts(), type);
67      this.stm = new SortableTableModel(mailDownloadModel);
68      this.table = new JTable(stm);
69
70      ToolTipManager.sharedInstance().registerComponent(table);
71
72      if(mailDownloadModel.getTransferItems().size()==0)
73      {
74        JOptionPane.showMessageDialog(SnowMailClientApp.getInstance(),
75           Language.translate("There are no accounts to read mail from.\nActivate the checkbox read in the accounts editor."),
76             Language.translate("No accounts to check"),
77           JOptionPane.INFORMATION_MESSAGE);
78        downloadTerminated = true;
79        return;
80      }
81
82      stm.installGUI(table);
83      mailDownloadModel.setTableRenderer(table);
84
85      JTabbedPane tabbedPane = new JTabbedPane();
86      JPanel centerPanel = new JPanel(new BorderLayout());
87      tabbedPane.add(Language.translate("Transfer"), centerPanel);
88      getContentPane().add(tabbedPane, BorderLayout.CENTER);
89      centerPanel.add(new JScrollPane(table), BorderLayout.CENTER);
90      centerPanel.add(errorTA, BorderLayout.SOUTH);
91
92      errorTA.setEditable(false);
93      errorTA.setBorder(new EmptyBorder(3,3,3,3));
94      errorTA.setForeground(Color.red);
95
96      JTextPane logPane = new JTextPane(transferLog.doc);
97      logPane.setEditable(false);
98      tabbedPane.add(Language.translate("Log"), new JScrollPane(logPane) );
99
100      ccp.getOkButton().setVisible(false);
101      getContentPane().add(ccp, BorderLayout.SOUTH);
102
103      table.getSelectionModel().addListSelectionListener(new ListSelectionListener()
104      {
105         public void valueChanged(ListSelectionEvent lse)
106         {
107            int selrview = table.getSelectedRow();
108            errorTA.setText("");
109            errorTA.setVisible(false);
110            if( selrview==-1)
111            {
112               return;
113            }
114            int pos = stm.getIndexInUnsortedFromTablePos(selrview);
115            if(pos==-1) return;
116            TransferItem dac = mailDownloadModel.getTransferItems().elementAt(pos);
117            if(dac.error!=null)
118            {
119               errorTA.setText(""+dac.error.getMessage());
120               errorTA.setVisible(true);
121               //Debug: dac.error.printStackTrace();
122
}
123
124            table.setToolTipText(dac.status.toString());
125         }
126      });
127
128      this.addWindowListener(new WindowAdapter()
129      {
130        @Override JavaDoc public void windowClosing(WindowEvent we)
131        {
132          onClose();
133        }
134        @Override JavaDoc public void windowClosed(WindowEvent we)
135        {
136          onClose();
137        }
138      });
139
140      Thread JavaDoc t = new Thread JavaDoc()
141      {
142        public void run()
143        {
144          mailDownloadModel.updateView();
145
146          // this waits until termination
147
errorTA.setVisible(false);
148          startAllTransfers();
149          mailDownloadModel.updateView();
150
151          downloadTerminated = true;
152
153          // look if errors occured
154
if(hasErrors())
155          {
156            // let the user close after looking at the errors
157
}
158          else
159          {
160            setVisible(false);
161          }
162        }
163      };
164      t.setPriority(Thread.MIN_PRIORITY);
165      t.start();
166
167      int fs = UIManager.getFont("Label.font").getSize();
168      SnowMailClientApp.getInstance().getProperties().setComponentSizeFromINIFile(this, "MailDownloadDialog",
169           fs*45, fs*28, 10, 10);
170
171      //pack();
172
setLocationRelativeTo(parent);
173      setVisible(true); // Modal, but not always
174

175
176   } // Constructor
177

178   private boolean hasErrors()
179   {
180      for(TransferItem tri : mailDownloadModel.getTransferItems())
181      {
182         if(tri.error != null) return true;
183      }
184      return false;
185   }
186
187   /** parallel download AND wait until all terminated
188   */

189   private void startAllTransfers()
190   {
191     Vector JavaDoc<TransferItem> dacs = mailDownloadModel.getTransferItems();
192     Vector JavaDoc<Thread JavaDoc> threads = new Vector JavaDoc<Thread JavaDoc>();
193     for(TransferItem _dac : dacs)
194     {
195        final TransferItem dac = _dac;
196        if(dac.transferType==TransferItem.TransferType.Receive)
197        {
198          Thread JavaDoc t = new Thread JavaDoc() { public void run() {
199            downloadAllMails(dac);
200          }};
201          t.setPriority(Thread.NORM_PRIORITY-1);
202          threads.add(t);
203          t.start();
204        }
205        else if(dac.transferType==TransferItem.TransferType.Send)
206        {
207          Thread JavaDoc t = new Thread JavaDoc() { public void run() {
208            sendAllMails(dac);
209          }};
210          t.setPriority(Thread.NORM_PRIORITY-1);
211          threads.add(t);
212          t.start();
213        }
214
215     }
216
217     // wait for all
218
for(Thread JavaDoc t: threads)
219     {
220        try{ t.join(); } catch(Exception JavaDoc e) {}
221     }
222   }
223
224   /** send all the mails with the given account (one after each other)
225   */

226   private void sendAllMails(final TransferItem dac)
227   {
228
229         //
230
transferLog.append("\r\n"+Language.translate("Sending % mails", ""+dac.messagesToSend.size()));
231         dac.numberOfMailsToDownload = dac.messagesToSend.size();
232         dac.totalDownloadedBytes = 0;
233         dac.totalBytesToDownload = 0;
234         dac.numberOfDownladedMails = 0;
235
236         //MailMessage mess;
237
for(MailMessage mess : dac.messagesToSend)
238         {
239           // ### only approximatively the size to send
240
dac.totalBytesToDownload += mess.getSize();
241         }
242
243         for(MailMessage mess : dac.messagesToSend)
244         {
245           dac.numberOfDownladedMails++;
246
247           Counter counter = new Counter()
248           {
249              public void increment(int count)
250              {
251                 super.increment(count);
252                 dac.totalDownloadedBytes += count;
253                 mailDownloadModel.updateView();
254              }
255           };
256
257           try
258           {
259              if(mess.getToAddresses().size()==0)
260              {
261                 throw new Exception JavaDoc(Language.translate("The mail message has no destinee"));
262              }
263              transferLog.append("\r\n" + Language.translate("Sending message to %", ""+mess.getToAddresses()));
264              dac.status.setLength(0);
265              dac.status.append(Language.translate("Sending message to %", ""+mess.getToAddresses()));
266              TransferFunctions.sendMail(mess, dac.interrupter, counter);
267           }
268           catch(Exception JavaDoc e)
269           {
270              dac.error = e;
271              transferLog.appendError("\r\n"+Language.translate("Error")+": "+e.getMessage());
272           }
273         }
274
275         // all sent
276
//dac.totalDownloadedBytes = dac.totalBytesToDownload;
277

278   }
279
280   /** receive all the mails
281   */

282   private void downloadAllMails(final TransferItem dac)
283   {
284      try
285      {
286        SecurePopConnection sp = dac.ma.getCheckedPopConnection(); // must be retrieved and cached, the get looks if alive, sending NOOPs
287

288        dac.numberOfMailsToDownload = sp.getNumberOfMessages()[0];
289        dac.numberOfDownladedMails = 0;
290
291        dac.totalBytesToDownload = sp.getNumberOfMessages()[1];
292        dac.totalDownloadedBytes = 0;
293
294        mailDownloadModel.updateView();
295
296        String JavaDoc[] uidls = sp.getMessagesUIDLs();
297        int[] messSizes = sp.getSizes_from_MessagesLIST(sp.getMessagesLIST_());
298
299     /* if(uidls.length != messSizes.length) // Fixed dec 2005
300        {
301          System.out.println( "UIDLS: "+ArrayUtils.toString(uidls) );
302          System.out.println( "sizes: "+ArrayUtils.toString(messSizes) );
303          throw new Exception("Internal error: bad UIDLs");
304        } */

305
306     ml:for(int i=0; i<messSizes.length; i++)
307        {
308           // get header...
309
Header header = new Header();
310           try
311           {
312             String JavaDoc str = sp.getMessageTop(uidls[i], 0);
313             Header.parseHeader(new NumberedLineReader(str), header);
314           }
315           catch(Exception JavaDoc ignored)
316           {
317             // not so important...
318
}
319
320           String JavaDoc from = header.getEntryValue("from", "?");
321           String JavaDoc to = header.getEntryValue("to", "?");
322           String JavaDoc subject = header.getEntryValue("subject", "?");
323
324           dac.status.setLength(0);
325           dac.status.append(Language.translate("Receiving mail from %", from));
326
327           // ask for large messages
328
if(messSizes[i] > 100000) // 100k
329
{
330              int rep = JOptionPane.showConfirmDialog(SnowMailClientApp.getInstance(),
331                 Language.translate("The message")
332                 +"\n"+Language.translate(" from: %",from)
333                 +"\n"+Language.translate(" to: %",to)
334                 +"\n"+Language.translate(" subject: %",subject)
335                 +"\n"+Language.translate("has a size of %.\nDo you want to download it ?", MailMessageUtils.formatSize(messSizes[i])),
336                 Language.translate("Big message warning"),
337                 JOptionPane.YES_NO_OPTION);
338
339              if(!(rep==JOptionPane.OK_OPTION))
340              {
341                dac.totalBytesToDownload -= messSizes[i];
342                dac.numberOfMailsToDownload--;
343                continue ml; // go to the next message
344
}
345           }
346
347           Counter counter = new Counter()
348           {
349              public void increment(int count)
350              {
351                super.increment(count);
352                dac.totalDownloadedBytes += count;
353                mailDownloadModel.updateView();
354              }
355           };
356           dac.numberOfDownladedMails++;
357           String JavaDoc messContent = sp.getMessage(uidls[i], dac.interrupter, counter);
358           mailDownloadModel.updateView();
359
360           final MailMessage mess = new MailMessage();
361           mess.parse(messContent);
362
363           transferLog.append("\r\nReceived: "+mess.getFromAddress()+" to "+mess.getToAddresses());
364
365           addReceivedMessage(mess);
366           // read and add was successful => delete from server
367
if(true)
368           {
369              sp.deleteMessage(uidls[i]);
370           }
371        }
372
373        // terminated
374
dac.totalDownloadedBytes = dac.totalBytesToDownload;
375      }
376      catch(Exception JavaDoc e)
377      {
378        dac.error = e;
379        transferLog.appendError("\r\n"+Language.translate("Error")+": "+e.getMessage());
380      }
381   }
382
383   /** also calculate the spam prob and increment the stats of senders
384   */

385   private void addReceivedMessage(final MailMessage mess) throws Exception JavaDoc
386   {
387      try
388      {
389        double p = SnowMailClientApp.getInstance().getWordStatistic().calculateSpamProbability(mess).getProbability();
390        mess.setSPAMProbability(p);
391      }
392      catch(Exception JavaDoc es)
393      {
394        es.printStackTrace();
395      }
396
397      mess.setHasBeenReceived(true);
398      mess.setEditable(false);
399
400      final MailFolder mf = SnowMailClientApp.getInstance().getFoldersModel().getInboxFolder().getMailFolder();
401      EventQueue.invokeLater(new Runnable JavaDoc()
402      {
403        public void run()
404        {
405          mf.addMessage(mess);
406        }
407      });
408
409      // increment the number of mails received from IF the address is in the book
410
SnowMailClientApp.getInstance().getAddressBook().incrementMailsReceivedFromIfPresent( mess.getFromAddress() );
411      SnowMailClientApp.getInstance().getSpamBook().incrementMailsReceivedFromIfPresent( mess.getFromAddress() );
412
413   }
414
415   /** called when the dialog closes. either on normal close or when cancell was pressed
416   */

417   private void onClose()
418   {
419      SnowMailClientApp.getInstance().getProperties().saveComponentSizeInINIFile(this, "MailDownloadDialog");
420      ToolTipManager.sharedInstance().unregisterComponent(table);
421      downloadTerminated = true;
422
423      if(ccp.getWasCancelled())
424      {
425         // stop all process !!
426
for(TransferItem dac : this.mailDownloadModel.getTransferItems())
427         {
428            Process JavaDoc p = dac.interrupter.process;
429            if(p != null)
430            {
431               try{ p.destroy(); } catch(Exception JavaDoc e) {}
432            }
433            dac.interrupter.stopEvaluation();
434         }
435      }
436   }
437
438 }
Popular Tags