KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lamatek > tags > google > beans > Ip2GeoCoder


1 package com.lamatek.tags.google.beans;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.InputStreamReader JavaDoc;
5 import java.io.Serializable JavaDoc;
6 import java.net.URL JavaDoc;
7 import java.net.URLConnection JavaDoc;
8
9 /**
10  * Ip2GeoCoder
11  * @author Tom Cole
12  * @version 0.40
13  *
14  * This implementation of IPCoder attempts to geocode an IP address using
15  * the Ip2Geo web service.
16  *
17  * Developers should not override this method, but should rather create their
18  * own classes that implement IPCoder.
19  */

20 public class Ip2GeoCoder implements IPCoder, Serializable JavaDoc {
21     
22     String JavaDoc ip = null;
23     double longitude = 0.00d;
24     double latitude = 0.00d;
25     
26     public void setIp(String JavaDoc ip) {
27         this.ip = ip;
28     }
29     public boolean geocode() {
30         if (ip == null) {
31             return false;
32         }
33         else {
34             try {
35                 String JavaDoc path = "http://ws.cdyne.com/ip2geo/ip2geo.asmx/ResolveIP?IPAddress=" + ip + "&LicenseKey=0";
36                 URL JavaDoc url = new URL JavaDoc(path);
37                 URLConnection JavaDoc con = url.openConnection();
38                 BufferedReader JavaDoc input = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(con.getInputStream()));
39                 String JavaDoc line = "";
40                 while ((line = input.readLine()) != null) {
41                     if (line.indexOf("<Latitude>") >= 0) {
42                         int start = line.indexOf(">") + 1;
43                         int stop = line.indexOf("<", start);
44                         latitude = Double.parseDouble(line.substring(start, stop).trim());
45                     }
46                     else if (line.indexOf("<Longitude>") >= 0) {
47                         int start = line.indexOf(">") + 1;
48                         int stop = line.indexOf("<", start);
49                         longitude = Double.parseDouble(line.substring(start, stop).trim());
50                     }
51                 }
52                 input.close();
53                 return true;
54             }
55             catch(Exception JavaDoc ex) {
56                 ex.printStackTrace(System.err);
57                 return false;
58             }
59         }
60     }
61     public double getLongitude() {
62         return longitude;
63     }
64     public double getLatitude() {
65         return latitude;
66     }
67 }
68
Popular Tags