1 36 package org.columba.ristretto.parser; 37 38 import java.util.ArrayList ; 39 import java.util.LinkedList ; 40 import java.util.List ; 41 import java.util.regex.Matcher ; 42 import java.util.regex.Pattern ; 43 44 import org.columba.ristretto.message.Address; 45 46 51 public class AddressParser { 52 53 private static final Pattern addressTokenizerPattern = 54 Pattern.compile("([^\\s]+?)(\\s|<|$)+"); 55 56 private static final Pattern trimPattern = 57 Pattern.compile("[\"<]?([^\"<>]*)[\">]?"); 58 59 61 62 70 public static Address[] parseMailboxList(CharSequence mailboxList) throws ParserException { 71 List result = new LinkedList (); 72 CharSequence [] tokens = tokenizeList(mailboxList); 73 74 for( int i=0; i< tokens.length; i++) { 75 result.add(parseAddress(tokens[i])); 76 } 77 78 Address[] a = new Address[result.size()]; 79 result.toArray((Object []) a); 80 return a; 81 } 82 83 91 public static Address parseAddress(CharSequence address) throws ParserException { 92 Matcher addressTokenizer = addressTokenizerPattern.matcher(address); 93 94 ArrayList tokens = new ArrayList (); 95 96 while (addressTokenizer.find()) { 97 tokens.add(addressTokenizer.group(1)); 98 } 99 100 if (tokens.size() < 1) { 101 throw new ParserException("No valid EMail address", address); 102 } else if (tokens.size() == 1) { 103 return new Address(trim((String )tokens.get(0))); 104 } else { 105 StringBuffer name = new StringBuffer ((String )tokens.get(0)); 106 107 for (int i = 1; i < tokens.size() - 1; i++) { 108 name.append(' '); 109 name.append((String )tokens.get(i)); 110 } 111 112 return new Address(trim(name), 113 trim((String )tokens.get(tokens.size() - 1))); 114 } 115 } 116 117 private static String trim(CharSequence input) { 118 Matcher trimMatcher = trimPattern.matcher(input); 119 120 if( trimMatcher.matches() ) { 121 return trimMatcher.group(1); 122 } else { 123 return input.toString(); 124 } 125 } 126 127 private static CharSequence [] tokenizeList(CharSequence input) { 128 List result = new ArrayList (); 129 boolean quoted= false; 130 131 int start = 0; 132 int i; 133 134 for( i=0; i<input.length(); i++) { 135 char c = input.charAt(i); 136 137 switch( c ) { 138 case '\"' : { 139 quoted ^= true; 140 break; 141 } 142 143 case ',' : { 144 if( ! quoted ) { 145 result.add(input.subSequence(start, i)); 146 start = i+1; 147 } 148 break; 149 } 150 } 151 } 152 if( start < i ) { 153 result.add(input.subSequence(start, i)); 154 } 155 156 return (CharSequence [])result.toArray(new CharSequence [0]); 157 } 158 } 159 | Popular Tags |