1 |
package dk.daoas.daoadresseservice;
|
2 |
|
3 |
import java.net.URLEncoder;
|
4 |
|
5 |
import com.google.gson.Gson;
|
6 |
|
7 |
import dk.daoas.daoadresseservice.admin.ServiceConfig;
|
8 |
import dk.daoas.daoadresseservice.beans.OSMAddress;
|
9 |
import dk.daoas.daoadresseservice.beans.SearchRequest;
|
10 |
import dk.daoas.daoadresseservice.beans.SearchResult;
|
11 |
import dk.daoas.daoadresseservice.util.HttpUtil;
|
12 |
import dk.thoerup.circuitbreaker.CircuitBreaker;
|
13 |
import dk.thoerup.circuitbreaker.CircuitBreakerManager;
|
14 |
import dk.thoerup.circuitbreaker.CircuitInvocation;
|
15 |
|
16 |
public class OSMStreetnameHelper implements StreetnameHelper {
|
17 |
|
18 |
ServiceConfig conf;
|
19 |
|
20 |
public OSMStreetnameHelper(ServiceConfig conf) {
|
21 |
this.conf = conf;
|
22 |
}
|
23 |
|
24 |
@Override
|
25 |
public String proposeStreetName(SearchRequest request, SearchResult result) {
|
26 |
if (conf.useOpenStreetMaps == false)
|
27 |
return null;
|
28 |
|
29 |
result.osm = true;
|
30 |
|
31 |
try {
|
32 |
|
33 |
OSMInvocation wrapper = new OSMInvocation( conf, request.postnr, request.vejnavn );
|
34 |
CircuitBreaker breaker = CircuitBreakerManager.getManager().getCircuitBreaker("osm");
|
35 |
|
36 |
result.osmVej = (String) breaker.invoke(wrapper);
|
37 |
return result.osmVej;
|
38 |
|
39 |
} catch (Exception e) {
|
40 |
System.out.println( "OSMError: " + e.getClass().getName() +" / "+ e.getMessage() );
|
41 |
}
|
42 |
return null;
|
43 |
}
|
44 |
|
45 |
static class OSMInvocation implements CircuitInvocation {
|
46 |
int postnr;
|
47 |
String vejnavn;
|
48 |
ServiceConfig conf;
|
49 |
|
50 |
public OSMInvocation(ServiceConfig conf, int postnr, String vejnavn) {
|
51 |
this.conf = conf;
|
52 |
this.postnr= postnr;
|
53 |
this.vejnavn = vejnavn;
|
54 |
}
|
55 |
|
56 |
@Override
|
57 |
public String proceed() throws Exception {
|
58 |
//TimingHelper timer = new TimingHelper();
|
59 |
String encVej = URLEncoder.encode(vejnavn, "UTF-8");
|
60 |
|
61 |
|
62 |
String url = conf.nominatimBase + "/search?country=DK&street=" + encVej + "&postalcode=" + postnr + "&format=json&addressdetails=1";
|
63 |
|
64 |
//String url = "http://nominatim.openstreetmap.org/search?country=DK&street=" + encVej + "&format=json&addressdetails=1";
|
65 |
//System.out.println (url);
|
66 |
|
67 |
String json = HttpUtil.getContentString(url, conf.osmTimeout);
|
68 |
//System.out.println(json);
|
69 |
|
70 |
Gson gson = new Gson();
|
71 |
OSMAddress adrList[] = gson.fromJson(json, OSMAddress[].class);
|
72 |
|
73 |
//timer.printElapsed("OSM elapsed");
|
74 |
|
75 |
//System.out.println("Count: " + adrList.length);
|
76 |
if (adrList.length != 1)
|
77 |
return null;
|
78 |
|
79 |
if (adrList[0].address != null) {
|
80 |
return adrList[0].address.road;
|
81 |
}
|
82 |
|
83 |
return null;
|
84 |
}
|
85 |
}
|
86 |
|
87 |
|
88 |
}
|