/[projects]/dao/FuldDaekningWorker/src/main/java/dk/daoas/fulddaekning/osrm/OSRMHelper.java
ViewVC logotype

Diff of /dao/FuldDaekningWorker/src/main/java/dk/daoas/fulddaekning/osrm/OSRMHelper.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2733 by torben, Tue Sep 29 09:58:14 2015 UTC revision 2789 by torben, Thu Dec 3 11:30:27 2015 UTC
# Line 2  package dk.daoas.fulddaekning.osrm; Line 2  package dk.daoas.fulddaekning.osrm;
2    
3  import java.io.IOException;  import java.io.IOException;
4  import java.util.Collection;  import java.util.Collection;
 import java.util.Iterator;  
5  import java.util.logging.Level;  import java.util.logging.Level;
6  import java.util.logging.Logger;  import java.util.logging.Logger;
7    
8    import net.minidev.json.JSONValue;
9    
10  import java.util.ArrayList;  import org.apache.http.HttpEntity;
 import java.util.List;  
 import java.util.concurrent.Future;  
   
 import org.apache.http.HttpHost;  
 import org.apache.http.HttpRequest;  
11  import org.apache.http.HttpResponse;  import org.apache.http.HttpResponse;
12    import org.apache.http.client.ClientProtocolException;
13    import org.apache.http.client.ResponseHandler;
14  import org.apache.http.client.methods.HttpGet;  import org.apache.http.client.methods.HttpGet;
15  import org.apache.http.impl.nio.client.CloseableHttpPipeliningClient;  import org.apache.http.impl.client.CloseableHttpClient;
16  import org.apache.http.impl.nio.client.HttpAsyncClients;  import org.apache.http.impl.client.HttpClients;
17  import org.apache.http.util.EntityUtils;  import org.apache.http.util.EntityUtils;
18    
19  import com.google.gson.Gson;  import com.google.gson.Gson;
# Line 24  import com.google.gson.Gson; Line 21  import com.google.gson.Gson;
21  import dk.daoas.fulddaekning.Adresse;  import dk.daoas.fulddaekning.Adresse;
22  import dk.daoas.fulddaekning.HttpUtil;  import dk.daoas.fulddaekning.HttpUtil;
23    
24    /*
25    import dk.thoerup.osrmbinding.OSRMBinding;
26    import dk.thoerup.osrmbinding.ViarouteResult;
27    */
28    
29  public class OSRMHelper {  public class OSRMHelper {
30            
31            private static final boolean ENABLE_OSRM = false;
32    
33    
34          final static Logger logger = Logger.getLogger( OSRMHelper.class.toString() );          final static Logger logger = Logger.getLogger( OSRMHelper.class.toString() );
35    
36          Gson gson = new Gson();          Gson gson = new Gson();
37    
38            //static OSRMBinding binding = null;
39    
40          final String host = "10.30.2.61";          final String host = "127.0.0.1";
41            //final String host = "10.30.2.103";
42          final int port = 5000;          final int port = 5000;
43          final String base_url = "http://" + host + ":" + port;          final String base_url = "http://" + host + ":" + port;
44    /*
45            private static synchronized void initOsrm() {
46                    if (binding == null) {
47                            binding = new OSRMBinding("/home/openstreetmap/denmark-latest.osrm");
48                    }
49            }
50    */
51    
52          public Adresse getNearestViaTable(Adresse a1, Collection<Adresse> haystack) {          public Adresse getNearestTableHttp(Adresse a1, Collection<Adresse> haystack) {
53    
54                  Adresse bedsteAdresse = null;                  Adresse bedsteAdresse = null;
55    
# Line 53  public class OSRMHelper { Line 66  public class OSRMHelper {
66                  }                  }
67    
68                  try {                  try {
69    
70    
71                          String txtResponse = HttpUtil.getContentString(sb.toString(), 500, "UTF-8");                          String txtResponse = HttpUtil.getContentString(sb.toString(), 500, "UTF-8");
72                          OSRMDistanceTable table = gson.fromJson(txtResponse, OSRMDistanceTable.class);                          //OSRMDistanceTable table = gson.fromJson(txtResponse, OSRMDistanceTable.class);
73                            OSRMDistanceTable table = JSONValue.parse(txtResponse, OSRMDistanceTable.class);
74                          if (table.status != 0) {                          if (table.status != 0) {
75                                  logger.info("OSRM failed with message: " + table.status_message);                                  logger.info("OSRM failed with message: " + table.status_message);
76                                  return null;                                  return null;
77                          }                          }
78    
79                            if ( table.distance_table.length != (hayArray.length + 1) ) {
80                                    logger.log(Level.SEVERE, "Wrong number of results in matrix " + table.distance_table.length);
81                                    System.exit(0);
82                            }
83    
84                          int bedsteTid = Integer.MAX_VALUE;                          int bedsteTid = Integer.MAX_VALUE;
85    
86                          for (int i = 1; i<table.distance_table.length; i++) {                          for (int i = 1; i<table.distance_table[0].length; i++) {
87                                  if (table.distance_table[0][i] < bedsteTid) {                                  if (table.distance_table[0][i] < bedsteTid) {
88                                          bedsteTid = table.distance_table[0][i];                                          bedsteTid = table.distance_table[0][i];
89                                          int idx = i-1;                                          int idx = i-1;
# Line 81  public class OSRMHelper { Line 102  public class OSRMHelper {
102                  return bedsteAdresse;                  return bedsteAdresse;
103          }          }
104    
105          public Adresse getNearestPipeline(Adresse a1, Collection<Adresse> haystack) {          public Adresse getNearestTableHttpExperimental(Adresse a1, Collection<Adresse> haystack) {
106    
107    
108    
                 int bedsteAfstand = Integer.MAX_VALUE;  
109                  Adresse bedsteAdresse = null;                  Adresse bedsteAdresse = null;
110    
111                  Adresse hayArray[] = new Adresse[ haystack.size() ];                  Adresse hayArray[] = new Adresse[ haystack.size() ];
112                  haystack.toArray(hayArray);                  haystack.toArray(hayArray);
113    
114                    StringBuilder sb = new StringBuilder();
115                    sb.append(base_url);
116                    sb.append("/table?src=").append(a1.latitude).append(",").append(a1.longitude);
117    
118                  try (CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining(); ) {                  for(int i = 0; i<hayArray.length; i++) {
119                          httpclient.start();                          Adresse a = hayArray[i];
120                            sb.append("&dst=").append( a.latitude ).append(",").append(a.longitude);
121                    }
122    
123                          HttpHost targetHost = new HttpHost(host, port);                  try {
124    
125                          System.out.println("1>" + targetHost.toString() );                          String txtResponse = HttpUtil.getContentString(sb.toString(), 500, "UTF-8");
                         System.out.println("2>" + targetHost.toURI() );  
126    
127                          List<HttpRequest> requests = new ArrayList<HttpRequest>();                          //OSRMDistanceTable table = gson.fromJson(txtResponse, OSRMDistanceTable.class);
128                            OSRMDistanceTable table = JSONValue.parse(txtResponse, OSRMDistanceTable.class);
129                            if (table.status != 0) {
130                                    logger.info("OSRM failed with message: " + table.status_message);
131                                    return null;
132                            }
133    
134                          String loc1 = a1.latitude + "," + a1.longitude;                          if ( table.distance_table[0].length != hayArray.length  ) {
135                                    logger.log(Level.SEVERE, "Wrong number of results in matrix " + table.distance_table[0].length);
136    
137                          //for (int i=0; i<hayArray.length; i++) {                                  System.out.println("--------------");
138                          for (int i=0; i<2; i++) {                                  System.out.println("URL:");
139                                  Adresse a2 = hayArray[i];                                  System.out.println(sb.toString());
140                                  String loc2 = a2.latitude + "," + a2.longitude;                                  System.out.println("--------------");
141                                    System.out.println("Response:");
142                                    System.out.println(txtResponse);
143    
                                 String uri = "/viaroute?loc=" + loc1 + "&loc=" + loc2 + "&geometry=false&instructions=false&alt=false";  
                                 System.out.println( uri );  
144    
145                                  requests.add( new HttpGet(uri) );                                  System.exit(0);
146                            }
147    
148                            int bedsteTid = Integer.MAX_VALUE;
149    
150                            for (int i = 0; i<table.distance_table[0].length; i++) {
151                                    if (table.distance_table[0][i] < bedsteTid) {
152                                            bedsteTid = table.distance_table[0][i];
153                                            bedsteAdresse = hayArray[i];
154                                    }
155                          }                          }
156    
157    
158                          Future<List<HttpResponse>> future = httpclient.execute(targetHost, requests, null);                  } catch (Exception e) {
159                          List<HttpResponse> responses = future.get();                          logger.log(Level.SEVERE, "Lookup failed", e);
160                            System.out.println( sb.toString() );
161                            System.out.println( a1 );
162                            System.exit(1);                
163                    }
164    
165                          HttpResponse respArr[] = new HttpResponse[ responses.size() ];                  //return gson.fromJson(txtResponse, OSRMResponse.class);
                         responses.toArray( respArr );  
166    
                         for (int i=0; i<respArr.length; i++) {  
                                 String jsonBody = EntityUtils.toString( respArr[i].getEntity() );  
                                 OSRMResponse res = gson.fromJson(jsonBody, OSRMResponse.class);  
167    
                                 if (res.route_summary.total_distance < bedsteAfstand) {  
                                         bedsteAfstand = res.route_summary.total_distance;  
                                         bedsteAdresse = hayArray[i];  
                                 }  
168    
169                    return bedsteAdresse;
170            }
171            
172            
173            
174    /*
175            public Adresse getNearestTableJni(Adresse a1, Collection<Adresse> haystack) {
176                    if (binding == null) {
177                            initOsrm();
178                    }
179    
180                    Adresse bedsteAdresse = null;
181    
182                    Adresse hayArray[] = new Adresse[ haystack.size() ];
183                    haystack.toArray(hayArray);
184    
185                    dk.thoerup.osrmbinding.Geopoint points[] = new dk.thoerup.osrmbinding.Geopoint[ hayArray.length + 1 ];
186                    points[0] = new dk.thoerup.osrmbinding.Geopoint( a1.latitude, a1.longitude);
187    
188    
189                    for(int i = 0; i<hayArray.length; i++) {
190                            Adresse a = hayArray[i];
191                            int idx = i+1;
192                            points[idx] = new dk.thoerup.osrmbinding.Geopoint(a.latitude, a.longitude);
193                    }
194    
195                    try {
196                            float distance_table[][] = binding.table( points );
197                            
198                            if ( distance_table.length != (hayArray.length + 1) ) {
199                                    logger.log(Level.SEVERE, "Wrong number of results in matrix " + distance_table.length);
200                                    System.exit(0);
201                          }                          }
202    
203                            int bedsteTid = Integer.MAX_VALUE;
204    
205                          System.out.println(responses);                          for (int i = 1; i<distance_table.length; i++) {
206                                    if (distance_table[0][i] < bedsteTid) {
207                                            bedsteTid = (int) distance_table[0][i];
208                                            int idx = i-1;
209                                            bedsteAdresse = hayArray[idx];
210                                    }
211                            }
212    
213                  } catch(Exception e) {                  } catch (Exception e) {
214                          logger.log(Level.SEVERE, "Lookup failed", e);                          logger.log(Level.SEVERE, "Lookup failed", e);
215                            System.exit(1);                
216                    }
217    
218                  }                  return bedsteAdresse;
219            }*/
220            
221    
222            public Adresse getNearestMultitargetHttp(Adresse a1, Collection<Adresse> haystack) {
223    
224                  return bedsteAdresse;                  Adresse bedsteAdresse = null;
225          }  
226                    Adresse hayArray[] = new Adresse[ haystack.size() ];
227                    haystack.toArray(hayArray);
228    
229                    StringBuilder sb = new StringBuilder();
230                    sb.append(base_url);
231                    sb.append("/multitarget?loc=").append(a1.latitude).append(",").append(a1.longitude);
232    
233                    for(int i = 0; i<hayArray.length; i++) {
234                            Adresse a = hayArray[i];
235                            sb.append("&loc=").append( a.latitude ).append(",").append(a.longitude);
236                    }
237    
238                    try {
239                            String txtResponse = HttpUtil.getContentString(sb.toString(), 500, "UTF-8");
240                            OSRMMultiTarget table = gson.fromJson(txtResponse, OSRMMultiTarget.class);
241    
242    
243                            double bedsteAfstand = Double.MAX_VALUE;
244    
245                            for (int i = 1; i<table.distances.length; i++) {
246                                    if (table.distances[i].distance < bedsteAfstand) {
247                                            bedsteAfstand = table.distances[i].distance;
248                                            bedsteAdresse = hayArray[i];
249                                    }
250                            }
251    
252                    } catch (Exception e) {
253                            logger.log(Level.SEVERE, "Lookup failed", e);
254                            System.exit(1);                
255                    }
256    
257    
258          /*                  return bedsteAdresse;
259           * Denne virker men table opslaget er 10 gange hurtigere          }
260           *          
261           */          public Adresse getNearestViarouteHttp(Adresse a1, Collection<Adresse> haystack) {
         @Deprecated  
         public Adresse getNearest(Adresse a1, Collection<Adresse> haystack) {  
262                  int bedsteAfstand = Integer.MAX_VALUE;                  int bedsteAfstand = Integer.MAX_VALUE;
263                  Adresse bedsteAdresse = null;                  Adresse bedsteAdresse = null;
264                    
265                    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
266                            
267                            String loc1 = a1.latitude + "," + a1.longitude;
268    
269                  Iterator<Adresse> it = haystack.iterator();                          
270                  while (it.hasNext()) {                          for(Adresse a2: haystack) {
271                          Adresse a2 = it.next();                                  String loc2 = a2.latitude + "," + a2.longitude;
   
                         try {  
                                 OSRMResponse res = getRoute(a1, a2);  
272    
273                                  if (res.status != 0) {                                  String uri = base_url + "/viaroute?loc=" + loc1 + "&loc=" + loc2 + "&geometry=false&instructions=false&alt=false";
274                                    
275                                    HttpGet httpget = new HttpGet(uri);
276                                    
277                                    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
278    
279                            @Override
280                            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
281                                int status = response.getStatusLine().getStatusCode();
282                                
283                                if (status >= 200 && status < 300) {
284                                    HttpEntity entity = response.getEntity();
285                                    return entity != null ? EntityUtils.toString(entity) : null;
286                                } else {
287                                    throw new ClientProtocolException("Unexpected response status: " + status);
288                                }
289                            }
290    
291                        };
292                        String responseBody = httpclient.execute(httpget, responseHandler);
293                        
294                                    OSRMResponse res = gson.fromJson(responseBody, OSRMResponse.class);
295    
296                                    
297                        
298                        if (res.status != 0) {
299                                          System.out.println("OSRM Returned " + res.status + "/" + res.status_message );                                          System.out.println("OSRM Returned " + res.status + "/" + res.status_message );
300                                          continue;                                          continue;
301                                  }                                  }
302    
303                                    if (res.route_summary.total_distance == 0) {
304                                            continue;
305                                    }
306    
307    
308                                  if (res.route_summary.total_distance < bedsteAfstand) {                                  if (res.route_summary.total_distance < bedsteAfstand) {
309                                          bedsteAfstand = res.route_summary.total_distance;                                          bedsteAfstand = res.route_summary.total_distance;
310                                          bedsteAdresse = a2;                                          bedsteAdresse = a2;
311                                  }                                  }
                         } catch (IOException e) {  
                                 System.out.println( e.getMessage() );  
                                 System.exit(1);  
                         }  
312    
313                                    if (bedsteAfstand < 200) { //vejdistance er tæt nok på
314                                            return bedsteAdresse;
315                                    }
316                        
317                            }
318                            
319                    } catch (Exception e) {
320                            logger.log(Level.SEVERE, "Lookup failed", e);
321                  }                  }
322    
323                  return bedsteAdresse;                  return bedsteAdresse;
324          }          }
325    
326          public OSRMResponse getRoute(Adresse a1, Adresse a2) throws IOException {  /*      
327            public Adresse getNearestViarouteJni(Adresse a1, Collection<Adresse> haystack) {
328    
329                    if (binding == null) {
330                            initOsrm();
331                    }
332    
333    
334                  String loc1 = a1.latitude + "," + a1.longitude;                  int bedsteAfstand = Integer.MAX_VALUE;
335                  String loc2 = a2.latitude + "," + a2.longitude;                  Adresse bedsteAdresse = null;
336                    
337                            
338                            for(Adresse a2: haystack) {
339    
340                        ViarouteResult res = binding.viaRoute(a1.latitude, a1.longitude, a2.latitude, a2.longitude);
341    
342                        
343                        if (res.status != 0) {
344                                            System.out.println("OSRM Returned " + res.status  );
345                                            continue;
346                                    }
347    
348                  String params = "loc=" + loc1 + "&loc=" + loc2 + "&geometry=false&instructions=false&alt=false";                                  if (res.totalDistance == 0) {
349                                            continue;
350                                    }
351    
                 String url = base_url + "/viaroute?" + params;  
352    
353                  String txtResponse = HttpUtil.getContentString(url, 500, "UTF-8");                                  if (res.totalDistance < bedsteAfstand) {
354                                            bedsteAfstand = res.totalDistance;
355                                            bedsteAdresse = a2;
356                                    }
357    
358                  return gson.fromJson(txtResponse, OSRMResponse.class);                                  if (bedsteAfstand < 200) { //vejdistance er tæt nok på
359          }                                          return bedsteAdresse;
360                                    }
361                        
362                            }                      
363    
364                    return bedsteAdresse;
365            }*/
366  }  }
367    
368    

Legend:
Removed from v.2733  
changed lines
  Added in v.2789

  ViewVC Help
Powered by ViewVC 1.1.20