// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package e_geo;

import java.net.*;
import java.sql.*;
import java.util.*;

public class GeoLocate {
    /* START CONFIGURATION */
    private final static String dbDriver = "com.mysql.jdbc.Driver";
    private final static String dbUrl = "jdbc:mysql://localhost/Test";
    private final static String dbUsername = "";
    private final static String dbPassword = "";
    /* END CONFIGURATION */
    private static Connection con;
    private static HashMap cache;
    static {
        try {
            Class.forName(dbDriver);
            con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
            cache = new HashMap();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static String locate(String ip, String tblnam) {
        String country = (String)cache.get(ip);
        if(country == null) {
            try {
                byte[] b = InetAddress.getByName(ip).getAddress();
                long ipnum = 0;
                for(int i = 0; i < 4; i++) {
                    ipnum = (ipnum << 8) | (b[i] & 0xFF);
                }
                synchronized(con) {
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT country FROM " + tblnam + " WHERE ip1 < " + ipnum + " AND " + ipnum + " < ip2");
                    if(rs.next()) {
                        country = rs.getString(1);
                    } else {
                        country = "??";
                    }
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            cache.put(ip, country);
        }
        return country;
    }
}
