package dk.daoas.daoadresseservice; import java.net.URLEncoder; import com.google.gson.Gson; import com.google.common.util.concurrent.RateLimiter; import dk.daoas.daoadresseservice.admin.ServiceConfig; import dk.daoas.daoadresseservice.beans.OSMAddress; import dk.daoas.daoadresseservice.beans.SearchRequest; import dk.daoas.daoadresseservice.beans.SearchResult; import dk.daoas.daoadresseservice.util.HttpUtil; import dk.thoerup.circuitbreaker.CircuitBreaker; import dk.thoerup.circuitbreaker.CircuitBreakerManager; import dk.thoerup.circuitbreaker.CircuitInvocation; public class OSMStreetnameHelper implements StreetnameHelper { ServiceConfig conf; RateLimiter limiter; public OSMStreetnameHelper(ServiceConfig conf) { this.conf = conf; limiter = RateLimiter.create( 10.0 ); //Max 10 requests pr sekund } @Override public String proposeStreetName(SearchRequest request, SearchResult result) { if (conf.useOpenStreetMaps == false) return null; result.osm = true; try { OSMInvocation wrapper = new OSMInvocation( limiter, conf, request.postnr, request.vejnavn ); CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("osm"); result.osmVej = (String) breaker.invoke(wrapper); return result.osmVej; } catch (Exception e) { System.out.println( "OSMError: " + e.getClass().getName() +" / "+ e.getMessage() ); } return null; } static class OSMInvocation implements CircuitInvocation { int postnr; String vejnavn; ServiceConfig conf; RateLimiter limiter; public OSMInvocation(RateLimiter limiter, ServiceConfig conf, int postnr, String vejnavn) { this.limiter = limiter; this.conf = conf; this.postnr= postnr; this.vejnavn = vejnavn; } @Override public String proceed() throws Exception { limiter.acquire(); //TimingHelper timer = new TimingHelper(); String encVej = URLEncoder.encode(vejnavn, "UTF-8"); String url = conf.nominatimBase + "/search?country=DK&street=" + encVej + "&postalcode=" + postnr + "&format=json&addressdetails=1"; //String url = "http://nominatim.openstreetmap.org/search?country=DK&street=" + encVej + "&format=json&addressdetails=1"; //System.out.println (url); String json = HttpUtil.getContentString(url, conf.osmTimeout); //System.out.println(json); Gson gson = new Gson(); OSMAddress adrList[] = gson.fromJson(json, OSMAddress[].class); //timer.printElapsed("OSM elapsed"); //System.out.println("Count: " + adrList.length); if (adrList.length != 1) return null; if (adrList[0].address != null) { return adrList[0].address.road; } return null; } } }