My favorites | Sign in
Project Home Wiki
Search
for
GoogleAppEngine  
Sample code for Google App Engine
Updated Feb 4, 2010 by wtan...@yahoo.com

Helper Function

def getGeoIPCode(ipaddr):
   from google.appengine.api import memcache
   memcache_key = "gip_%s" % ipaddr
   data = memcache.get(memcache_key)
   if data is not None:
      return data

   geoipcode = ''
   from google.appengine.api import urlfetch
   try:
      fetch_response = urlfetch.fetch(
            'http://geoip.wtanaka.com/cc/%s' % ipaddr)
      if fetch_response.status_code == 200:
         geoipcode = fetch_response.content
   except urlfetch.Error, e:
      pass

   if geoipcode:
      memcache.set(memcache_key, geoipcode)
   return geoipcode

Django Helper for Google App Engine

getGeoIPCode(request.META['REMOTE_ADDR'])

WSGI

getGeoIPCode(self.request.remote_addr)
Comment by joakim.erdfelt, Oct 16, 2009

Java AppEngine? Example

GeoIp?.java

package com.erdfelt.example.geoip;

import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class GeoIp {
    private static final Logger    logger     = Logger.getLogger(GeoIp.class.getName());
    private static final String    USER_AGENT = "GAE/" + GeoIp.class.getName();
    private static final String    GEOIP_URL  = "http://geoip.wtanaka.com/cc/";
    private static MemcacheService memcache;
    private static URLFetchService urlfetch;

    static {
        memcache = MemcacheServiceFactory.getMemcacheService();
    }

    public static String fetchCountry(String ip) {
        try {
            if (urlfetch == null) {
                urlfetch = URLFetchServiceFactory.getURLFetchService();
            }

            URL url = new URL(GEOIP_URL + ip);
            HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET);
            request.addHeader(new HTTPHeader("User-Agent", USER_AGENT));

            HTTPResponse response = urlfetch.fetch(request);
            if (response.getResponseCode() != 200) {
                return null;
            }

            String country = new String(response.getContent(), "UTF-8");
            return country;
        } catch (Throwable t) {
            logger.log(Level.WARNING, "Unable to fetch GeoIp for " + ip, t);
            return null;
        }
    }

    public static String getClientCountry(HttpServletRequest request) {
        return getCountry(request.getRemoteAddr());
    }

    public static String getCountry(String ip) {
        if (ip == null) {
            return null;
        }

        String cacheid = "geoip-" + ip;
        String country = (String) memcache.get(cacheid);

        if (country == null) {
            // Perform lookup at geoip.wtanaka.com
            country = fetchCountry(ip);

            if (country != null) {
                // Store lookup in memcache.
                memcache.put(cacheid, country);
            }
        }

        return country;
    }
}

GeoIpServlet?

Example Servlet that uses the GeoIp?.class

package com.erdfelt.example.geoip;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GeoIpServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        out.println("<html>");
        out.println("<head><title>GeoIp Example</title></head>");
        out.println("<style type='text/css'>");
        out.println(" body { font-family: sans-serif; }");
        out.println(" .country { font-weight:bold; color:cyan; ");
        out.println("   background-color:blue; padding:5px; }");
        out.println(" .country code { font-size:1.2em; }");
        out.println("</style>");

        out.println("<body>");

        out.println("<h1>GeoIp Example</h1>");
        
        String geourl = "http://geoip.wtanaka.com/";

        out.printf("<p>Demonstrating use of <a href='%s'>%s</a></p>%n", geourl, geourl);

        out.printf("<p>Your IP is %s and you are in %s</p>%n", req.getRemoteAddr(), toCountryHtml(GeoIp
                .getClientCountry(req)));

        String ip = req.getRemoteAddr();

        if (req.getParameter("ip") != null) {
            ip = req.getParameter("ip");

            out.printf("<p>Results: %s is in %s</p>%n", ip, toCountryHtml(GeoIp.getCountry(ip)));
        }

        out.printf("<form method='get' action='%s%s'>%n", req.getContextPath(), req.getServletPath());
        out.println("<p>Provide an IP address:</p>");
        out.printf("<p><input type='text' name='ip' value='%s' /></p>%n", ip);
        out.println("<p><input type='submit' value='Submit'></p>");
        out.println("</form>");

        out.println("</body>");

        out.println("</html>");
    }

    private String toCountryHtml(String country) {
        if (country == null) {
            return "<em>No Country Found</em>";
        }
        return String.format("<span class='country'><code>%s</code> (%s)</span>", country, toDisplayCountry(country));
    }

    private String toDisplayCountry(String country) {
        if ("zz".equals(country)) {
            return "Local IP / No Country";
        }
        return new Locale("", country).getDisplayCountry();
    }
}
Comment by skb....@gmail.com, May 19, 2011

may i know whether above servlet give the latest data,


Sign in to add a comment
Powered by Google Project Hosting