Package gt.geolocation

Source Code of gt.geolocation.IPAddressBasedGeoAcquirer

package gt.geolocation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;

import gt.geolocation.w3c.Coordinates;
import gt.geolocation.w3c.Position;

public class IPAddressBasedGeoAcquirer extends GeolocationAcquirer {
 
  private String getCurrentIPAddress() throws MalformedURLException, IOException {
    HttpURLConnection conn = (HttpURLConnection)new URL("http://ifconfig.me/ip").openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String response = reader.readLine();
    if (conn.getResponseCode() == 200) {
      return response.trim();
    } else {
      return null;
    }
  }
 
  @Override
  protected Position acquireLocation(boolean enableHighAccuracy) throws InterruptedException {
    HttpURLConnection conn = null;
    try {
      String ipAddress = getCurrentIPAddress();
      if (ipAddress != null) {
        conn = (HttpURLConnection)new URL("http://freegeoip.net/csv/"+ipAddress).openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        if (conn.getResponseCode() == 200) {
          StringTokenizer stTok = new StringTokenizer(response, ",");
          stTok.nextToken(); // IP Address
          stTok.nextToken(); // country code
          stTok.nextToken(); // country
          stTok.nextToken(); // state code
          stTok.nextToken(); // state
          stTok.nextToken(); // city
          stTok.nextToken(); // zip code
          String x = stTok.nextToken().substring(1);
          x = x.substring(0, x.length()-1);
          double latitude = Double.parseDouble(x);
          x = stTok.nextToken().substring(1);
          x = x.substring(0, x.length()-1);
          double longitude = Double.parseDouble(x);
         
          Coordinates coords = new Coordinates(latitude, longitude, new Double(0), 0, new Double(0), null, new Double(0));
          Position pos = new Position(coords, -1);
          return pos;
        } else {
          return null;
        }
      } else {
        return null;
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      conn.disconnect();
    }
   
    return null;
  }

}
TOP

Related Classes of gt.geolocation.IPAddressBasedGeoAcquirer

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.