Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Thursday, December 11, 2014

List of cities as SQL inserts

There are times you might need a list of cities as SQL inserts.
For this reason I extracted quite a large list of cities from MaxMind database.
The list is composed of 2 columns:
  • Country code as ISO-3166 alpha2 (2 letters for each country)
  • City name
There is also a script that creates the cities table (SQL Server syntax):

 CREATE TABLE [dbo].[city](  
      [country_code] [char](2) NOT NULL,  
      [city] [varchar](100) NOT NULL,  
  CONSTRAINT [PK_city] PRIMARY KEY CLUSTERED   
 (  
      [country_code] ASC,  
      [city] ASC  
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
 ) ON [PRIMARY]  

DOWNLOAD: You can download the list of cities HERE

Wednesday, December 3, 2014

Show Resultset as HTML table

There are times you simply want to show some result set as a table on the screen.
You do not need anything fancy, just show some tabular data on the screen.

In order to solve this issue I wrote a very small and lightweight Java class named: ResultSetToHtmlTable. Even through this class is doing a quite simple task it still have some nice qualities:

  • It is very fast. It doesn't construct any string. It simply writes the table directly to a writer.
  • It doesn't use any external libraries. All plain and simple Java.
  • It is only a single class.
  • It knows to format the data in each column. It supports the following formats:
    • Integer - Show 1000 as 1,000
    • Float - Show 0.5145235 as 0.51
    • Currency - Show 5.2 as $5.2
    • Percentage - Show 0.5 as 50%
    • Date - Show 12/5/2014 as 5 Dec 2014
    • Date and time - Show 12/5/2014 12:00:00 as 5 Dec 2014 12:00:00
    • Time - Show only the time part of a date. For example: 13:22:15
  • It allows to align the data to the left or right and add titles to columns.
  • If no strict column information is supplied is knows to auto detect:
    • Column types.
    • Column titles - titles are named as column names returned in query.
    • Column alignment - Numbers are aligned to the right.
The code of this class is quite simple and straightforward. Here is how it looks like:
package com.todacell.util.sql;

import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.DateFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Bashan
 *         Date: 18/11/2014 15:07
 */
public class ResultSetToHtmlTable {

  public void writeTable(ResultSet rs, Writer writer, Column[] columns) throws IOException, SQLException {
    writer.write("<table>");
    // Write titles
    writer.write("\t<tr>\n");
    for (Column column : columns) {
      writer.write("\t\t<th>" + column.title + "</th>");
    }
    writer.write("\t</tr>\n");

    // Write data
    int cols = columns.length;
    while (rs.next()) {
      writer.write("\t<tr>\n");
      for (int i = 0; i < cols; i++) {
        ColumnType columnType = columns[i].columnType;
        String columnAlign = columnAlignToColumnCss.get(columns[i].columnAlign);
        writer.write("\t\t<td" + columnAlign + ">" + format(columnType, rs.getObject(i + 1)) + "</td>");
      }
      writer.write("\t</tr>");
    }

    writer.write("</table>");
  }

  private static Map<Integer, ColumnType> sqlTypeToColumnType = new HashMap<Integer, ColumnType>();
  private static Map<ColumnType, ColumnAlign> columnTypeTpColumnAlign = new HashMap<ColumnType, ColumnAlign>();
  private static Map<ColumnAlign, String> columnAlignToColumnCss = new HashMap<ColumnAlign, String>();

  static {
    // Map SQL types to column types

    // integer
    sqlTypeToColumnType.put(Types.INTEGER, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.BIGINT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.SMALLINT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.TINYINT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.NUMERIC, ColumnType.INTEGER);

    // float
    sqlTypeToColumnType.put(Types.FLOAT, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.DOUBLE, ColumnType.INTEGER);
    sqlTypeToColumnType.put(Types.DECIMAL, ColumnType.INTEGER);

    // date
    sqlTypeToColumnType.put(Types.TIME, ColumnType.DATE);
    sqlTypeToColumnType.put(Types.TIMESTAMP, ColumnType.DATE);

    // Map column type to column alignment
    columnTypeTpColumnAlign.put(ColumnType.INTEGER, ColumnAlign.RIGHT);
    columnTypeTpColumnAlign.put(ColumnType.FLOAT, ColumnAlign.RIGHT);
    columnTypeTpColumnAlign.put(ColumnType.CURRENCY, ColumnAlign.RIGHT);
    columnTypeTpColumnAlign.put(ColumnType.DATE, ColumnAlign.LEFT);
    columnTypeTpColumnAlign.put(ColumnType.STRING, ColumnAlign.LEFT);

    // Map column alignment to css style
    columnAlignToColumnCss.put(ColumnAlign.LEFT, "");
    columnAlignToColumnCss.put(ColumnAlign.RIGHT, " style=\"text-align:right\"");
    columnAlignToColumnCss.put(ColumnAlign.CENTER, " style=\"text-align:center\"");
  }

  public void writeTable(ResultSet rs, Writer writer) throws IOException, SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    int cols = meta.getColumnCount();

    Column[] columns = new Column[meta.getColumnCount()];
    for (int i = 0; i < cols; i++) {
      ColumnType columnType = sqlTypeToColumnType.get(meta.getColumnType(i + 1));
      ColumnAlign columnAlign = columnTypeTpColumnAlign.get(columnType);
      columns[i] = new Column(
          columnType != null ? columnType : ColumnType.STRING,
          meta.getColumnName(i + 1),
          columnAlign != null ? columnAlign : ColumnAlign.LEFT);
    }

    writeTable(rs, writer, columns);
  }

  public enum ColumnType {
    STRING, INTEGER, FLOAT, DATE, DATE_TIME, TIME, CURRENCY, PERCENTAGE
  }

  public enum ColumnAlign {
    LEFT, RIGHT, CENTER
  }

  private static NumberFormat integerFormat = NumberFormat.getInstance();
  private static NumberFormat floatFormat = NumberFormat.getInstance();
  private static final NumberFormat percentFormat = NumberFormat.getPercentInstance();
  private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
  private static final DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
  private static final DateFormat dateTimeFormat = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");
  private static final DateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");

  static {
    floatFormat.setMaximumFractionDigits(2);
    integerFormat.setMaximumFractionDigits(0);
  }

  public String format(ColumnType columnType, Object value) {
    String result;
    if (value != null) {
      if (columnType == ColumnType.STRING) {
        result = value.toString();
      } else {
        Format format;
        if (columnType == ColumnType.FLOAT) {
          format = floatFormat;
        } else if (columnType == ColumnType.CURRENCY) {
          format = currencyFormat;
        } else if (columnType == ColumnType.PERCENTAGE) {
          format = percentFormat;
        } else if (columnType == ColumnType.DATE) {
          format = dateFormat;
        } else if (columnType == ColumnType.DATE_TIME) {
          format = dateTimeFormat;
        } else if (columnType == ColumnType.TIME) {
          format = timeFormat;
        }else {
          format = integerFormat;
        }

        result = format.format(value);
      }
    } else {
      result = "N/A";
    }

    return result;
  }

  public static class Column {
    ColumnType columnType;
    String title;
    ColumnAlign columnAlign;

    public Column(ColumnType columnType, String title, ColumnAlign columnAlign) {
      this.columnType = columnType;
      this.title = title;
      this.columnAlign = columnAlign;
    }
  }
}

