KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > suberic > pooka > UserProfile


1 package net.suberic.pooka;
2 import net.suberic.util.*;
3 import java.util.*;
4 import javax.mail.*;
5 import javax.mail.internet.MimeMessage JavaDoc;
6 import javax.mail.internet.InternetAddress JavaDoc;
7 import javax.mail.internet.InternetHeaders JavaDoc;
8
9 public class UserProfile extends Object JavaDoc implements ValueChangeListener, Item {
10   Properties mailProperties;
11   String JavaDoc name;
12   //URLName sendMailURL;
13
String JavaDoc mailServerName;
14   String JavaDoc defaultDomain;
15   String JavaDoc defaultDefaultDomain;
16   OutgoingMailServer mailServer;
17   OutgoingMailServer mTempMailServer = null;
18   //String sendPrecommand;
19
String JavaDoc sentFolderName;
20   FolderInfo sentFolder;
21   public boolean autoAddSignature = true;
22   public boolean signatureFirst = true;
23   private SignatureGenerator sigGenerator;
24   private AddressBook addressBook;
25
26   private String JavaDoc smimeEncryptionKeyId;
27   private String JavaDoc pgpEncryptionKeyId;
28   private boolean signAsDefault = false;
29   private String JavaDoc cryptoDefaultType = "PGP";
30
31   private Vector excludeAddresses;
32
33   // default value
34
public static String JavaDoc S_DEFAULT_PROFILE_KEY = "__default";
35
36   public UserProfile(String JavaDoc newName, VariableBundle mainProperties) {
37     name = newName;
38
39     registerChangeListeners();
40   }
41
42   /**
43    * This populates the UserProfile from the Pooka properties list.
44    * Useful on creation as well as when any of the properties change.
45    */

46   public void initializeFromProperties(VariableBundle mainProperties, List mailPropertiesList) {
47     mailProperties = new Properties();
48     String JavaDoc profileKey;
49
50     for (int i = 0; i < mailPropertiesList.size(); i++) {
51       profileKey = (String JavaDoc)mailPropertiesList.get(i);
52       mailProperties.put(profileKey, mainProperties.getProperty("UserProfile." + name + ".mailHeaders." + profileKey, ""));
53     }
54
55     setSentFolderName(mainProperties.getProperty("UserProfile." + name + ".sentFolder", ""));
56
57     mailServerName = mainProperties.getProperty("UserProfile." + name + ".mailServer", "_default");
58     mailServer = null; // reload it next time it's requested.
59

60     //sendMailURL=new URLName(mainProperties.getProperty("UserProfile." + name + ".sendMailURL", ""));
61
//sendPrecommand=(String)mainProperties.getProperty("UserProfile." + name + ".sendPrecommand", "");
62
sigGenerator=createSignatureGenerator();
63
64     setDefaultDomain(mainProperties.getProperty("UserProfile." + name + ".defaultDomain", ""));
65
66     String JavaDoc fromAddr = (String JavaDoc)mailProperties.get("From");
67     excludeAddresses = new Vector();
68     excludeAddresses.add(fromAddr);
69     if (fromAddr.lastIndexOf('@') >0) {
70       defaultDefaultDomain = fromAddr.substring(fromAddr.lastIndexOf('@') + 1);
71     }
72     Vector excludeProp = mainProperties.getPropertyAsVector("UserProfile." + name + ".excludeAddresses", "");
73     excludeAddresses.addAll(excludeProp);
74
75     pgpEncryptionKeyId = mainProperties.getProperty("UserProfile." + name + ".pgpKey", "");
76
77     smimeEncryptionKeyId = mainProperties.getProperty("UserProfile." + name + ".smimeKey", "");
78
79     signAsDefault = (! mainProperties.getProperty("UserProfile." + name + ".sigPolicy", "").equalsIgnoreCase("manual"));
80
81     if (! signAsDefault) {
82       if ( mainProperties.getProperty("UserProfile." + name + ".sigPolicy", "").equalsIgnoreCase("smime")) {
83         cryptoDefaultType="SMIME";
84       }
85     }
86
87     String JavaDoc addressBookId = mainProperties.getProperty("UserProfile." + name + ".addressBook", "");
88     if (!addressBookId.equals("")) {
89       addressBook = Pooka.getAddressBookManager().getAddressBook(addressBookId);
90     } else
91       addressBook = null;
92   }
93
94   /**
95    * Registers this UserProfile as a ValueChangeListener for all of its
96    * source properties.
97    */

98   private void registerChangeListeners() {
99     VariableBundle resources = Pooka.getResources();
100     resources.addValueChangeListener(this, "UserProfile." + name + ".*");
101   }
102
103   /**
104    * Modifies the UserProfile if any of its source values change.
105    *
106    * As specified in net.suberic.util.ValueChangeListener.
107    */

108   public void valueChanged(String JavaDoc changedValue) {
109     VariableBundle bundle = Pooka.getResources();
110     UserProfileManager manager = Pooka.getPookaManager().getUserProfileManager();
111     initializeFromProperties(bundle, manager.getMailPropertiesList());
112   }
113
114   /**
115    * Populates the given message with the headers for this UserProfile.
116    */

117   public void populateMessage(MimeMessage JavaDoc mMsg) throws MessagingException {
118     // I hate this. I hate having to grab half of these headers on my
119
// own.
120

121     Enumeration keys = mailProperties.propertyNames();
122     String JavaDoc fromAddr = null, fromPersonal = null, replyAddr = null, replyPersonal = null;
123
124     while (keys.hasMoreElements()) {
125       String JavaDoc key = (String JavaDoc)(keys.nextElement());
126
127       if (key.equals("FromPersonal")) {
128         fromPersonal = mailProperties.getProperty(key);
129       } else if (key.equals("From")) {
130         fromAddr = mailProperties.getProperty(key);
131       } else if (key.equals("ReplyTo")) {
132         replyAddr = mailProperties.getProperty(key);
133       } else if (key.equals("ReplyToPersonal")) {
134         replyPersonal = mailProperties.getProperty(key);
135       } else {
136         mMsg.setHeader(key, mailProperties.getProperty(key));
137       }
138
139       try {
140         if (fromAddr != null)
141           if (fromPersonal != null && !(fromPersonal.equals("")))
142             mMsg.setFrom(new InternetAddress JavaDoc(fromAddr, fromPersonal));
143           else
144             mMsg.setFrom(new InternetAddress JavaDoc(fromAddr));
145
146         if (replyAddr != null && !(replyAddr.equals("")))
147           if (replyPersonal != null)
148             mMsg.setReplyTo(new InternetAddress JavaDoc[] {new InternetAddress JavaDoc(replyAddr, replyPersonal)});
149           else
150             mMsg.setReplyTo(new InternetAddress JavaDoc[] {new InternetAddress JavaDoc(replyAddr)});
151
152       } catch (java.io.UnsupportedEncodingException JavaDoc uee) {
153         throw new MessagingException("", uee);
154       }
155     }
156   }
157
158   /**
159    * Populates the given InternetHeaders object with the headers for this
160    * UserProfile.
161    */

162   public void populateHeaders(InternetHeaders JavaDoc pHeaders) throws MessagingException {
163     // I hate this. I hate having to grab half of these headers on my
164
// own.
165

166     Enumeration keys = mailProperties.propertyNames();
167     String JavaDoc fromAddr = null, fromPersonal = null, replyAddr = null, replyPersonal = null;
168
169     while (keys.hasMoreElements()) {
170       String JavaDoc key = (String JavaDoc)(keys.nextElement());
171
172       if (key.equals("FromPersonal")) {
173         fromPersonal = mailProperties.getProperty(key);
174       } else if (key.equals("From")) {
175         fromAddr = mailProperties.getProperty(key);
176       } else if (key.equals("ReplyTo")) {
177         replyAddr = mailProperties.getProperty(key);
178       } else if (key.equals("ReplyToPersonal")) {
179         replyPersonal = mailProperties.getProperty(key);
180       } else {
181         pHeaders.setHeader(key, mailProperties.getProperty(key));
182       }
183
184       try {
185         if (fromAddr != null)
186           if (fromPersonal != null && !(fromPersonal.equals("")))
187             pHeaders.setHeader("From", new InternetAddress JavaDoc(fromAddr, fromPersonal).toString());
188           else
189             pHeaders.setHeader("From", new InternetAddress JavaDoc(fromAddr).toString());
190
191         if (replyAddr != null && !(replyAddr.equals("")))
192           if (replyPersonal != null)
193             pHeaders.setHeader("Reply-To", new InternetAddress JavaDoc(replyAddr, replyPersonal).toString());
194           else
195             pHeaders.setHeader("Reply-To", new InternetAddress JavaDoc(replyAddr).toString());
196
197       } catch (java.io.UnsupportedEncodingException JavaDoc uee) {
198         throw new MessagingException("", uee);
199       }
200     }
201   }
202
203   /**
204    * This removes the email addresses that define this user from the
205    * given message's to fields.
206    */

207   public void removeFromAddress(Message JavaDoc m) {
208     try {
209       Address JavaDoc[] toRecs = m.getRecipients(Message.RecipientType.TO);
210       Address JavaDoc[] ccRecs = m.getRecipients(Message.RecipientType.CC);
211       Address JavaDoc[] bccRecs = m.getRecipients(Message.RecipientType.BCC);
212       toRecs = filterAddressArray(toRecs);
213       ccRecs = filterAddressArray(ccRecs);
214       bccRecs = filterAddressArray(bccRecs);
215
216       m.setRecipients(Message.RecipientType.TO, toRecs);
217       m.setRecipients(Message.RecipientType.CC, ccRecs);
218       m.setRecipients(Message.RecipientType.BCC, bccRecs);
219     } catch (MessagingException me) {
220     }
221   }
222
223   /**
224    * Filters out this address from the given array of addresses.
225    */

226   private Address JavaDoc[] filterAddressArray(Address JavaDoc[] addresses) {
227     if (addresses != null && addresses.length > 0) {
228       Vector returnVector = new Vector();
229       for (int i = 0; i < addresses.length; i++) {
230         String JavaDoc currentAddress = ((InternetAddress JavaDoc) addresses[i]).getAddress();
231         boolean found = false;
232         for (int j = 0; j < excludeAddresses.size() && found == false ; j++) {
233           String JavaDoc excludeAddr = (String JavaDoc)excludeAddresses.elementAt(j);
234           if (currentAddress.equalsIgnoreCase(excludeAddr))
235             found = true;
236         }
237         if (!found)
238           returnVector.add(addresses[i]);
239       }
240
241       Object JavaDoc[] retArr = returnVector.toArray();
242       Address JavaDoc[] returnValue = new Address JavaDoc[retArr.length];
243       for (int i = 0; i < retArr.length; i++)
244         returnValue[i] = (Address JavaDoc) retArr[i];
245
246       return returnValue;
247     } else
248       return addresses;
249   }
250
251   public String JavaDoc getName() {
252     return name;
253   }
254
255   public String JavaDoc getUserProperty() {
256     return "UserProfile." + getName();
257   }
258
259   public String JavaDoc getItemID() {
260     return getName();
261   }
262
263   public String JavaDoc getItemProperty() {
264     return getUserProperty();
265   }
266
267   public Properties getMailProperties() {
268     return mailProperties;
269   }
270
271   public String JavaDoc toString() {
272     return name;
273   }
274
275   /*
276     public URLName getSendMailURL() {
277     return sendMailURL;
278     }
279
280     public String getSendPrecommand() {
281     return sendPrecommand;
282     }
283   */

284
285   public FolderInfo getSentFolder() {
286     if (sentFolder == null)
287       loadSentFolder();
288
289     return sentFolder;
290   }
291
292   public void setSentFolderName(String JavaDoc newValue) {
293     sentFolderName = newValue;
294
295     loadSentFolder();
296   }
297
298   public OutgoingMailServer getMailServer() {
299     if (mailServer == null)
300       loadMailServer();
301
302     return mailServer;
303   }
304
305   public void setMailServerName(String JavaDoc newValue) {
306     mailServerName = newValue;
307
308     loadMailServer();
309   }
310
311   /**
312    * Sets a mail server for this session.
313    */

314   public void setTemporaryMailServer(OutgoingMailServer pTempServer) {
315     mTempMailServer = pTempServer;
316
317     loadMailServer();
318   }
319
320   /**
321    * Returns the default domain. This will be appended to any email
322    * address which doesn't include a domain.
323    */

324   public String JavaDoc getDefaultDomain() {
325     if (defaultDomain == null || defaultDomain.equals(""))
326       return defaultDefaultDomain;
327     else
328       return defaultDomain;
329   }
330
331   /**
332    * Sets the default domain. This is what will be added to email
333    * addresses that don't include a domain.
334    */

335   public void setDefaultDomain(String JavaDoc newDomain) {
336     defaultDomain = newDomain;
337   }
338
339   /**
340    * Loads the sent folder from the UserProfile.username.sentFolder
341    * property.
342    */

343   public void loadSentFolder() {
344     StoreManager sm = Pooka.getStoreManager();
345     if (sm != null) {
346       sentFolder = Pooka.getStoreManager().getFolder(sentFolderName);
347
348       if (sentFolder != null) {
349         sentFolder.setSentFolder(true);
350       }
351     }
352   }
353
354   /**
355    * Loads the MailServer from the UserProfile.username.mailServer
356    * property.
357    */

358   public void loadMailServer() {
359     if (mTempMailServer != null) {
360       mailServer = mTempMailServer;
361
362       return;
363     }
364
365     mailServer = Pooka.getOutgoingMailManager().getOutgoingMailServer(mailServerName);
366     if (mailServer == null) {
367       mailServer = Pooka.getOutgoingMailManager().getDefaultOutgoingMailServer();
368     }
369   }
370
371
372   /**
373    * Creates the signatureGenerator for this Profile.
374    */

375   public SignatureGenerator createSignatureGenerator() {
376     try {
377       String JavaDoc classname = Pooka.getProperty("UserProfile." + name + ".sigClass", Pooka.getProperty("Pooka.defaultSigGenerator", "net.suberic.pooka.FileSignatureGenerator"));
378       Class JavaDoc sigClass = Class.forName(classname);
379       SignatureGenerator sigGen = (SignatureGenerator) sigClass.newInstance();
380       sigGen.setProfile(this);
381       return sigGen;
382     } catch (Exception JavaDoc e) {
383       SignatureGenerator sigGen = new StringSignatureGenerator();
384       sigGen.setProfile(this);
385       return sigGen;
386     }
387   }
388
389   /**
390    * This returns a signature appropriate for the given text.
391    */

392   public String JavaDoc getSignature(String JavaDoc text) {
393     if (sigGenerator != null)
394       return sigGenerator.generateSignature(text);
395     else
396       return null;
397   }
398
399   /**
400    * Returns the default signature for this UserProfile. Use
401    * getSignature(String text) instead.
402    */

403   public String JavaDoc getSignature() {
404     if (sigGenerator != null)
405       return sigGenerator.generateSignature(null);
406     else
407       return null;
408     //return (Pooka.getProperty("UserProfile." + name + ".signature", null));
409
}
410
411   public void setSignature(String JavaDoc newValue) {
412     Pooka.setProperty("UserProfile." + name + ".signature", newValue);
413   }
414
415   /**
416    * Returns the default encryption key for this profile, if any.
417    */

418   public java.security.Key JavaDoc getEncryptionKey() {
419     return getEncryptionKey(cryptoDefaultType);
420   }
421
422   /**
423    * Returns the default encryption key for this profile, if any.
424    */

425   public java.security.Key JavaDoc getEncryptionKey(String JavaDoc type) {
426     String JavaDoc keyAlias = pgpEncryptionKeyId;
427     if (type.equalsIgnoreCase(net.suberic.crypto.EncryptionManager.SMIME)) {
428       keyAlias = smimeEncryptionKeyId;
429     }
430
431     if (keyAlias != null && keyAlias.length() > 0) {
432       try {
433         if (Pooka.getCryptoManager().privateKeyAliases(type).contains(keyAlias)) {
434           try {
435             java.security.Key JavaDoc returnValue = Pooka.getCryptoManager().getPrivateKey(keyAlias);
436
437             return returnValue;
438           } catch (java.security.UnrecoverableKeyException JavaDoc uke) {
439             // we just haven't accessed the key yet. skip.
440
}
441         }
442       } catch (Exception JavaDoc ee) {
443         ee.printStackTrace();
444       }
445       // FIXME
446
return null;
447     }
448
449     return null;
450   }
451
452   /**
453    * Returns whether or not we want to sign messages as default for this
454    * UserProfile.
455    */

456   public boolean getSignAsDefault() {
457     return signAsDefault;
458   }
459
460   /**
461    * Returns the default AddressMatcher for this UserProfile.
462    */

463   public AddressMatcher getAddressMatcher() {
464     if (addressBook != null)
465       return addressBook.getAddressMatcher();
466     else {
467       AddressBook defaultBook = Pooka.getAddressBookManager().getDefault();
468       if (defaultBook != null)
469         return defaultBook.getAddressMatcher();
470       else
471         return null;
472     }
473   }
474
475   public AddressBook getAddressBook() {
476     return addressBook;
477   }
478 }
479
Popular Tags