// 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.io.*;
import java.math.*;
import java.net.*;
import java.sql.*;
import java.util.zip.*;

public class GeoLoad {
    /* START CONFIGURATION */
    private final static String urlWebHostingInfo = "http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip";
    private final static String urlMaxMind = "http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip";
    private final static String workDir = "C:\\e";
    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 void download(String urlstr, String zipfnm) throws IOException {
        URL url = new URL(urlstr);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.connect();
        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
           InputStream is = con.getInputStream();
           OutputStream os = new FileOutputStream(workDir + File.separator + zipfnm);
           byte[] b = new byte[100000];
           int n;
           while ((n = is.read(b)) >= 0) {
              os.write(b, 0, n);
           }
           os.close();
           is.close();
        }
        con.disconnect();
    }
    private static void unzip(String zipfnm, String csvfnm) throws IOException {
        ZipFile zf = new ZipFile(workDir + File.separator + zipfnm);
        ZipEntry ze = (ZipEntry) zf.entries().nextElement();
        InputStream is = zf.getInputStream(ze);
        OutputStream os = new FileOutputStream(workDir + File.separator + csvfnm);
        byte[] b = new byte[100000];
        int n;
        while ((n = is.read(b)) >= 0) {
           os.write(b, 0, n);
        }
        os.close();
        is.close();
        zf.close();
    }
    private static void dbimport(String csvfnm, int fromcol, int tocol, int countrycol, String tblnam) throws ClassNotFoundException, SQLException, IOException {
        Class.forName(dbDriver);
        Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
        Statement stmt = con.createStatement();
        try {
            stmt.executeUpdate("DROP TABLE " + tblnam);
        } catch (SQLException e) {
            /* we will end here first time */
        }
        stmt.executeUpdate("CREATE TABLE " + tblnam + "(id INTEGER NOT NULL, ip1 NUMERIC(10,0), ip2 NUMERIC(10,0), country CHAR(2), PRIMARY KEY(id))");
        stmt.executeUpdate("CREATE INDEX ixip1 ON " + tblnam + "(ip1)");
        stmt.executeUpdate("CREATE INDEX ixip2 ON " + tblnam + "(ip2)");
        stmt.close();
        PreparedStatement pstmt = con.prepareStatement("INSERT INTO " + tblnam + " VALUES(?,?,?,?)");
        BufferedReader br = new BufferedReader(new FileReader(workDir + File.separator + csvfnm));
        int n = 0;
        String line;
        while((line = br.readLine()) != null) {
            n++;
            String[] cols = line.split(",");
            BigDecimal fromval = new BigDecimal(cols[fromcol-1].replace('"', ' ').trim());
            BigDecimal toval = new BigDecimal(cols[tocol-1].replace('"', ' ').trim());
            String code = cols[countrycol-1].replace('"', ' ').trim();
            pstmt.setInt(1, n);
            pstmt.setBigDecimal(2, fromval);
            pstmt.setBigDecimal(3, toval);
            pstmt.setString(4, code);
            pstmt.executeUpdate();
        }
        pstmt.close();
        con.close();
    }
    private static void loadWebHostingInfo() throws IOException, ClassNotFoundException, SQLException {
        download(urlWebHostingInfo, "whi.zip");
        unzip("whi.zip", "whi.csv");
        dbimport("whi.csv", 1, 2, 3, "whi");
    }
    private static void loadMaxMind() throws IOException, ClassNotFoundException, SQLException {
        download(urlMaxMind, "mm.zip");
        unzip("mm.zip", "mm.csv");
        dbimport("mm.csv", 3, 4, 5, "mm");
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        loadWebHostingInfo();
        loadMaxMind();
    }
}