And here is a simple example of how to use this code in a JSP file:
 <%@ page import="com.todacell.management.SessionSingleton" %>  
 <%@ page import="com.todacell.util.sql.ResultSetToHtmlTable" %>  
 <%@ page import="org.hibernate.Session" %>  
 <%@ page import="java.sql.Connection" %>  
 <%@ page import="java.sql.ResultSet" %>  
 <%@ page import="java.sql.Statement" %>  
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>  
 <html>  
 <head>  
   <title>Daily Deposits</title>  
   <style type="text/css">  
     table {  
       border-collapse: collapse;  
     }  
     table, th, td {  
       border: 1px solid black;  
     }  
     td, th {  
       padding: 5px;  
     }  
   </style>  
 </head>  
 <body>  
 <jsp:include page="k2_menu.jsp" />  
 <h1>Daily Deposits</h1>  
 <%  
   Session hSession = SessionSingleton.instance();  
   Connection conn = hSession.connection();  
   try {  
     Statement stmt = conn.createStatement();  
     ResultSet rs = stmt.executeQuery("select * from k2_deposits(60)");  
     ResultSetToHtmlTable resultSetToHtmlTable = new com.todacell.util.sql.ResultSetToHtmlTable();  
     resultSetToHtmlTable.writeTable(rs, out,  
         new com.todacell.util.sql.ResultSetToHtmlTable.Column[] {  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.DATE, "Date", ResultSetToHtmlTable.ColumnAlign.LEFT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Deposits", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Allocated", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Deallocated", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Ad Spend", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.CURRENCY, "Potential Spend", ResultSetToHtmlTable.ColumnAlign.RIGHT),  
             new ResultSetToHtmlTable.Column(ResultSetToHtmlTable.ColumnType.INTEGER, "New Users", ResultSetToHtmlTable.ColumnAlign.RIGHT)  
         });  
   } finally {  
     if (hSession != null) {  
       hSession.close();  
     }  
   }  
 %>  
 </body>  
 </html>  
