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.Html;
30 import com.liferay.util.Http;
31 import com.liferay.util.TextFormatter;
32 import com.liferay.util.Time;
33
34 import java.io.BufferedReader;
35 import java.io.StringReader;
36
37 import java.util.ArrayList;
38 import java.util.List;
39
40
46 public class ZipConverter implements WebCacheable {
47
48 public ZipConverter(String zip) {
49 _zip = zip;
50 }
51
52 public Object convert(String id) throws ConverterException {
53 List list = new ArrayList();
54
55 String city = null;
56 String state = null;
57 String zip = _zip;
58
59 try {
60 String text = Http.URLtoString(
61 "http://zip4.usps.com/zip4/zcl_3_results.jsp?zip5=" + zip);
62
63 BufferedReader br = new BufferedReader(new StringReader(text));
64
65 String line = null;
66
67 while ((line = br.readLine()) != null) {
68 line = line.trim();
69
70 if (!line.equals("")) {
71 if (line.indexOf(
72 "<h2 style=\"color:#CC0000;\">Not Acceptable")
73 > -1) {
74
75 break;
76 }
77 else if (line.indexOf(
78 "<td valign=\"top\" class=\"main\"") > -1) {
79
80 String cityAndState = Html.stripHtml(line).trim();
81
82 int pos = cityAndState.indexOf(StringPool.COMMA);
83
84 city = cityAndState.substring(0, pos);
85 state = cityAndState.substring(
86 pos + 1, cityAndState.length()).trim();
87
88 if (city != null && state != null) {
89 list.add(new CSZAddress(
90 null, TextFormatter.formatName(city), state,
91 zip));
92
93 city = null;
94 state = null;
95 }
96 }
97 }
98 }
99
100 br.close();
101 }
102 catch (Exception e) {
103 throw new ConverterException(e);
104 }
105
106 return list;
107 }
108
109 public long getRefreshTime() {
110 return _REFRESH_TIME;
111 }
112
113 private static final long _REFRESH_TIME = Time.DAY * 90;
114
115 private String _zip;
116
117 }