11package com .osrm .client ;
22
3- import java .io .UnsupportedEncodingException ;
4- import java .net .URLEncoder ;
5- import java .nio .charset .StandardCharsets ;
3+ import com .fasterxml .jackson .databind .ObjectMapper ;
4+
65import java .util .ArrayList ;
76import java .util .List ;
7+ import java .util .Map ;
88import java .util .concurrent .TimeUnit ;
9+
10+ import com .osrm .client .exception .EmptyUrlException ;
11+ import com .osrm .client .exception .OSRMClientException ;
12+ import com .osrm .client .request .CostMatricesRequest ;
13+ import com .osrm .client .request .GeoLocation ;
914import okhttp3 .MediaType ;
1015import okhttp3 .OkHttpClient ;
1116import okhttp3 .OkHttpClient .Builder ;
1419import okhttp3 .Response ;
1520
1621
17- public class OSRMClient {
22+ public class OSRMClient implements CostService {
1823 private final String uri ;
24+ private static final String ENDPOINT_V2_TABLE = "/v2/table/" ;
1925
2026 public OSRMClient (String uri ) throws EmptyUrlException {
21- if (uri != null || !uri .isEmpty ()) {
22- this .uri = uri ;
23- } else {
27+ if (!stringHasValue (uri )) {
2428 throw new EmptyUrlException ("OSRMClient Constructor requires a OSRM http url" );
2529 }
26- }
2730
31+ this .uri = uri ;
32+ }
2833
29- public OSRMDistanceResponse getDistanceMatrix (List <GeoLocation > locations , double speedRate , String country ,
30- String token , String profile ,
31- String startTime ) throws OptimizationDistanceMatrixException {
34+ @ Override
35+ public CostMatrices getCostMatrices (CostMatricesRequest request ) {
3236 Builder requestBuilder = new Builder ();
3337
3438 requestBuilder .readTimeout (900000 , TimeUnit .MILLISECONDS );
@@ -40,73 +44,50 @@ public OSRMDistanceResponse getDistanceMatrix(List<GeoLocation> locations, doubl
4044
4145 List <String > locationsCollection = new ArrayList <>();
4246
43-
44- for (GeoLocation geoloc : locations ) {
45- locationsCollection .add (geoloc .getLatLongString ());
47+ for (GeoLocation geolocation : request .getLocations ()) {
48+ locationsCollection .add (geolocation .getLatLongString ());
4649 }
4750
4851 String paramsString = String .join ("&loc=" , locationsCollection );
4952
50- paramsString += "&speedRate=" + speedRate ;
51- paramsString += "&country=" + country ;
52- paramsString += encodeStartTime (startTime );
53+ paramsString = addParamString (paramsString , "speedRate" , Double .toString (request .getSpeedRate ()));
54+ paramsString = addParamString (paramsString , "country" , request .getCountry ());
55+ paramsString = addParamString (paramsString , "start_time" , request .getStartTime ());
56+ paramsString = addParamString (paramsString , "vehicleSubType" , request .getVehicleSubType ());
57+ paramsString = addParamString (paramsString , "restriction" , request .getRestrictionOption ());
5358
54- RequestBody body = RequestBody . create ( mediaType , "loc=" + paramsString ) ;
59+ final String metricsParam = request . isReturnDistanceMatrix () ? "time,distance" : "time" ;
5560
56- Request request = new Request .Builder ()
57- .url (this .uri + "/table/" + profile )
58- .post (body )
59- .addHeader ("Content-Type" , "application/x-www-form-urlencoded" )
60- .addHeader ("Authorization" , token )
61- .build ();
61+ paramsString = addParamString (paramsString , "metrics" , metricsParam );
6262
63- Response response ;
64- try {
65- response = client .newCall (request ).execute ();
66- if (response .isSuccessful ()) {
67- return OSRMDistanceResponse .fromJSON (response .body ().string ());
68- }
69- } catch (Exception e ) {
70- System .out .print (e .getMessage ());
71- throw new OptimizationDistanceMatrixException ("Error while connecting to OSRM Server" );
63+ for (Map .Entry <String , Object > paramEntry : request .getCustomParameters ().entrySet ()) {
64+ paramsString = addParamString (paramsString , paramEntry .getKey (), paramEntry .getValue ().toString ());
7265 }
7366
74- UnsuccessfulResponse unsuccessfulResponse = this .getUnsuccessfulResponse (response );
75- if (unsuccessfulResponse != null && unsuccessfulResponse .getMessage () != null ) {
76- throw new DistanceMatrixResponseException ("OSRM Error: " + unsuccessfulResponse .getMessage ());
77- }
67+ RequestBody body = RequestBody .create (mediaType , "loc=" + paramsString );
7868
79- throw new DistanceMatrixResponseException ("OSRM Error: " + response );
80- }
69+ Request osrmRequest = new Request .Builder ()
70+ .url (this .uri + ENDPOINT_V2_TABLE + request .getProfile ())
71+ .post (body )
72+ .addHeader ("Content-Type" , "application/x-www-form-urlencoded" )
73+ .addHeader ("Authorization" , request .getToken ())
74+ .build ();
8175
82- private String encodeStartTime (String startTime ) {
83- String paramsString = "" ;
84- if (startTime == null || startTime .isEmpty ()) {
85- return paramsString ;
86- }
8776 try {
88- String encodedStartTime = URLEncoder .encode (startTime , StandardCharsets .UTF_8 .toString ());
89- paramsString += "&start_time=" + encodedStartTime ;
90- } catch (Exception e ){
91- throw new OptimizationDistanceMatrixException ("Error while encoding startTime parameter" );
92- }
93- return paramsString ;
94- }
77+ Response response = client .newCall (osrmRequest ).execute ();
9578
96- private UnsuccessfulResponse getUnsuccessfulResponse (Response response ){
97- try {
98- if (response .body () != null ) {
99- String bodyResponse = response .body ().string ();
100- UnsuccessfulResponse unsuccessfulResponse = UnsuccessfulResponse .fromJSON (bodyResponse );
101- if (unsuccessfulResponse .getMessage () == null ){
102- return new UnsuccessfulResponse (bodyResponse ,String .valueOf (response .code ()),"" );
103- }
104- }
79+ ObjectMapper mapper = new ObjectMapper ();
80+ return mapper .readValue (response .body ().string (), CostMatrices .class );
10581 } catch (Exception e ) {
106- System .out .print ("Error getUnsuccessfulResponse.fromJSON: " + e .getMessage ());
107- }
108- return null ;
82+ throw new OSRMClientException ("Error while connecting to OSRM Server" );
83+ }
10984 }
11085
86+ private String addParamString (String paramString , String key , String value ) {
87+ return stringHasValue (value ) ? paramString .concat ("&" + key + "=" + value ) : paramString ;
88+ }
11189
90+ private boolean stringHasValue (String string ) {
91+ return (string != null ) && (!string .equals ("" ));
92+ }
11293}
0 commit comments