And here is how it looks on the browser:
DOWNLOAD: You can download the ResultSetToHtmlTable here

Thursday, November 13, 2014

Working with SHA1 on SQL Server


There are times you might need to convert some information to MD5 on your SQL Server in HEX format. As it is for now there is no out of the box function to do it on SQL Server. But you can easily accomplish this task by using the following function:
create FUNCTION [dbo].[sha1]
(
        @value varchar(4000)
)
RETURNS varchar(40)
AS
BEGIN
  return
    case when @value is not null then
      SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA1', @value)), 3, 40)
    else null end
END
GO

Testing it is quite straight forward. For example:
select dbo.sha1('123') 

And here is the output:
40bd001563085fc35165329ea1ff5c5ecbdbbeef


 

Wednesday, November 12, 2014

Working with MD5 on SQL Server


There are times you might need to convert some information to MD5 on your SQL Server in HEX format. As it is for now there is no out of the box function to do it on SQL Server. But you can easily accomplish this task by using the following function:
create FUNCTION [dbo].[md5]
(
        @value varchar(4000)
)
RETURNS varchar(40)
AS
BEGIN
  return
    case when @value is not null then
      (SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', @value)), 3, 32))
    else null end
END
GO

Testing it is quite straight forward. For example:
select dbo.md5('123') 

And here is the output:
202cb962ac59075b964b07152d234b70 


 

Saturday, December 18, 2010

Mobile Operator/Carrier detection using MaxMind – Second Part – Creating carriers JSON file

In this post we saw how the first steps to mobile operator/carrier detection. We saw how the data of carriers and carriers mapping is stored in database.
Now we will see how to convert this data to a JSON file. Our mobile operator/carrier detection module will be probably be used by an Ad server. Ad servers are usually not connected to database (you need Ad server to be robust and work under high pressure). Therefore, we would like to be able to load the carriers information from a simple file.
For this purpose, we will create a simple class named CarrierDataHolder that will host all the mobile operator/carrier mapping in a single map. The map is constructed from 2 inner classes: a composite key named Key and value named Value.
These are the members of the map Key:
  • countryCode
  • isp
  • org
These are the members of the map Value:
  • carrierId
  • name
Note, that for the Key of the map, we implement “hashCode” and “equals” methods, otherwise the map would not function properly.
By using this map, we later be able to get any carrier simple by supplying country code, isp and organization. The country code isp and organization will be extracted from the user ip using MaxMind.
The CarrierDataHolder contains 2 important methods:
  • loadCarriersFromDB – This method gets a database connection and loads all the carrier and carrier mapping information to the carrierMapping map.
  • toJSONFile – This method stores all the data loaded to carrierMapping map to a JSON file. The data is saved to JSON using XStream open source project.
Let’s have a look at the CarrierDataHolder class:
package com.bashan.blog.geo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author Bashan
*/
public class CarrierDataHolder {
 
public final Map<Key, Value> carrierMapping = new HashMap<Key, Value>();
 
public void loadCarriersFromDB(Connection conn) throws SQLException {
carrierMapping.clear();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select c.carrier_id, c.country_code, c.name, cm.isp, cm.org from carrier c inner join " +
"carrier_mapping cm on c.carrier_id = cm.carrier_id order by c.carrier_id");
  while (rs.next()) {
    int carrierId = rs.getInt("carrier_id");
String countryCode = rs.getString("country_code");
String name = rs.getString("name");
String isp = rs.getString("isp");
String org = rs.getString("org");
carrierMapping.put(new Key(countryCode, isp, org), new Value(carrierId, name));
}
}
 
private XStream getXStream() {
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("carrierMapping", Map.class);
xstream.alias("key", Key.class);
xstream.alias("value", Value.class);
  return xstream;
} 
 
public String toJSON() {
XStream xStream = getXStream();
  return xStream.toXML(carrierMapping);
} 
 
public void toJSONFile(File file) throws IOException {
XStream xStream = getXStream();
FileWriter fileWriter = null;
  try {
fileWriter = new FileWriter(file);
xStream.toXML(carrierMapping, fileWriter);
} finally {
      if (fileWriter != null) {
fileWriter.close();
}
}
}
 
public static class Key {
 
private String countryCode;
private String isp;
private String org;
 
public Key() {
}
 
public Key(String countryCode, String isp, String org) {
  this.countryCode = countryCode;
  this.isp = isp;
  this.org = org;
}
 
public String getCountryCode() {
  return countryCode;
} 
 
public void setCountryCode(String countryCode) {
  this.countryCode = countryCode;
} 
 
public String getIsp() {
  return isp;
} 
 
public void setIsp(String isp) {
  this.isp = isp;
} 
 
public String getOrg() {
  return org;
} 
 
public void setOrg(String org) {
  this.org = org;
}
 
@Override
public boolean equals(Object o) {
  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
  if (countryCode != null ? !countryCode.equals(key.countryCode) : key.countryCode != null) return false;
  if (isp != null ? !isp.equals(key.isp) : key.isp != null) return false;
  if (org != null ? !org.equals(key.org) : key.org != null) return false;
  return true;
} 
 
@Override
public int hashCode() {
  int result = countryCode != null ? countryCode.hashCode() : 0;
result = 31 * result + (isp != null ? isp.hashCode() : 0);
result = 31 * result + (org != null ? org.hashCode() : 0);
  return result;
}
} 
 
public static class Value {
 
private int carrierId;
private String name;
 
public Value() {
} 
 
public Value(int carrierId, String name) {
  this.carrierId = carrierId;
  this.name = name;
} 
 
public int getCarrierId() {
  return carrierId;
} 
 
public void setCarrierId(int carrierId) {
  this.carrierId = carrierId;
} 
 
public String getName() {
  return name;
} 
 
public void setName(String name) {
  this.name = name;
}
}
}


