1 |
package dk.daoas.adressevedligehold.afstandandenrute;
|
2 |
|
3 |
import java.util.Collection;
|
4 |
import java.util.logging.Level;
|
5 |
|
6 |
import com.google.gson.Gson;
|
7 |
|
8 |
import dk.daoas.adressevedligehold.ServiceConfig;
|
9 |
import dk.daoas.adressevedligehold.beans.Address;
|
10 |
import dk.daoas.adressevedligehold.tasks.TaskLogger;
|
11 |
import dk.daoas.adressevedligehold.util.HttpUtil;
|
12 |
|
13 |
|
14 |
public class OSRMHelper {
|
15 |
|
16 |
|
17 |
private TaskLogger logger = TaskLogger.getInstance();
|
18 |
|
19 |
|
20 |
Gson gson = new Gson();
|
21 |
|
22 |
final static int PORT = 5000;
|
23 |
final String base_url = "http://" + ServiceConfig.getInstance().osrmHost + ":" + PORT;
|
24 |
|
25 |
|
26 |
public Address getNearestTableHttp(Address a1, Collection<Address> haystack) throws Exception {
|
27 |
|
28 |
|
29 |
Address bedsteAddress = null;
|
30 |
|
31 |
Address hayArray[] = new Address[ haystack.size() ];
|
32 |
haystack.toArray(hayArray);
|
33 |
|
34 |
StringBuilder sb = new StringBuilder();
|
35 |
sb.append(base_url);
|
36 |
sb.append("/table?src=").append(a1.latitude).append(",").append(a1.longitude);
|
37 |
|
38 |
for(int i = 0; i<hayArray.length; i++) {
|
39 |
Address a = hayArray[i];
|
40 |
sb.append("&dst=").append( a.latitude ).append(",").append(a.longitude);
|
41 |
}
|
42 |
|
43 |
try {
|
44 |
|
45 |
String txtResponse = HttpUtil.getContentString(sb.toString(), 1000, "UTF-8");
|
46 |
|
47 |
OSRMDistanceTable table = gson.fromJson(txtResponse, OSRMDistanceTable.class);
|
48 |
|
49 |
if (table.status != 200) {
|
50 |
logger.info("OSRM failed with message: " + table.status + " / "+ table.status_message);
|
51 |
return null;
|
52 |
}
|
53 |
|
54 |
if ( table.distance_table[0].length != hayArray.length ) {
|
55 |
logger.log(Level.SEVERE, "Wrong number of results in matrix " + table.distance_table[0].length);
|
56 |
|
57 |
System.out.println("--------------");
|
58 |
System.out.println("URL:");
|
59 |
System.out.println(sb.toString());
|
60 |
System.out.println("--------------");
|
61 |
System.out.println("Response:");
|
62 |
System.out.println(txtResponse);
|
63 |
|
64 |
|
65 |
throw new Exception("Wrong number of results in matrix");
|
66 |
}
|
67 |
|
68 |
int bedsteTid = Integer.MAX_VALUE;
|
69 |
|
70 |
for (int i = 0; i<table.distance_table[0].length; i++) {
|
71 |
if (table.distance_table[0][i] < bedsteTid) {
|
72 |
bedsteTid = table.distance_table[0][i];
|
73 |
bedsteAddress = hayArray[i];
|
74 |
}
|
75 |
}
|
76 |
|
77 |
|
78 |
} catch (Exception e) {
|
79 |
logger.log(Level.SEVERE, "Lookup failed", e);
|
80 |
System.out.println( sb.toString() );
|
81 |
System.out.println( a1 );
|
82 |
throw e; //Re-throw
|
83 |
}
|
84 |
|
85 |
//return gson.fromJson(txtResponse, OSRMResponse.class);
|
86 |
|
87 |
|
88 |
|
89 |
return bedsteAddress;
|
90 |
}
|
91 |
|
92 |
}
|
93 |
|
94 |
|