1 package net.sourceforge.jgeocoder.us;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.util.HashMap;
7 import java.util.HashSet;
8 import java.util.Map;
9 import java.util.Set;
10
11 import net.sourceforge.jgeocoder.CommonUtils;
12
13 import org.apache.commons.lang.StringUtils;
14
15 class AliasResolver{
16 private static final Map<String, Map<String, String>> CITY_ALIAS_MAP = new HashMap<String, Map<String,String>>();
17 static{
18 BufferedReader br = null;
19 try {
20 br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("city-alias.txt")));
21 String line = null;
22 Map<String, Set<String>> allRealCitiesMap = new HashMap<String, Set<String>>();
23 while((line=br.readLine())!= null){
24 String[] items = line.split("//s*=//s*");
25 String[] cs = items[0].split("<b>")[1].split("//s*,//s*");
26 String city = cs[0], state = cs[1];
27 String[] alias = items[1].split("[|]");
28 Map<String, String> aliasMap = CITY_ALIAS_MAP.get(state);
29 if(aliasMap == null){
30 aliasMap = new HashMap<String, String>();
31 CITY_ALIAS_MAP.put(state, aliasMap);
32 }
33 for(String a : alias){
34 String aa = a.split("//s*,//s*")[0];
35 String realCity = city.intern();
36 Set<String> allRealCities = allRealCitiesMap.get(state);
37 if(allRealCities == null){
38 allRealCities = new HashSet<String>();
39 allRealCitiesMap.put(state, allRealCities);
40 }
41 allRealCities.add(realCity);
42 if(!allRealCities.contains(aa)){
43 aliasMap.put(aa.replaceAll("//s+", "").intern(), city.intern());
44 }
45 }
46 }
47
48 allRealCitiesMap.clear();
49 allRealCitiesMap = null;
50 } catch (IOException e) {
51 throw new Error("Unable to initalize City Alias Resolver", e);
52 }finally{
53 if(br != null){ try {
54 br.close();
55 } catch (IOException e) {} }
56 }
57 }
58
59 /***
60 * @param city
61 * @param state
62 * @return the real city if the input {@code city} is an recognized alias, otherwise returns the
63 * original input
64 */
65 public static String resolveCityAlias(String city, String state){
66 if(StringUtils.isBlank(city) || StringUtils.isBlank(state)){
67 return city;
68 }
69 Map<String, String> aliasMap = CITY_ALIAS_MAP.get(state);
70 if(aliasMap == null) return city;
71 String realCity = aliasMap.get(city.replaceAll("//s+", ""));
72 return CommonUtils.nvl(realCity, city);
73 }
74
75 }