The data loaded by the loadCarriersFromDB method is taken from carrier and carrier_mapping tables. This post explains how they are created.

Let’s have a look at a small test program that loads all carriers information and stores it to a JSON file. Note that we assume the name of the database is adserver:
public static void main(String[] args) {
CarrierDataHolder carrierDataHolder = new CarrierDataHolder();
Connection conn = null;
  try {
String userName = "root";
String password = "root";
String url = "jdbc:mysql://localhost:3306/adserver?useUnicode=true&characterEncoding=UTF-8";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
carrierDataHolder.loadCarriersFromDB(conn);
carrierDataHolder.toJSONFile(new File("c:\\data\\carriers.json"));
} catch (Exception e) {
e.printStackTrace();
} finally {
  if (conn != null) {
    try {
conn.close();
} catch (SQLException sql) {
sql.printStackTrace();
}
}
}
}

You can download the class CarrierDataHolder by pressing this link. Note that this class is using XStream open source project. Therefore you will have to download XStream jar files as well (xstream and jettison).
Here is the mobile operators/carriers detection JSON file generated by using the CarrierDataHolder class.

Wednesday, December 1, 2010

Mobile Operator/Carrier detection using MaxMind – First Part – Database information

One important key targeting of mobile advertising networks, is the ability to target mobile campaigns for specific mobile operators/carrier. In order to it, we have to be able to detect the mobile operator of a given IP. I have been looking for quite some time (the passed 2 years) for a decent solution for mobile operator detection. The only decent solution (there are not much services like that) came from Quova. The problem with Quova, is that they don’t give you an API and some binary file (like most other geo/device targeting services). They insist you install dedicated server solution, that you have to query by HTTP, in order to get the information you want. If you have several machines, you have to start install Quova solution on each and every one of them.
Since we didn’t like Quova solution on the company that I work for (Mobile Ad Network), and we couldn’t find any other good solution, we decided on developing our own in-house solution. The solution is based on user IP and ISP and Organization data as it extracted from MaxMind geo service.
This is in general the detection processes:
  • Get client IP.
  • Use MaxMind to extract ISP and Organization from client IP.
  • Check what is the corresponding mobile operator/carrier for the given combination of ISP and Organization.
