1
22
23 package com.liferay.portlet.cszsearch.util;
24
25 import com.liferay.portal.kernel.util.StringPool;
26 import com.liferay.portal.kernel.util.Validator;
27 import com.liferay.portal.util.WebCacheable;
28 import com.liferay.portlet.cszsearch.model.CSZAddress;
29 import com.liferay.util.ConverterException;
30 import com.liferay.util.Html;
31 import com.liferay.util.Http;
32 import com.liferay.util.HttpUtil;
33 import com.liferay.util.Time;
34
35 import java.io.BufferedReader;
36 import java.io.StringReader;
37
38 import java.util.ArrayList;
39 import java.util.List;
40
41
47 public class CityStateConverter implements WebCacheable {
48
49 public CityStateConverter(String cityAndState) {
50 _cityAndState = cityAndState;
51 }
52
53 public Object convert(String id) throws ConverterException {
54 List list = new ArrayList();
55
56 String cityAndState = _cityAndState;
57 String city = null;
58 String state = null;
59
60 try {
61 int pos = cityAndState.indexOf(StringPool.COMMA);
62
63 city = cityAndState.substring(0, pos);
64 state = cityAndState.substring(
65 pos + 1, cityAndState.length()).trim();
66 }
67 catch (Exception e) {
68 return list;
69 }
70
71 try {
72 String text = Http.URLtoString(
73 "http://zip4.usps.com/zip4/zcl_1_results.jsp?pagenumber=all" +
74 "&city=" + HttpUtil.encodeURL(city) + "&state=" +
75 HttpUtil.encodeURL(state));
76
77 int x = text.indexOf("<!-- **");
78 int y = text.lastIndexOf("<!-- **");
79
80 BufferedReader br = new BufferedReader(
81 new StringReader(Html.stripHtml(text.substring(x, y))));
82
83 String line = null;
84
85 while ((line = br.readLine()) != null) {
86 line = line.trim();
87
88 if (!line.equals("")) {
89
90 if (Validator.isNumber(line)) {
91 list.add(new CSZAddress(null, city, state, line));
92 }
93 }
94 }
95
96 br.close();
97 }
98 catch (Exception e) {
99 throw new ConverterException(e);
100 }
101
102 return list;
103 }
104
105 public long getRefreshTime() {
106 return _REFRESH_TIME;
107 }
108
109 private static final long _REFRESH_TIME = Time.DAY * 90;
110
111 private String _cityAndState;
112
113 }