Address.toString() now offers long and short forms
[org.ibex.mail.git] / src / org / ibex / mail / Address.java
1 package org.ibex.mail;
2 import org.ibex.crypto.*;
3 import org.ibex.js.*;
4 import org.ibex.util.*;
5 import org.ibex.mail.protocol.*;
6 import java.util.*;
7 import java.net.*;
8 import java.io.*;
9
10 // FIXME this should be more forgiving
11 public class Address extends JSReflection {
12     public final String user;
13     public final String host;
14     public final String description;
15     public static Address parse(String s) { try { return s==null?null:new Address(s); } catch (Malformed _) { return null; } }
16     public Address(String user, String host, String description) {this.user=user;this.host=host;this.description=description;}
17     public Address(String s0) throws Address.Malformed {
18         String s = s0.trim();
19         if (s.indexOf('<') == -1) description = "";
20         else {
21             if (s.indexOf('>') == -1) { throw new Malformed("found open-angle-bracket (<) but not close-angle-bracket (>)"); }
22             description = s.substring(0, s.indexOf('<')) + s.substring(s.indexOf('>') + 1);
23             s = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
24         }
25         if (s.indexOf('@') == -1) { throw new Malformed("no @-sign in email address \""+s0+"\""); }
26         user = s.substring(0, s.indexOf('@'));
27         host = s.substring(s.indexOf('@')+1);
28     }
29     public String toString() { return user + "@" + host; }
30     public String toString(boolean desc) {
31         return desc && description != null && description.length() > 0 ? (description+" <" + toString() + ">") : toString(); }
32     public String coerceToString() { return toString(); }
33     public static class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
34
35     public boolean isLocal() {
36         InetAddress[] mx = SMTP.getMailExchangerIPs(host);
37         for(int i=0; i<mx.length; i++) {
38             try { if (NetworkInterface.getByInetAddress(mx[i]) != null) { return true; } }
39             catch (Exception e) { /* DELIBERATE */ }
40         }
41         Log.warn(this, "returning false");
42         return false;
43     }
44
45     public static Address[] list(String spec) {
46         if (spec == null) return new Address[] { };
47         StringTokenizer st = new StringTokenizer((String)spec, ",");
48         Address[] ret = new Address[st.countTokens()];
49         for(int i=0; i<ret.length; i++) {
50             String s = st.nextToken();
51             ret[i] = Address.parse(s);
52             if (ret[i] == null) Log.warn(Address.class, "Warning: address " + s + " is unparseable");
53         }
54         return ret;
55     }
56 }