The solution is quite simple and neat. The only problem with it, is that it is needed to be maintained on a regular basis, since Geo information is being changed all the time.
In order to be able to identify mobile operators, we first need to have two tables containing the following information:
  • Mobile operators/carriers table, containing all mobile operators in the world. You can have a look at this post in order to see how I built the information in this table.
  • Mobile operators and their ISP and organization. This table maps between mobile operators and their corresponding ISPs and organizations. Building this table is a hard work involving data mining, research and continuing refinement and update process. During the time of this post, the data in this table is quite good, but not full (not all countries/mobile operators are mapped).
Note for:
  • The data in these tables is loaded to memory, since we need good performance.
  • MaxMind updates it’s ISP and Organization data on a monthly basis.
  • ISP and Organization is being changed all the time. The changes are not drastic, but they happen all the time, so data is needed to be maintained, and there is a need to keep refining the mapping between mobile operators/carriers and combinations of ISP and Organizations.
Let’s have a look at the structure of the mobile operators/carriers table. The table is called “carrier” and contains 3 columns:
  • carrier_id – The id of the mobile operator/carrier. This is not some universal id. It is an arbitrary id used only by the system.
  • country_code – The country code of the mobile operator/carrier.
  • name – The name of the mobile operator/carrier.
The SQL script that creates this table:
CREATE TABLE `carrier` (
`carrier_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`country_code` char(2) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`carrier_id`)
) ENGINE=InnoDB;
This script contains both the scrip that creates “carrier” table as well as its data. It contains all the mobile operators in the world. This data has to be maintained (carriers are being added or merged from time to time), but not very often.

This is the structure of the table that maps ISPs and Organizations to mobile operators/carriers. The table is called: “carrier_mapping” and also contains 3 columns:
  • carrier_id – The id of the mobile operator/carrier, for which we would to like to map a combination of ISP and Organization.
  • isp – ISP corresponds to carried_id.
  • org – Organization corresponds to carrier_id.
The SQL script that creates this table:
CREATE TABLE `carrier_mapping` (
`carrier_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`isp` varchar(50) NOT NULL,
`org` varchar(50) NOT NULL,
PRIMARY KEY (`carrier_id`,`isp`,`org`),
CONSTRAINT `FK_carrier_mapping_carrier_id` FOREIGN KEY (`carrier_id`) REFERENCES `carrier` (`carrier_id`)
) ENGINE=InnoDB;
This script contains both the scrip that creates “carrier_mapping” table as well as its data. It contains a decent amount of mapping of most large mobile operators/carriers in the world. Note that the data here may not be so accurate in a few months or so.

Saturday, July 11, 2009

Programmatically Delete a database in SQL server

Sometimes we would like to programmatically delete SQL server database. Simply writing:
DROP DATABASE 'database_name'
is not always a good solution, for 2 main reasons:
  1. The database may be already deleted, therefore we will get exception telling there is no such database to delete.
  2. There may still be existing connections to the database, preventing from the database being deleted.
The first problem can be easily solved by checking the existence of the database before deleting it:
IF EXISTS (SELECT 1 FROM SYS.DATABASES WHERE NAME = 'database_name') BEGIN
DROP DATABASE 'database_name'
END
GO
Solving the second problem is a bit harder. In order to delete the database, all existing connections needed to be closed. This should be done carefully since we do not want to close our own connection. This script, first closes all existing connections and then drops the database:
DECLARE @spid INT,
@cnt INT,
@sql VARCHAR(255)
IF EXISTS (SELECT 1 FROM SYS.DATABASES WHERE NAME = 'database_name') BEGIN
SELECT @spid = MIN(spid), @cnt = COUNT(*)
FROM master..sysprocesses
WHERE dbid = DB_ID('database_name')
AND spid != @@SPID
PRINT 'Starting to KILL '+RTRIM(@cnt)+' processes.'
WHILE @spid IS NOT NULL
BEGIN
PRINT 'About to KILL '+RTRIM(@spid)
SET @sql = 'KILL '+RTRIM(@spid)
EXEC(@sql)
SELECT @spid = MIN(spid), @cnt = COUNT(*)
FROM master..sysprocesses
WHERE dbid = DB_ID('database_name')
AND spid != @@SPID
PRINT RTRIM(@cnt)+' processes remain.'
END
DROP DATABASE 'database_name'
END
GO
Note that the name of the database (“database_name” in this example) can be replaced with SQL parameter.