1
22
23 package com.liferay.portlet.cszsearch.util;
24
25 import com.liferay.portal.kernel.util.StringPool;
26 import com.liferay.portal.util.WebCacheable;
27 import com.liferay.portlet.cszsearch.model.CSZAddress;
28 import com.liferay.util.ConverterException;
29 import com.liferay.util.Http;
30 import com.liferay.util.HttpUtil;
31 import com.liferay.util.Time;
32
33 import java.io.BufferedReader;
34 import java.io.IOException;
35 import java.io.StringReader;
36
37 import java.util.ArrayList;
38 import java.util.List;
39
40
46 public class Zip4Converter implements WebCacheable {
47
48 public Zip4Converter(String street, String cityAndState) {
49 _street = street;
50 _cityAndState = cityAndState;
51 }
52
53 public Object convert(String id) throws ConverterException {
54 List list = new ArrayList();
55
56 String street = _street;
57 String city = "";
58 String state = "";
59 String zip = "";
60
61 try {
62 String csz = _cityAndState;
63
64 int pos = csz.indexOf(StringPool.COMMA);
65
66 if (pos != -1) {
67 city = csz.substring(0, pos).trim();
68 state = csz.substring(pos + 1, csz.length()).trim();
69 }
70 else {
71 zip = csz;
72 }
73 }
74 catch (Exception e) {
75 return list;
76 }
77
78 try {
79 String text = Http.URLtoString(
80 "http://zip4.usps.com/zip4/zcl_0_results.jsp?visited=1&" +
81 "pagenumber=all&firmname=&urbanization=&address1=&" +
82 "address2=" + HttpUtil.encodeURL(street) + "&city=" +
83 HttpUtil.encodeURL(city) + "&state=" + state +
84 "&zip5=" + zip);
85
86 if (text.indexOf("headers=\"full\"") > -1) {
87 int x = text.indexOf("<td headers=\"full\"");
88 x = text.indexOf(">", x) + 1;
89
90 int y = text.indexOf("<br />", x);
91
92 street = text.substring(x, y).trim();
93
94 x = y + 6;
95
96 y = text.indexOf(" ", x);
97
98 city = text.substring(x, y).trim();
99
100 x = y + 6;
101
102 y = text.indexOf(" ", x);
103
104 state = text.substring(x, y).trim();
105
106 x = y + 12;
107
108 y = text.indexOf("<br />", x);
109
110 zip = text.substring(x, y).trim();
111
112 list.add(new CSZAddress(street, city, state, zip));
113 }
114 else if (text.indexOf("headers=\"units\"") > -1) {
115 int x = text.indexOf("<!-- **");
116 int y = text.lastIndexOf("<!-- **");
117
118 BufferedReader br = new BufferedReader(
119 new StringReader(text.substring(x, y)));
120
121 String line = null;
122
123 while ((line = br.readLine()) != null) {
124 if (line.indexOf("headers=\"zip\"") > -1) {
125 zip = br.readLine().trim();
126
127 list.add(new CSZAddress(street, city, state, zip));
128 }
129 }
130
131 br.close();
132 }
133 }
134 catch (IOException ioe) {
135 throw new ConverterException(ioe);
136 }
137 catch (Exception e) {
138 }
139
140 return list;
141 }
142
143 public long getRefreshTime() {
144 return _REFRESH_TIME;
145 }
146
147 private static final long _REFRESH_TIME = Time.DAY * 90;
148
149 private String _street;
150 private String _cityAndState;
151
152 }