Skip to content

Commit 44d2275

Browse files
Merge pull request #14 from SimpliRoute/FEATURE-DEV423-new_osrm_client
Feature dev423 new osrm client
2 parents bf025d4 + 606d5fc commit 44d2275

16 files changed

+134
-174
lines changed

build.gradle

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ dependencies {
1818
compile 'com.squareup.okhttp3:okhttp:3.12.0'
1919
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
2020
implementation 'com.google.guava:guava:28.1-jre'
21+
implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.5'
22+
23+
compileOnly 'org.projectlombok:lombok:1.18.22'
24+
annotationProcessor 'org.projectlombok:lombok:1.18.22'
2125

2226
testCompile group: 'junit', name: 'junit', version: '4.12'
27+
testImplementation 'org.projectlombok:lombok:1.18.22'
2328
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.osrm.client;
2+
3+
import lombok.Getter;
4+
import lombok.Setter;
5+
6+
@Getter
7+
@Setter
8+
public class CostMatrices {
9+
private CostMatrix timeMatrix;
10+
private CostMatrix distanceMatrix;
11+
}

src/main/java/com/osrm/client/DistanceMatrix.java renamed to src/main/java/com/osrm/client/CostMatrix.java

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
11
package com.osrm.client;
22

3+
import lombok.Getter;
4+
import lombok.Setter;
5+
36
import java.util.ArrayList;
47
import java.util.List;
58

6-
public class DistanceMatrix {
9+
@Getter
10+
@Setter
11+
public class CostMatrix {
712
private int[][] matrix;
813

9-
public DistanceMatrix(int size) {
10-
this.matrix = new int[size][size];
14+
public double getValueAtCoord(int x, int y) {
15+
return this.matrix[x][y];
1116
}
12-
1317
public void setValueAtCoord(int x, int y, int value) {
1418
this.matrix[x][y] = value;
1519
}
1620

17-
public int getValueAtCoord(int x, int y) {
18-
return this.matrix[x][y];
19-
}
20-
2121
public List<List<Float>> asList() {
2222
List<List<Float>> list = new ArrayList<>();
2323
for (int x = 0; x < matrix.length; x++) {
2424
List<Float> row = new ArrayList<>();
2525
for (int y = 0; y < matrix.length; y++) {
26-
Float distance = Float.MAX_VALUE;
26+
float cost = Float.MAX_VALUE;
2727
try {
28-
distance = Double.valueOf(matrix[x][y]).floatValue();
28+
cost = Double.valueOf(matrix[x][y]).floatValue();
2929
} catch (NumberFormatException e) {
3030
e.printStackTrace();
3131
}
32-
row.add(distance);
32+
row.add(cost);
3333
}
3434
list.add(row);
3535
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.osrm.client;
2+
3+
import com.osrm.client.request.CostMatricesRequest;
4+
5+
6+
public interface CostService {
7+
CostMatrices getCostMatrices(CostMatricesRequest request);
8+
}

src/main/java/com/osrm/client/DistanceMatrixResponseException.java

Lines changed: 0 additions & 7 deletions
This file was deleted.

src/main/java/com/osrm/client/DistanceResponse.java

Lines changed: 0 additions & 5 deletions
This file was deleted.

src/main/java/com/osrm/client/DistanceService.java

Lines changed: 0 additions & 7 deletions
This file was deleted.

src/main/java/com/osrm/client/Main.java

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,45 @@
11
package com.osrm.client;
2+
import com.osrm.client.exception.EmptyUrlException;
3+
import com.osrm.client.request.CostMatricesRequest;
4+
import com.osrm.client.request.GeoLocation;
5+
26
import java.util.List;
37
import java.util.ArrayList;
48

59
public class Main {
610
public static void main(String[] args) throws EmptyUrlException {
711

812
try {
9-
OSRMClient client = new OSRMClient("http://localhost:8008");
13+
OSRMClient client = new OSRMClient("http://0.0.0.0:8080");
1014
List<GeoLocation> locations = new ArrayList<>();
1115

12-
GeoLocation geo1 = new GeoLocation(-33.416943, -70.60952);
13-
GeoLocation geo2 = new GeoLocation(-33.416943, -70.60952);
14-
GeoLocation geo3 = new GeoLocation(-33.4445755, -70.6404943);
15-
GeoLocation geo4 = new GeoLocation(-33.4457167, -70.61926449999999);
16+
GeoLocation geo1 = new GeoLocation(42.5434488, 1.4949332);
17+
GeoLocation geo2 = new GeoLocation(42.5434488, 1.395);
1618

1719
locations.add(geo1);
1820
locations.add(geo2);
19-
locations.add(geo3);
20-
locations.add(geo4);
2121

2222
// low fmv
2323
double speedRate = 2;
24-
String country = "CL";
24+
String country = "AD";
2525

2626
// token
27-
String token = "None";
27+
String token = "Token TUTOKEN";
2828

2929
String profile = "car";
3030

31-
OSRMDistanceResponse response = client.getDistanceMatrix(locations, speedRate, country, token, profile,
32-
null);
31+
CostMatricesRequest request = CostMatricesRequest.builder()
32+
.speedRate(speedRate)
33+
.country(country)
34+
.locations(locations)
35+
.token(token)
36+
.profile(profile)
37+
.returnDistanceMatrix(true)
38+
.build();
39+
40+
CostMatrices matrices = client.getCostMatrices(request);
3341

34-
System.out.println(response);
42+
System.out.println(matrices);
3543
}catch (Exception e){
3644
e.printStackTrace();
3745
System.out.println("End with errors.");
Lines changed: 44 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
package 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+
65
import java.util.ArrayList;
76
import java.util.List;
7+
import java.util.Map;
88
import 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;
914
import okhttp3.MediaType;
1015
import okhttp3.OkHttpClient;
1116
import okhttp3.OkHttpClient.Builder;
@@ -14,21 +19,20 @@
1419
import 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
}

src/main/java/com/osrm/client/OSRMDistanceResponse.java

Lines changed: 0 additions & 40 deletions
This file was deleted.

0 commit comments

Comments
 (0)