diff --git a/ors-api/WebContent/WEB-INF/web.xml b/ors-api/WebContent/WEB-INF/web.xml index 9e43a2a521..05fe59ed2f 100644 --- a/ors-api/WebContent/WEB-INF/web.xml +++ b/ors-api/WebContent/WEB-INF/web.xml @@ -1,25 +1,26 @@ - - openrouteservice API - - - CompressionFilter - org.heigit.ors.api.servlet.filters.CompressionFilter - - - CompressionFilter - /* - + + openrouteservice API + + + CompressionFilter + org.heigit.ors.api.servlet.filters.CompressionFilter + + + CompressionFilter + /* + - - StatusCodeHandlerFilter - org.heigit.ors.api.servlet.filters.StatusCodeHandlerFilter - - - StatusCodeHandlerFilter - /* - REQUEST - + + StatusCodeHandlerFilter + org.heigit.ors.api.servlet.filters.StatusCodeHandlerFilter + + + StatusCodeHandlerFilter + /* + REQUEST + diff --git a/ors-api/ors-config.yml b/ors-api/ors-config.yml index 08814bc6d8..a3fab2d418 100644 --- a/ors-api/ors-config.yml +++ b/ors-api/ors-config.yml @@ -9,14 +9,14 @@ # override: classpath:logs/DEBUG_LOGGING.json ors: -### uncomment the following lines to change CORS settings. -# cors: -# allowed_origins: "*" -# allowed_headers: Content-Type, X-Requested-With, accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization -# preflight_max_age: 600 + ### uncomment the following lines to change CORS settings. + #cors: + # allowed_origins: "*" + # allowed_headers: Content-Type, X-Requested-With, accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization + # preflight_max_age: 600 engine: -### use the following line for development setup using test OSM file for Heidelberg -# source_file: ./src/test/files/heidelberg.osm.gz + ### use the following line for development setup using test OSM file for Heidelberg + #source_file: ./src/test/files/heidelberg.osm.gz source_file: ./ors-core/data/osm_file.pbf graphs_root_path: ./ors-core/data/graphs elevation: diff --git a/ors-api/src/main/java/org/heigit/ors/api/Application.java b/ors-api/src/main/java/org/heigit/ors/api/Application.java index 49f9e935eb..1f9076eb83 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/Application.java +++ b/ors-api/src/main/java/org/heigit/ors/api/Application.java @@ -10,8 +10,6 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import java.io.File; - @ServletComponentScan("org.heigit.ors.api.servlet.listeners") @SpringBootApplication public class Application extends SpringBootServletInitializer { diff --git a/ors-api/src/main/java/org/heigit/ors/api/EndpointsProperties.java b/ors-api/src/main/java/org/heigit/ors/api/EndpointsProperties.java index 5ad8a329e7..f8e69c54b3 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/EndpointsProperties.java +++ b/ors-api/src/main/java/org/heigit/ors/api/EndpointsProperties.java @@ -286,13 +286,13 @@ public void setMaximumRangeTime(List profileMaxRangeDistances = new HashMap<>(); + private final Map profileMaxRangeDistances = new HashMap<>(); public Map getProfileMaxRangeDistances() { return profileMaxRangeDistances; } - private Map profileMaxRangeTimes = new HashMap<>(); + private final Map profileMaxRangeTimes = new HashMap<>(); public Map getProfileMaxRangeTimes() { return profileMaxRangeTimes; diff --git a/ors-api/src/main/java/org/heigit/ors/api/ORSEnvironmentPostProcessor.java b/ors-api/src/main/java/org/heigit/ors/api/ORSEnvironmentPostProcessor.java index 69a276ba61..c9fd3276b4 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/ORSEnvironmentPostProcessor.java +++ b/ors-api/src/main/java/org/heigit/ors/api/ORSEnvironmentPostProcessor.java @@ -1,6 +1,5 @@ package org.heigit.ors.api; -import org.apache.log4j.Logger; import org.heigit.ors.util.StringUtility; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; @@ -10,7 +9,6 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.FileSystemResource; -import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; diff --git a/ors-api/src/main/java/org/heigit/ors/api/SystemMessageProperties.java b/ors-api/src/main/java/org/heigit/ors/api/SystemMessageProperties.java index 0ab11c080d..06c3678af6 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/SystemMessageProperties.java +++ b/ors-api/src/main/java/org/heigit/ors/api/SystemMessageProperties.java @@ -10,9 +10,11 @@ @ConfigurationProperties(prefix = "ors") public class SystemMessageProperties { private List messages; + public List getMessages() { return messages; } + public void setMessages(List messages) { this.messages = messages; } diff --git a/ors-api/src/main/java/org/heigit/ors/api/controllers/ExportAPI.java b/ors-api/src/main/java/org/heigit/ors/api/controllers/ExportAPI.java index 44849a604b..36224eb9b2 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/controllers/ExportAPI.java +++ b/ors-api/src/main/java/org/heigit/ors/api/controllers/ExportAPI.java @@ -25,6 +25,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; import org.heigit.ors.api.errors.CommonResponseEntityExceptionHandler; import org.heigit.ors.api.requests.export.ExportRequest; import org.heigit.ors.api.responses.export.json.JsonExportResponse; @@ -39,8 +40,6 @@ import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.*; -import jakarta.servlet.http.HttpServletResponse; - @RestController @Tag(name = "Export Service", description = "Export the base graph for different modes of transport") @RequestMapping("/v2/export") @@ -74,7 +73,7 @@ public String getPostMapping(@RequestBody ExportRequest request) throws MissingP } // Matches any response type that has not been defined - @PostMapping(value="/{profile}/*") + @PostMapping(value = "/{profile}/*") @Operation(hidden = true) public void getInvalidResponseType() throws StatusCodeException { throw new StatusCodeException(HttpServletResponse.SC_NOT_ACCEPTABLE, ExportErrorCodes.UNSUPPORTED_EXPORT_FORMAT, "This response format is not supported"); @@ -84,9 +83,9 @@ public void getInvalidResponseType() throws StatusCodeException { @PostMapping(value = "/{profile}") @Operation( description = """ - Returns a list of points, edges and weights within a given bounding box for a selected profile as JSON. \ - This method does not accept any request body or parameters other than profile, start coordinate, and end coordinate.\ - """, + Returns a list of points, edges and weights within a given bounding box for a selected profile as JSON. \ + This method does not accept any request body or parameters other than profile, start coordinate, and end coordinate.\ + """, summary = "Export Service" ) @ApiResponse( @@ -98,7 +97,7 @@ public void getInvalidResponseType() throws StatusCodeException { ) }) public JsonExportResponse getDefault(@Parameter(description = "Specifies the route profile.", required = true, example = "driving-car") @PathVariable APIEnums.Profile profile, - @Parameter(description = "The request payload", required = true) @RequestBody ExportRequest request) throws StatusCodeException { + @Parameter(description = "The request payload", required = true) @RequestBody ExportRequest request) throws StatusCodeException { return getJsonExport(profile, request); } diff --git a/ors-api/src/main/java/org/heigit/ors/api/controllers/HealthAPI.java b/ors-api/src/main/java/org/heigit/ors/api/controllers/HealthAPI.java index eca5e11421..238601cb6f 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/controllers/HealthAPI.java +++ b/ors-api/src/main/java/org/heigit/ors/api/controllers/HealthAPI.java @@ -37,13 +37,10 @@ public ResponseEntity fetchHealth() { JSONObject jsonResponse = new JSONObject(); HttpStatus status; - if (!RoutingProfileManagerStatus.isReady()) - { + if (!RoutingProfileManagerStatus.isReady()) { jsonResponse.put("status", "not ready"); status = HttpStatus.SERVICE_UNAVAILABLE; - } - else - { + } else { jsonResponse.put("status", "ready"); status = HttpStatus.OK; } diff --git a/ors-api/src/main/java/org/heigit/ors/api/controllers/IsochronesAPI.java b/ors-api/src/main/java/org/heigit/ors/api/controllers/IsochronesAPI.java index 366d5af4ce..bad0b04218 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/controllers/IsochronesAPI.java +++ b/ors-api/src/main/java/org/heigit/ors/api/controllers/IsochronesAPI.java @@ -26,6 +26,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.errors.CommonResponseEntityExceptionHandler; @@ -44,8 +45,6 @@ import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.*; -import jakarta.servlet.http.HttpServletResponse; - @RestController @Tag(name = "Isochrones Service", description = "Obtain areas of reachability from given locations") @RequestMapping("/v2/isochrones") @@ -92,10 +91,10 @@ public void getInvalidResponseType() throws StatusCodeException { @PostMapping(value = "/{profile}", produces = "application/geo+json;charset=UTF-8") @Operation( description = """ - The Isochrone Service supports time and distance analyses for one single or multiple locations. - You may also specify the isochrone interval or provide multiple exact isochrone range values. - This service allows the same range of profile options as the /directions endpoint, - which help you to further customize your request to obtain a more detailed reachability area response.""", + The Isochrone Service supports time and distance analyses for one single or multiple locations. + You may also specify the isochrone interval or provide multiple exact isochrone range values. + This service allows the same range of profile options as the /directions endpoint, + which help you to further customize your request to obtain a more detailed reachability area response.""", summary = "Isochrones Service" ) @ApiResponse( @@ -115,10 +114,10 @@ public GeoJSONIsochronesResponse getDefaultIsochrones( @PostMapping(value = "/{profile}/geojson", produces = "application/geo+json;charset=UTF-8") @Operation( description = """ - The Isochrone Service supports time and distance analyses for one single or multiple locations. - You may also specify the isochrone interval or provide multiple exact isochrone range values. - This service allows the same range of profile options as the /directions endpoint, - which help you to further customize your request to obtain a more detailed reachability area response.""", + The Isochrone Service supports time and distance analyses for one single or multiple locations. + You may also specify the isochrone interval or provide multiple exact isochrone range values. + This service allows the same range of profile options as the /directions endpoint, + which help you to further customize your request to obtain a more detailed reachability area response.""", summary = "Isochrones Service", hidden = true ) diff --git a/ors-api/src/main/java/org/heigit/ors/api/controllers/MatrixAPI.java b/ors-api/src/main/java/org/heigit/ors/api/controllers/MatrixAPI.java index 98e541b264..f3946f5f5c 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/controllers/MatrixAPI.java +++ b/ors-api/src/main/java/org/heigit/ors/api/controllers/MatrixAPI.java @@ -26,6 +26,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.errors.CommonResponseEntityExceptionHandler; @@ -44,8 +45,6 @@ import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.*; -import jakarta.servlet.http.HttpServletResponse; - @RestController @Tag(name = "Matrix Service", description = "Obtain one-to-many, many-to-one and many-to-many matrices for time and distance") @RequestMapping("/v2/matrix") @@ -93,9 +92,9 @@ public void getInvalidResponseType() throws StatusCodeException { @PostMapping(value = "/{profile}", produces = {"application/json;charset=UTF-8"}) @Operation( description = """ - Returns duration or distance matrix for multiple source and destination points. - By default a square duration matrix is returned where every point in locations is paired with each other. The result is null if a value can’t be determined.\ - """, + Returns duration or distance matrix for multiple source and destination points. + By default a square duration matrix is returned where every point in locations is paired with each other. The result is null if a value can’t be determined.\ + """, summary = "Matrix Service" ) @ApiResponse( diff --git a/ors-api/src/main/java/org/heigit/ors/api/controllers/RoutingAPI.java b/ors-api/src/main/java/org/heigit/ors/api/controllers/RoutingAPI.java index 9cc5556895..279bdecd8d 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/controllers/RoutingAPI.java +++ b/ors-api/src/main/java/org/heigit/ors/api/controllers/RoutingAPI.java @@ -25,6 +25,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletResponse; import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.errors.CommonResponseEntityExceptionHandler; @@ -46,8 +47,6 @@ import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.*; -import jakarta.servlet.http.HttpServletResponse; - @RestController @Tag(name = "Directions Service", description = "Get directions for different modes of transport") @RequestMapping("/v2/directions") @@ -97,9 +96,9 @@ public void getInvalidResponseType() throws StatusCodeException { @Operation( method = "GET", description = """ - Get a basic route between two points with the profile provided. Returned response is in GeoJSON format. \ - This method does not accept any request body or parameters other than profile, start coordinate, and end coordinate.\ - """, summary = "Directions Service") + Get a basic route between two points with the profile provided. Returned response is in GeoJSON format. \ + This method does not accept any request body or parameters other than profile, start coordinate, and end coordinate.\ + """, summary = "Directions Service") @ApiResponse( responseCode = "200", description = "Standard response for successfully processed requests. Returns GeoJSON. The decoded values of the extra information can be found [here](https://GIScience.github.io/openrouteservice/documentation/extra-info/Extra-Info.html).", diff --git a/ors-api/src/main/java/org/heigit/ors/api/controllers/StatusAPI.java b/ors-api/src/main/java/org/heigit/ors/api/controllers/StatusAPI.java index cd48a4b393..f4287f8ffc 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/controllers/StatusAPI.java +++ b/ors-api/src/main/java/org/heigit/ors/api/controllers/StatusAPI.java @@ -17,6 +17,7 @@ import com.graphhopper.storage.StorableProperties; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.util.AppConfigMigration; import org.heigit.ors.api.util.AppInfo; @@ -34,7 +35,6 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.HttpServerErrorException; -import jakarta.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; @@ -49,6 +49,7 @@ public class StatusAPI { public StatusAPI(EndpointsProperties endpointsProperties) { this.endpointsProperties = AppConfigMigration.overrideEndpointsProperties(endpointsProperties); } + @GetMapping public ResponseEntity fetchHealth(HttpServletRequest request) throws Exception { HttpHeaders headers = new HttpHeaders(); diff --git a/ors-api/src/main/java/org/heigit/ors/api/converters/BBoxSerializer.java b/ors-api/src/main/java/org/heigit/ors/api/converters/BBoxSerializer.java index 7d88ea4cbe..3531fceac3 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/converters/BBoxSerializer.java +++ b/ors-api/src/main/java/org/heigit/ors/api/converters/BBoxSerializer.java @@ -41,9 +41,9 @@ public void serialize(double[][] coordinates, JsonGenerator jsonGenerator, Seria formattedCoords[1][0] = FormatUtility.roundToDecimals(coordinates[1][0], COORDINATE_PRECISION); formattedCoords[1][1] = FormatUtility.roundToDecimals(coordinates[1][1], COORDINATE_PRECISION); - if(coordinates[0].length == 3) + if (coordinates[0].length == 3) formattedCoords[0][2] = FormatUtility.roundToDecimals(coordinates[0][2], COORDINATE_PRECISION); - if(coordinates[1].length == 3) + if (coordinates[1].length == 3) formattedCoords[1][2] = FormatUtility.roundToDecimals(coordinates[0][2], COORDINATE_PRECISION); jsonGenerator.writeStartArray(); diff --git a/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListDeserializer.java b/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListDeserializer.java index b0c08f9241..042db5f491 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListDeserializer.java +++ b/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListDeserializer.java @@ -19,8 +19,8 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.api.requests.common.CoordinateListWrapper; +import org.locationtech.jts.geom.Coordinate; import java.io.IOException; import java.util.ArrayList; @@ -38,10 +38,10 @@ public CoordinateListWrapper deserialize(JsonParser jsonParser, DeserializationC JsonNode node = jsonParser.getCodec().readTree(jsonParser); List convertedCoords = new ArrayList<>(); - if(node.isArray()) { + if (node.isArray()) { Iterator coordinates = node.iterator(); JsonNode coord; - while(coordinates.hasNext() && ( coord = coordinates.next()) != null) { + while (coordinates.hasNext() && (coord = coordinates.next()) != null) { convertedCoords.add(new Coordinate(coord.get(0).asDouble(), coord.get(1).asDouble())); } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListSerializer.java b/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListSerializer.java index 56047a93f3..bc4ff2d3c2 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListSerializer.java +++ b/ors-api/src/main/java/org/heigit/ors/api/converters/CoordinateListSerializer.java @@ -18,8 +18,8 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.api.requests.common.CoordinateListWrapper; +import org.locationtech.jts.geom.Coordinate; import java.io.IOException; @@ -36,7 +36,7 @@ public CoordinateListSerializer(Class listWrapper) { public void serialize(CoordinateListWrapper listWrapper, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException { jsonGenerator.writeStartArray(); - for(Coordinate coord : listWrapper.getCoordinates()) { + for (Coordinate coord : listWrapper.getCoordinates()) { jsonGenerator.writeStartArray(); jsonGenerator.writeNumber(coord.x); diff --git a/ors-api/src/main/java/org/heigit/ors/api/errors/CommonResponseEntityExceptionHandler.java b/ors-api/src/main/java/org/heigit/ors/api/errors/CommonResponseEntityExceptionHandler.java index d1deeac9fb..62ab7c79fc 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/errors/CommonResponseEntityExceptionHandler.java +++ b/ors-api/src/main/java/org/heigit/ors/api/errors/CommonResponseEntityExceptionHandler.java @@ -17,11 +17,11 @@ import com.fasterxml.jackson.databind.exc.ValueInstantiationException; import org.apache.log4j.Logger; +import org.heigit.ors.api.util.AppInfo; import org.heigit.ors.exceptions.ParameterValueException; import org.heigit.ors.exceptions.StatusCodeException; import org.heigit.ors.exceptions.UnknownParameterException; import org.heigit.ors.isochrones.IsochronesErrorCodes; -import org.heigit.ors.api.util.AppInfo; import org.heigit.ors.util.DebugUtility; import org.json.simple.JSONObject; import org.springframework.http.HttpHeaders; diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/common/CoordinateListWrapper.java b/ors-api/src/main/java/org/heigit/ors/api/requests/common/CoordinateListWrapper.java index 0393b51f46..78474f7991 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/common/CoordinateListWrapper.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/common/CoordinateListWrapper.java @@ -17,10 +17,10 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.locationtech.jts.geom.Coordinate; import io.swagger.v3.oas.annotations.media.Schema; import org.heigit.ors.api.converters.CoordinateListDeserializer; import org.heigit.ors.exceptions.ParameterValueException; +import org.locationtech.jts.geom.Coordinate; import java.util.ArrayList; import java.util.List; @@ -56,7 +56,7 @@ public CoordinateListWrapper(List coordinates) throws ParameterValue via.add(coordinates.get(i)); } - end = coordinates.get(coordinates.size()-1); + end = coordinates.get(coordinates.size() - 1); } public CoordinateListWrapper(double[][] coordinates) throws ParameterValueException { @@ -106,7 +106,7 @@ public List> getCoordinatesList() { startCoords.add(start.x); startCoords.add(start.y); coordinates.add(startCoords); - for(Coordinate c : via) { + for (Coordinate c : via) { List viaCoords = new ArrayList<>(); viaCoords.add(c.x); viaCoords.add(c.y); diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/common/RequestOptions.java b/ors-api/src/main/java/org/heigit/ors/api/requests/common/RequestOptions.java index 050b42a435..1973f0b493 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/common/RequestOptions.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/common/RequestOptions.java @@ -32,7 +32,7 @@ public class RequestOptions implements RouteRequestParameterNames { @Schema(name = PARAM_AVOID_FEATURES, description = "List of features to avoid. ", - extensions = { @Extension(name = "itemRestrictions", properties = { + extensions = {@Extension(name = "itemRestrictions", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "itemsWhen", value = "{\"driving-*\":[\"highways\",\"tollways\",\"ferries\"],\"cycling-*\":[\"ferries\",\"steps\",\"fords\"],\"foot-*\":[\"ferries\",\"fords\",\"steps\"],\"wheelchair\":[\"ferries\",\"steps\"]}", parseValue = true)} )}, @@ -43,7 +43,7 @@ public class RequestOptions implements RouteRequestParameterNames { private boolean hasAvoidFeatures = false; @Schema(name = PARAM_AVOID_BORDERS, description = "`all` for no border crossing. `controlled` to cross open borders but avoid controlled ones. Only for `driving-*` profiles. ", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-*")} )}, @@ -58,7 +58,7 @@ public class RequestOptions implements RouteRequestParameterNames { `[ 11, 193 ]` would exclude Austria and Switzerland. List of countries and application examples can be found [here](https://GIScience.github.io/openrouteservice/documentation/routing-options/Country-List.html). \ Also, ISO standard country codes cna be used in place of the numerical ids, for example, DE or DEU for Germany. \ """, - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-*")} )}, @@ -69,7 +69,7 @@ public class RequestOptions implements RouteRequestParameterNames { private boolean hasAvoidCountries = false; @Schema(name = PARAM_VEHICLE_TYPE, description = "(for profile=driving-hgv only): hgv,bus,agricultural,delivery,forestry and goods. It is needed for vehicle restrictions to work. ", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-hgv")} )}, @@ -80,7 +80,7 @@ public class RequestOptions implements RouteRequestParameterNames { private boolean hasVehicleType = false; @Schema(name = PARAM_PROFILE_PARAMS, description = " Specifies additional matrix parameters.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "valueNot", value = "driving-car")} )}) diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/export/ExportRequest.java b/ors-api/src/main/java/org/heigit/ors/api/requests/export/ExportRequest.java index 01832a9571..399a9c5c37 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/export/ExportRequest.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/export/ExportRequest.java @@ -20,27 +20,27 @@ public class ExportRequest extends APIRequest { public static final String PARAM_DEBUG = "debug"; - @Schema(name= PARAM_ID, description = "Arbitrary identification string of the request reflected in the meta information.", + @Schema(name = PARAM_ID, description = "Arbitrary identification string of the request reflected in the meta information.", example = "export_request") @JsonProperty(PARAM_ID) private String id; @JsonIgnore private boolean hasId = false; - @Schema(name= PARAM_PROFILE, hidden = true) + @Schema(name = PARAM_PROFILE, hidden = true) private APIEnums.Profile profile; - @Schema(name= PARAM_BBOX, description = "The bounding box to use for the request as an array of `longitude/latitude` pairs", + @Schema(name = PARAM_BBOX, description = "The bounding box to use for the request as an array of `longitude/latitude` pairs", example = "[[8.681495,49.41461],[8.686507,49.41943]]", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty(PARAM_BBOX) private List> bbox; //apparently, this has to be a non-primitive type… - @Schema(name= PARAM_FORMAT,hidden = true) + @Schema(name = PARAM_FORMAT, hidden = true) @JsonProperty(PARAM_FORMAT) private APIEnums.ExportResponseType responseType = APIEnums.ExportResponseType.JSON; - @Schema(name= PARAM_DEBUG,hidden = true) + @Schema(name = PARAM_DEBUG, hidden = true) @JsonProperty(PARAM_DEBUG) private boolean debug; @@ -66,11 +66,11 @@ public boolean debug() { return debug; } - public List> getBbox () { + public List> getBbox() { return bbox; } - public void setBbox(List> bbox ) { + public void setBbox(List> bbox) { this.bbox = bbox; } diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/isochrones/IsochronesRequest.java b/ors-api/src/main/java/org/heigit/ors/api/requests/isochrones/IsochronesRequest.java index 591430ee14..908b0f7449 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/isochrones/IsochronesRequest.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/isochrones/IsochronesRequest.java @@ -53,7 +53,7 @@ public class IsochronesRequest extends APIRequest { public static final String PARAM_SMOOTHING = "smoothing"; public static final String PARAM_TIME = "time"; - @Schema(name= PARAM_LOCATIONS, description = "The locations to use for the route as an array of `longitude/latitude` pairs in WGS 84 (EPSG:4326)", + @Schema(name = PARAM_LOCATIONS, description = "The locations to use for the route as an array of `longitude/latitude` pairs in WGS 84 (EPSG:4326)", example = "[[8.681495,49.41461],[8.686507,49.41943]]", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty(PARAM_LOCATIONS) @@ -61,14 +61,14 @@ public class IsochronesRequest extends APIRequest { @JsonIgnore private boolean hasLocations = false; - @Schema(name= PARAM_LOCATION_TYPE, description = "`start` treats the location(s) as starting point, `destination` as goal.", + @Schema(name = PARAM_LOCATION_TYPE, description = "`start` treats the location(s) as starting point, `destination` as goal.", defaultValue = "start") @JsonProperty(value = PARAM_LOCATION_TYPE) private IsochronesRequestEnums.LocationType locationType; @JsonIgnore private boolean hasLocationType = false; - @Schema(name= PARAM_RANGE, description = """ + @Schema(name = PARAM_RANGE, description = """ Maximum range value of the analysis in **seconds** for time and **metres** for distance.\ Alternatively a comma separated list of specific range values. Ranges will be the same for all locations.\ """, @@ -79,7 +79,7 @@ public class IsochronesRequest extends APIRequest { @JsonIgnore private boolean hasRange = false; - @Schema(name= PARAM_RANGE_TYPE, + @Schema(name = PARAM_RANGE_TYPE, description = "Specifies the isochrones reachability type.", defaultValue = "time") @JsonProperty(value = PARAM_RANGE_TYPE, defaultValue = "time") private IsochronesRequestEnums.RangeType rangeType; @@ -87,12 +87,12 @@ public class IsochronesRequest extends APIRequest { private boolean hasRangeType = false; // unit only valid for range_type distance, will be ignored for range_time time - @Schema(name= PARAM_RANGE_UNITS, + @Schema(name = PARAM_RANGE_UNITS, description = """ Specifies the distance units only if `range_type` is set to distance. Default: m. \ """, - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "range_type"), @ExtensionProperty(name = "value", value = "distance")} )}, @@ -102,7 +102,7 @@ public class IsochronesRequest extends APIRequest { @JsonIgnore private boolean hasRangeUnits = false; - @Schema(name= PARAM_OPTIONS, + @Schema(name = PARAM_OPTIONS, description = "Additional options for the isochrones request", example = "{\"avoid_borders\":\"all\"}") @JsonProperty(PARAM_OPTIONS) @@ -113,12 +113,12 @@ public class IsochronesRequest extends APIRequest { @Schema(hidden = true) private APIEnums.RouteResponseType responseType = APIEnums.RouteResponseType.GEOJSON; - @Schema(name= PARAM_AREA_UNITS, + @Schema(name = PARAM_AREA_UNITS, description = """ Specifies the area unit. Default: m. \ """, - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "attributes"), @ExtensionProperty(name = "value", value = "area")} )}, @@ -128,21 +128,21 @@ public class IsochronesRequest extends APIRequest { @JsonIgnore private boolean hasAreaUnits = false; - @Schema(name= PARAM_INTERSECTIONS, + @Schema(name = PARAM_INTERSECTIONS, description = "Specifies whether to return intersecting polygons. ", defaultValue = "false") @JsonProperty(value = PARAM_INTERSECTIONS) private boolean intersections; @JsonIgnore private boolean hasIntersections = false; - @Schema(name= PARAM_ATTRIBUTES, description = "List of isochrones attributes", + @Schema(name = PARAM_ATTRIBUTES, description = "List of isochrones attributes", example = "[\"area\"]") @JsonProperty(PARAM_ATTRIBUTES) private IsochronesRequestEnums.Attributes[] attributes; @JsonIgnore private boolean hasAttributes = false; - @Schema(name= PARAM_INTERVAL, description = """ + @Schema(name = PARAM_INTERVAL, description = """ Interval of isochrones or equidistants. This is only used if a single range value is given. \ Value in **seconds** for time and **meters** for distance.\ """, @@ -153,7 +153,7 @@ public class IsochronesRequest extends APIRequest { @JsonIgnore private boolean hasInterval = false; - @Schema(name= PARAM_SMOOTHING, + @Schema(name = PARAM_SMOOTHING, description = """ Applies a level of generalisation to the isochrone polygons generated as a `smoothing_factor` between `0` and `100.0`. Generalisation is produced by determining a maximum length of a connecting line between two points found on the outside of a containing polygon. @@ -168,7 +168,7 @@ public class IsochronesRequest extends APIRequest { @JsonIgnore private boolean hasSmoothing = false; - @Schema(name= PARAM_TIME, description = "Departure date and time provided in local time zone", + @Schema(name = PARAM_TIME, description = "Departure date and time provided in local time zone", example = "2020-01-31T12:45:00", hidden = true) @JsonProperty(PARAM_TIME) private LocalDateTime time; diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/matrix/MatrixRequest.java b/ors-api/src/main/java/org/heigit/ors/api/requests/matrix/MatrixRequest.java index 324be8b1ff..cb00853384 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/matrix/MatrixRequest.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/matrix/MatrixRequest.java @@ -90,7 +90,7 @@ public class MatrixRequest extends APIRequest { Specifies the distance unit. Default: m.\ """, - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "metrics"), @ExtensionProperty(name = "value", value = "distance")} )}, diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParams.java b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParams.java index c56184c1c2..2ed243785b 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParams.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParams.java @@ -40,8 +40,8 @@ public class RequestProfileParams { @JsonIgnore private boolean hasRestrictions = false; - @Schema(name= PARAM_SURFACE_QUALITY_KNOWN, description = "Specifies whether to enforce that only ways with known information on surface quality be taken into account - default false", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_SURFACE_QUALITY_KNOWN, description = "Specifies whether to enforce that only ways with known information on surface quality be taken into account - default false", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -51,8 +51,8 @@ public class RequestProfileParams { @JsonIgnore private boolean hasSurfaceQualityKnown = false; - @Schema(name= PARAM_ALLOW_UNSUITABLE, description = "Specifies if ways that might not be suitable (e.g. unknown pedestrian usage) should be included in finding routes - default false", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_ALLOW_UNSUITABLE, description = "Specifies if ways that might not be suitable (e.g. unknown pedestrian usage) should be included in finding routes - default false", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -80,14 +80,18 @@ public void setRestrictions(RequestProfileParamsRestrictions restrictions) { hasRestrictions = true; } - public boolean getSurfaceQualityKnown() { return surfaceQualityKnown; } + public boolean getSurfaceQualityKnown() { + return surfaceQualityKnown; + } public void setSurfaceQualityKnown(boolean surfaceQualityKnown) { this.surfaceQualityKnown = surfaceQualityKnown; hasSurfaceQualityKnown = true; } - public boolean getAllowUnsuitable() { return allowUnsuitable; } + public boolean getAllowUnsuitable() { + return allowUnsuitable; + } public void setAllowUnsuitable(boolean allowUnsuitable) { this.allowUnsuitable = allowUnsuitable; @@ -102,7 +106,11 @@ public boolean hasRestrictions() { return hasRestrictions; } - public boolean hasAllowUnsuitable() { return hasAllowUnsuitable; } + public boolean hasAllowUnsuitable() { + return hasAllowUnsuitable; + } - public boolean hasSurfaceQualityKnown() { return hasSurfaceQualityKnown; } + public boolean hasSurfaceQualityKnown() { + return hasSurfaceQualityKnown; + } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsRestrictions.java b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsRestrictions.java index 9a60840dcc..c1ae283224 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsRestrictions.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsRestrictions.java @@ -42,8 +42,8 @@ public class RequestProfileParamsRestrictions { public static final String PARAM_MAX_INCLINE = "maximum_incline"; public static final String PARAM_MIN_WIDTH = "minimum_width"; - @Schema(name= PARAM_LENGTH, description = "Length restriction in metres.", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_LENGTH, description = "Length restriction in metres.", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-hgv")} )}, example = "8.4") @@ -51,8 +51,8 @@ public class RequestProfileParamsRestrictions { private Float length; private boolean hasLength = false; - @Schema(name= PARAM_WIDTH, description = "Width restriction in metres.", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_WIDTH, description = "Width restriction in metres.", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-hgv")} )}, example = "5.6") @@ -61,8 +61,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasWidth = false; - @Schema(name= PARAM_HEIGHT, description = "Height restriction in metres. ", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_HEIGHT, description = "Height restriction in metres. ", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-hgv")} )}, example = "4.2") @@ -71,8 +71,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasHeight = false; - @Schema(name= PARAM_AXLE_LOAD, description = "Axleload restriction in tons.", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_AXLE_LOAD, description = "Axleload restriction in tons.", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-hgv")} )}, example = "50") @@ -81,8 +81,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasAxleLoad = false; - @Schema(name= PARAM_WEIGHT, description = "Weight restriction in tons. ", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_WEIGHT, description = "Weight restriction in tons. ", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-hgv")} )}, example = "40") @@ -91,8 +91,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasWeight = false; - @Schema(name= PARAM_HAZMAT, description = "Specifies whether to use appropriate routing for delivering hazardous goods and avoiding water protected areas. Default is `false`. ", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_HAZMAT, description = "Specifies whether to use appropriate routing for delivering hazardous goods and avoiding water protected areas. Default is `false`. ", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "driving-hgv")} )}, @@ -102,8 +102,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasHazardousMaterial = false; - @Schema(name= PARAM_SURFACE_TYPE, description = "Specifies the minimum surface type. Default is `sett`. ", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_SURFACE_TYPE, description = "Specifies the minimum surface type. Default is `sett`. ", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -113,8 +113,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasSurfaceType = false; - @Schema(name= PARAM_TRACK_TYPE, description = "Specifies the minimum grade of the route. Default is `grade1`. ", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_TRACK_TYPE, description = "Specifies the minimum grade of the route. Default is `grade1`. ", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -124,8 +124,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasTrackType = false; - @Schema(name= PARAM_SMOOTHNESS_TYPE, description = "Specifies the minimum smoothness of the route. Default is `good`.", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_SMOOTHNESS_TYPE, description = "Specifies the minimum smoothness of the route. Default is `good`.", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -135,8 +135,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasSmoothnessType = false; - @Schema(name= PARAM_MAXIMUM_SLOPED_KERB, description = "Specifies the maximum height of the sloped curb in metres. Values are `0.03`, `0.06` (default), `0.1`.", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_MAXIMUM_SLOPED_KERB, description = "Specifies the maximum height of the sloped curb in metres. Values are `0.03`, `0.06` (default), `0.1`.", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -146,8 +146,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasMaxSlopedKerb = false; - @Schema(name= PARAM_MAX_INCLINE, description = "Specifies the maximum incline as a percentage. `3`, `6` (default), `10`, `15.", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_MAX_INCLINE, description = "Specifies the maximum incline as a percentage. `3`, `6` (default), `10`, `15.", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -157,8 +157,8 @@ public class RequestProfileParamsRestrictions { @JsonIgnore private boolean hasMaxIncline = false; - @Schema(name= PARAM_MIN_WIDTH, description = "Specifies the minimum width of the footway in metres.", - extensions = { @Extension(name = "validWhen", properties = { + @Schema(name = PARAM_MIN_WIDTH, description = "Specifies the minimum width of the footway in metres.", + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "wheelchair")} )}, @@ -327,29 +327,29 @@ public boolean hasMinWidth() { @JsonIgnore public List getRestrictionsThatAreSet() { List setRestrictions = new ArrayList<>(); - if(hasLength) + if (hasLength) setRestrictions.add(PARAM_LENGTH); - if(hasWidth) + if (hasWidth) setRestrictions.add(PARAM_WIDTH); - if(hasHeight) + if (hasHeight) setRestrictions.add(PARAM_HEIGHT); - if(hasAxleLoad) + if (hasAxleLoad) setRestrictions.add(PARAM_AXLE_LOAD); - if(hasWeight) + if (hasWeight) setRestrictions.add(PARAM_WEIGHT); - if(hasHazardousMaterial) + if (hasHazardousMaterial) setRestrictions.add(PARAM_HAZMAT); - if(hasSurfaceType) + if (hasSurfaceType) setRestrictions.add(PARAM_SURFACE_TYPE); - if(hasTrackType) + if (hasTrackType) setRestrictions.add(PARAM_TRACK_TYPE); - if(hasSmoothnessType) + if (hasSmoothnessType) setRestrictions.add(PARAM_SMOOTHNESS_TYPE); - if(hasMaxSlopedKerb) + if (hasMaxSlopedKerb) setRestrictions.add(PARAM_MAXIMUM_SLOPED_KERB); - if(hasMaxIncline) + if (hasMaxIncline) setRestrictions.add(PARAM_MAX_INCLINE); - if(hasMinWidth) + if (hasMinWidth) setRestrictions.add(PARAM_MIN_WIDTH); return setRestrictions; } diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsWeightings.java b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsWeightings.java index 1ba7afdb72..1af1ee36c3 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsWeightings.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RequestProfileParamsWeightings.java @@ -32,11 +32,11 @@ public class RequestProfileParamsWeightings { private static final String PARAM_CSV_COLUMN = "csv_column"; public static final String PARAM_SHADOW_INDEX = "shadow"; - @Schema(name= PARAM_STEEPNESS_DIFFICULTY, description = """ + @Schema(name = PARAM_STEEPNESS_DIFFICULTY, description = """ Specifies the fitness level for `cycling-*` profiles. level: 0 = Novice, 1 = Moderate, 2 = Amateur, 3 = Pro. The prefered gradient increases with level.""", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "cycling-*")} )}, example = "2") @@ -45,11 +45,11 @@ public class RequestProfileParamsWeightings { @JsonIgnore private boolean hasSteepnessDifficulty = false; - @Schema(name= PARAM_GREEN_INDEX, description = """ + @Schema(name = PARAM_GREEN_INDEX, description = """ Specifies the Green factor for `foot-*` profiles. factor: Multiplication factor range from 0 to 1. 0 is the green routing base factor without multiplying it by the manual factor and is already different from normal routing. 1 will prefer ways through green areas over a shorter route.""", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "foot-*")} )}, example = "0.4") @@ -58,11 +58,11 @@ public class RequestProfileParamsWeightings { @JsonIgnore private boolean hasGreenIndex = false; - @Schema(name= PARAM_QUIETNESS, description = """ + @Schema(name = PARAM_QUIETNESS, description = """ Specifies the Quiet factor for foot-* profiles. factor: Multiplication factor range from 0 to 1. 0 is the quiet routing base factor without multiplying it by the manual factor and is already different from normal routing. 1 will prefer quiet ways over a shorter route.""", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "foot-*")} )}, example = "0.8") @@ -81,11 +81,11 @@ public class RequestProfileParamsWeightings { @JsonIgnore private boolean hasCsv = false; - @Schema(name= PARAM_SHADOW_INDEX, description = """ + @Schema(name = PARAM_SHADOW_INDEX, description = """ Specifies the shadow factor for `foot-*` profiles. factor: Multiplication factor range from 0 to 1. 0 is the shadow routing base factor without multiplying it by the manual factor and is already different from normal routing. 1 will prefer ways through shadow areas over a shorter route.""", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "profile"), @ExtensionProperty(name = "value", value = "foot-*")} )}, example = "0.4") @@ -121,14 +121,18 @@ public void setQuietIndex(Float quiteIndex) { hasQuietIndex = true; } - public Float getCsvFactor() {return csvFactor; } + public Float getCsvFactor() { + return csvFactor; + } public void setCsvFactor(Float csvFactor) { this.csvFactor = csvFactor; hasCsv = true; } - public String getCsvColumn() { return csvColumn; } + public String getCsvColumn() { + return csvColumn; + } public void setCsvColumn(String csvColumnName) { this.csvColumn = csvColumnName; diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutes.java b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutes.java index 8e3427979a..ee6f4dcc30 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutes.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutes.java @@ -27,19 +27,19 @@ public class RouteRequestAlternativeRoutes { public static final String PARAM_WEIGHT_FACTOR = "weight_factor"; public static final String PARAM_SHARE_FACTOR = "share_factor"; - @Schema(name= PARAM_TARGET_COUNT, description = "Target number of alternative routes to compute. Service returns up to this number of routes that fulfill the share-factor and weight-factor constraints.", example = "2") + @Schema(name = PARAM_TARGET_COUNT, description = "Target number of alternative routes to compute. Service returns up to this number of routes that fulfill the share-factor and weight-factor constraints.", example = "2") @JsonProperty(PARAM_TARGET_COUNT) private Integer targetCount; @JsonIgnore private boolean hasTargetCount = false; - @Schema(name= PARAM_WEIGHT_FACTOR, description = "Maximum factor by which route weight may diverge from the optimal route. The default value of 1.4 means alternatives can be up to 1.4 times longer (costly) than the optimal route.", example = "1.4") + @Schema(name = PARAM_WEIGHT_FACTOR, description = "Maximum factor by which route weight may diverge from the optimal route. The default value of 1.4 means alternatives can be up to 1.4 times longer (costly) than the optimal route.", example = "1.4") @JsonProperty(PARAM_WEIGHT_FACTOR) private Double weightFactor; @JsonIgnore private boolean hasWeightFactor = false; - @Schema(name= PARAM_SHARE_FACTOR, description = "Maximum fraction of the route that alternatives may share with the optimal route. The default value of 0.6 means alternatives can share up to 60% of path segments with the optimal route.", example = "0.6") + @Schema(name = PARAM_SHARE_FACTOR, description = "Maximum fraction of the route that alternatives may share with the optimal route. The default value of 0.6 means alternatives can share up to 60% of path segments with the optimal route.", example = "0.6") @JsonProperty(PARAM_SHARE_FACTOR) private Double shareFactor; @JsonIgnore diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestOptions.java b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestOptions.java index 2cba70cead..05fd5694f3 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestOptions.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestOptions.java @@ -26,7 +26,7 @@ public class RouteRequestOptions extends RequestOptions { public static final String PARAM_ROUND_TRIP_OPTIONS = "round_trip"; - @Schema(name= PARAM_ROUND_TRIP_OPTIONS, description = "Options to be applied on round trip routes.", + @Schema(name = PARAM_ROUND_TRIP_OPTIONS, description = "Options to be applied on round trip routes.", example = "{\"length\":10000,\"points\":5}") @JsonProperty(PARAM_ROUND_TRIP_OPTIONS) private RouteRequestRoundTripOptions roundTripOptions; diff --git a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptions.java b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptions.java index f7fdd226db..50dbf3094f 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptions.java +++ b/ors-api/src/main/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptions.java @@ -27,21 +27,21 @@ public class RouteRequestRoundTripOptions { public static final String PARAM_POINTS = "points"; public static final String PARAM_SEED = "seed"; - @Schema(name= PARAM_LENGTH, description = "The target length of the route in `m` (note that this is a preferred value, but results may be different).", + @Schema(name = PARAM_LENGTH, description = "The target length of the route in `m` (note that this is a preferred value, but results may be different).", example = "10000") @JsonProperty(PARAM_LENGTH) private Float length; @JsonIgnore private boolean hasLength = false; - @Schema(name= PARAM_POINTS, description = "The number of points to use on the route. Larger values create more circular routes.", + @Schema(name = PARAM_POINTS, description = "The number of points to use on the route. Larger values create more circular routes.", example = "5") @JsonProperty(PARAM_POINTS) private Integer points; @JsonIgnore private boolean hasPoints = false; - @Schema(name= PARAM_SEED, description = "A seed to use for adding randomisation to the overall direction of the generated route", + @Schema(name = PARAM_SEED, description = "A seed to use for adding randomisation to the overall direction of the generated route", example = "1") @JsonProperty(PARAM_SEED) private Long seed; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox.java b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox.java index 9be58e6629..bd5c38e549 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox.java @@ -15,17 +15,19 @@ package org.heigit.ors.api.responses.common.boundingbox; -import org.heigit.ors.api.responses.routing.gpx.GPXBounds; - import jakarta.xml.bind.annotation.XmlSeeAlso; import jakarta.xml.bind.annotation.XmlTransient; +import org.heigit.ors.api.responses.routing.gpx.GPXBounds; @XmlSeeAlso(GPXBounds.class) @XmlTransient public interface BoundingBox { double getMinLon(); + double getMaxLon(); + double getMinLat(); + double getMaxLat(); double[] getAsArray(); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox3DBase.java b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox3DBase.java index bc6ba4ea05..04f3a923ff 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox3DBase.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBox3DBase.java @@ -39,7 +39,7 @@ public double getMaxEle() { @Override public double[] getAsArray() { - return new double[] { + return new double[]{ FormatUtility.roundToDecimals(minLon, COORDINATE_DECIMAL_PLACES), FormatUtility.roundToDecimals(minLat, COORDINATE_DECIMAL_PLACES), FormatUtility.roundToDecimals(minEle, ELEVATION_DECIMAL_PLACES), diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxBase.java b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxBase.java index 2b88686877..ce5395d143 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxBase.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxBase.java @@ -25,7 +25,8 @@ public class BoundingBoxBase implements BoundingBox { protected double maxLat; protected double maxLon; - public BoundingBoxBase() {} + public BoundingBoxBase() { + } public BoundingBoxBase(BBox bounding) { minLat = bounding.minLat; @@ -51,7 +52,7 @@ public double getMaxLon() { } public double[] getAsArray() { - return new double[] { + return new double[]{ FormatUtility.roundToDecimals(minLon, COORDINATE_DECIMAL_PLACES), FormatUtility.roundToDecimals(minLat, COORDINATE_DECIMAL_PLACES), FormatUtility.roundToDecimals(maxLon, COORDINATE_DECIMAL_PLACES), diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxFactory.java b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxFactory.java index e5602e32d2..1433916ab2 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxFactory.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/common/boundingbox/BoundingBoxFactory.java @@ -16,13 +16,13 @@ package org.heigit.ors.api.responses.common.boundingbox; import com.graphhopper.util.shapes.BBox; -import org.heigit.ors.routing.APIEnums; import org.heigit.ors.api.requests.isochrones.IsochronesRequest; import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.responses.routing.gpx.GPXBounds; import org.heigit.ors.api.responses.routing.json.JSON3DBoundingBox; import org.heigit.ors.api.responses.routing.json.JSONBoundingBox; import org.heigit.ors.exceptions.ParameterValueException; +import org.heigit.ors.routing.APIEnums; import org.heigit.ors.routing.RoutingErrorCodes; public class BoundingBoxFactory { @@ -31,10 +31,10 @@ private BoundingBoxFactory() { } public static BoundingBox constructBoundingBox(BBox bounds, RouteRequest request) throws ParameterValueException { - switch(request.getResponseType()) { + switch (request.getResponseType()) { case GEOJSON: case JSON: - if(request.hasUseElevation() && request.getUseElevation()) + if (request.hasUseElevation() && request.getUseElevation()) return new JSON3DBoundingBox(bounds); return new JSONBoundingBox(bounds); case GPX: diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/export/ExportResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/export/ExportResponse.java index 000e88946d..892f288fad 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/export/ExportResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/export/ExportResponse.java @@ -12,7 +12,8 @@ public class ExportResponse { @JsonIgnore protected ExportResult exportResults; - public ExportResponse() {}; + public ExportResponse() { + } // In RouteResponse, this method was used to get metadata from RouteRequest. public ExportResponse(ExportResult result) { diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/export/json/JsonExportResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/export/json/JsonExportResponse.java index 24daac7497..aac5cf6355 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/export/json/JsonExportResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/export/json/JsonExportResponse.java @@ -2,13 +2,13 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import org.locationtech.jts.geom.Coordinate; import io.swagger.v3.oas.annotations.media.Schema; import org.heigit.ors.api.responses.export.ExportResponse; import org.heigit.ors.api.responses.routing.json.JSONWarning; -import org.heigit.ors.export.ExportResult; import org.heigit.ors.common.Pair; +import org.heigit.ors.export.ExportResult; import org.heigit.ors.export.ExportWarning; +import org.locationtech.jts.geom.Coordinate; import java.util.ArrayList; import java.util.List; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/IsochronesResponseInfo.java b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/IsochronesResponseInfo.java index 00d061909f..01c5b21130 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/IsochronesResponseInfo.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/IsochronesResponseInfo.java @@ -23,9 +23,9 @@ import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.requests.isochrones.IsochronesRequest; +import org.heigit.ors.api.util.AppInfo; import org.heigit.ors.api.util.SystemMessage; import org.heigit.ors.config.AppConfig; -import org.heigit.ors.api.util.AppInfo; import org.json.JSONObject; @Schema(name = "IsochronesResponseInfo", description = "Information about the request") @@ -56,7 +56,7 @@ public class IsochronesResponseInfo { @JsonProperty("engine") private final EngineInfo engineInfo; - @Schema(description = "System message", example ="A message string configured in the service") + @Schema(description = "System message", example = "A message string configured in the service") @JsonProperty("system_message") private final String systemMessage; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochrone.java b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochrone.java index 236d78c091..72bf60b7e0 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochrone.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochrone.java @@ -1,9 +1,9 @@ package org.heigit.ors.api.responses.isochrones.geojson; import com.fasterxml.jackson.annotation.JsonProperty; +import org.heigit.ors.isochrones.Isochrone; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; -import org.heigit.ors.isochrones.Isochrone; public class GeoJSONIsochrone extends GeoJSONIsochroneBase { private final Isochrone isochrone; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochroneProperties.java b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochroneProperties.java index 11c34cfed4..cb50c5b387 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochroneProperties.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochroneProperties.java @@ -4,15 +4,15 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.extensions.Extension; import io.swagger.v3.oas.annotations.extensions.ExtensionProperty; -import org.locationtech.jts.geom.Coordinate; import io.swagger.v3.oas.annotations.media.Schema; import org.heigit.ors.common.AttributeValue; import org.heigit.ors.isochrones.Isochrone; +import org.locationtech.jts.geom.Coordinate; @JsonInclude(JsonInclude.Include.NON_EMPTY) public class GeoJSONIsochroneProperties { - @Schema(description = "Id of the isochrone based on the position in the `locations` query-parameter. Every location comprises its own group of polygons.", example ="1") + @Schema(description = "Id of the isochrone based on the position in the `locations` query-parameter. Every location comprises its own group of polygons.", example = "1") @JsonProperty(value = "group_index") private final Integer groupIndex; @@ -25,7 +25,7 @@ public class GeoJSONIsochroneProperties { private final Double[] center; @Schema(description = "Area of the polygon in square meters (for attributes=area).", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "attributes"), @ExtensionProperty(name = "containsValue", value = "area")} )}, @@ -43,7 +43,7 @@ public class GeoJSONIsochroneProperties { private Double reachfactor; @Schema(description = "Total population of the polygon (for attributes=total_pop).", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "attributes"), @ExtensionProperty(name = "containsValue", value = "total_pop")} )}, diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesIntersection.java b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesIntersection.java index 625fa8760c..7acfa67de0 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesIntersection.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesIntersection.java @@ -17,7 +17,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import org.locationtech.jts.geom.Geometry; import org.heigit.ors.api.requests.isochrones.IsochronesRequest; import org.heigit.ors.api.requests.isochrones.IsochronesRequestEnums; import org.heigit.ors.common.Pair; @@ -25,6 +24,7 @@ import org.heigit.ors.isochrones.IsochronesErrorCodes; import org.heigit.ors.isochrones.IsochronesIntersection; import org.heigit.ors.util.FormatUtility; +import org.locationtech.jts.geom.Geometry; import java.util.*; @@ -40,7 +40,7 @@ public GeoJSONIsochronesIntersection(IsochronesIntersection intersection, Isochr properties = fillProperties(intersection, request); } - private Map fillProperties(IsochronesIntersection intersection, IsochronesRequest request) throws InternalServerException { + private Map fillProperties(IsochronesIntersection intersection, IsochronesRequest request) throws InternalServerException { Map props = new HashMap<>(); List contours = new ArrayList<>(); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesMap.java b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesMap.java index 05f58b8da7..1cc2876a7c 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesMap.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesMap.java @@ -1,8 +1,8 @@ package org.heigit.ors.api.responses.isochrones.geojson; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.isochrones.Isochrone; import org.heigit.ors.isochrones.IsochroneMap; +import org.locationtech.jts.geom.Coordinate; import java.util.ArrayList; import java.util.List; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesResponse.java index 4b4f5621b4..fd7b71eaad 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/isochrones/geojson/GeoJSONIsochronesResponse.java @@ -18,10 +18,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.graphhopper.util.shapes.BBox; +import io.swagger.v3.oas.annotations.media.Schema; import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; -import org.locationtech.jts.geom.Envelope; -import io.swagger.v3.oas.annotations.media.Schema; import org.heigit.ors.api.requests.isochrones.IsochronesRequest; import org.heigit.ors.api.responses.common.boundingbox.BoundingBoxFactory; import org.heigit.ors.api.responses.isochrones.IsochronesResponse; @@ -33,6 +32,7 @@ import org.heigit.ors.isochrones.IsochroneUtility; import org.heigit.ors.isochrones.IsochronesIntersection; import org.heigit.ors.util.GeomUtility; +import org.locationtech.jts.geom.Envelope; import java.util.ArrayList; import java.util.List; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/MatrixResponseInfo.java b/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/MatrixResponseInfo.java index e4ebaaf893..0ff7b2381e 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/MatrixResponseInfo.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/MatrixResponseInfo.java @@ -23,9 +23,9 @@ import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.requests.matrix.MatrixRequest; +import org.heigit.ors.api.util.AppInfo; import org.heigit.ors.api.util.SystemMessage; import org.heigit.ors.config.AppConfig; -import org.heigit.ors.api.util.AppInfo; import org.json.JSONObject; @Schema(description = "Information about the request") @@ -56,7 +56,7 @@ public class MatrixResponseInfo { @JsonProperty("engine") private final EngineInfo engineInfo; - @Schema(description = "System message", example ="A message string configured in the service") + @Schema(description = "System message", example = "A message string configured in the service") @JsonProperty("system_message") private final String systemMessage; @@ -79,6 +79,7 @@ public MatrixResponseInfo(MatrixRequest request, SystemMessageProperties systemM this.systemMessage = SystemMessage.getSystemMessage(request, systemMessageProperties); } + @JsonIgnore public void setGraphDate(String graphDate) { engineInfo.setGraphDate(graphDate); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/json/JSONIndividualMatrixResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/json/JSONIndividualMatrixResponse.java index 9b695b7c1c..a8ca65a908 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/json/JSONIndividualMatrixResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/matrix/json/JSONIndividualMatrixResponse.java @@ -50,7 +50,7 @@ public class JSONIndividualMatrixResponse extends JSONBasedIndividualMatrixRespo destinations = constructDestinations(result); sources = constructSources(result); - for (int i=0; i durations = constructMetric(result.getTable(i), result); @@ -68,9 +68,9 @@ private Double[][] constructMetric(float[] table, MatrixResult result) { Double[][] constructedTable = new Double[sourceCount][destinationCount]; - for (int i=0; i(); - for(RouteResult result : routeResults) { + for (RouteResult result : routeResults) { this.routeResults.add(new GeoJSONIndividualRouteResponse(result, request)); responseInformation.setGraphDate(result.getGraphDate()); } List bboxes = new ArrayList<>(); - for(RouteResult result : routeResults) { + for (RouteResult result : routeResults) { bboxes.add(result.getSummary().getBBox()); } diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/geojson/GeoJSONSummary.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/geojson/GeoJSONSummary.java index c8b8e53832..e046b921e5 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/geojson/GeoJSONSummary.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/geojson/GeoJSONSummary.java @@ -46,14 +46,14 @@ public class GeoJSONSummary extends JSONSummary { private final List legs; private final List warnings; @Schema(description = "Departure date and time", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "departure"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "2020-01-31T12:45:00+01:00") @JsonProperty(value = "departure") protected ZonedDateTime departure; @Schema(description = "Arrival date and time", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "arrival"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "2020-01-31T13:15:00+01:00") @@ -68,7 +68,7 @@ public GeoJSONSummary(RouteResult result, List segments, Map> getWarnings() { List> warningsMap = new ArrayList<>(); - for (RouteWarning warning: warnings) { + for (RouteWarning warning : warnings) { Map warningMap = new HashMap<>(); warningMap.put("code", warning.getWarningCode()); warningMap.put("message", warning.getWarningMessage()); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXAuthor.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXAuthor.java index 029fcbd9b3..7625133c96 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXAuthor.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXAuthor.java @@ -15,9 +15,8 @@ package org.heigit.ors.api.responses.routing.gpx; -import org.heigit.ors.exceptions.InternalServerException; - import jakarta.xml.bind.annotation.XmlElement; +import org.heigit.ors.exceptions.InternalServerException; public class GPXAuthor { @XmlElement(name = "name") @@ -34,7 +33,7 @@ public GPXAuthor() throws InternalServerException { this(null, null, null); } - public GPXAuthor(String name, String email, String baseUrl) throws InternalServerException { + public GPXAuthor(String name, String email, String baseUrl) throws InternalServerException { this.name = name; this.email = new GPXEmail(email); this.link = new GPXLink(baseUrl); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXBounds.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXBounds.java index 5d19af5d21..6ed1d45cd4 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXBounds.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXBounds.java @@ -16,12 +16,11 @@ package org.heigit.ors.api.responses.routing.gpx; import com.graphhopper.util.shapes.BBox; +import jakarta.xml.bind.annotation.XmlAttribute; import org.heigit.ors.api.responses.common.boundingbox.BoundingBox; import org.heigit.ors.api.responses.common.boundingbox.BoundingBoxBase; import org.heigit.ors.util.FormatUtility; -import jakarta.xml.bind.annotation.XmlAttribute; - public class GPXBounds extends BoundingBoxBase implements BoundingBox { public GPXBounds() { super(); @@ -36,16 +35,19 @@ public GPXBounds(BBox bounding) { public double getMinLat() { return FormatUtility.roundToDecimals(this.minLat, COORDINATE_DECIMAL_PLACES); } + @Override @XmlAttribute(name = "minLon") public double getMinLon() { return FormatUtility.roundToDecimals(this.minLon, COORDINATE_DECIMAL_PLACES); } + @Override @XmlAttribute(name = "maxLat") public double getMaxLat() { return FormatUtility.roundToDecimals(this.maxLat, COORDINATE_DECIMAL_PLACES); } + @Override @XmlAttribute(name = "maxLon") public double getMaxLon() { diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXCopyright.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXCopyright.java index 4a3a1b15fa..5de060b02d 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXCopyright.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXCopyright.java @@ -17,6 +17,7 @@ import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; + import java.util.Calendar; public class GPXCopyright { diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXEmail.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXEmail.java index 95745f88b6..4794665ff6 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXEmail.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXEmail.java @@ -15,11 +15,10 @@ package org.heigit.ors.api.responses.routing.gpx; -import org.heigit.ors.exceptions.InternalServerException; -import org.heigit.ors.routing.RoutingErrorCodes; - import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlRootElement; +import org.heigit.ors.exceptions.InternalServerException; +import org.heigit.ors.routing.RoutingErrorCodes; @XmlRootElement(name = "email") public class GPXEmail { diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXExtensions.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXExtensions.java index 38e30dd3bc..f704f8e4f2 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXExtensions.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXExtensions.java @@ -16,11 +16,10 @@ package org.heigit.ors.api.responses.routing.gpx; import com.graphhopper.util.Helper; -import org.heigit.ors.routing.APIEnums; +import jakarta.xml.bind.annotation.XmlElement; import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.util.AppInfo; - -import jakarta.xml.bind.annotation.XmlElement; +import org.heigit.ors.routing.APIEnums; public class GPXExtensions { @XmlElement(name = "attribution") @@ -31,7 +30,7 @@ public class GPXExtensions { private String buildDate; @XmlElement(name = "profile") private String profile; - @XmlElement(name="preference") + @XmlElement(name = "preference") private String preference; @XmlElement(name = "language") private String language; @@ -42,7 +41,8 @@ public class GPXExtensions { @XmlElement(name = "elevation") private boolean includeElevation; - public GPXExtensions() {} + public GPXExtensions() { + } public GPXExtensions(RouteRequest request, String attribution) { if (!Helper.isEmpty(attribution)) @@ -68,7 +68,7 @@ public GPXExtensions(RouteRequest request, String attribution) { else includeInstructions = true; - if(request.hasUseElevation()) + if (request.hasUseElevation()) includeElevation = request.getUseElevation(); else includeElevation = false; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadata.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadata.java index 6598f03520..f66b132224 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadata.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadata.java @@ -16,6 +16,8 @@ package org.heigit.ors.api.responses.routing.gpx; import com.graphhopper.util.shapes.BBox; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.requests.routing.RouteRequest; @@ -25,8 +27,6 @@ import org.heigit.ors.routing.RouteResult; import org.heigit.ors.util.GeomUtility; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; import java.util.Date; @XmlRootElement(name = "metadata") diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadataExtensions.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadataExtensions.java index b60e75c5ad..6f1ec6f3bb 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadataExtensions.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXMetadataExtensions.java @@ -15,19 +15,19 @@ package org.heigit.ors.api.responses.routing.gpx; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.util.SystemMessage; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; - @XmlRootElement(name = "extensions") public class GPXMetadataExtensions { @XmlElement(name = "system-message") private String systemMessage; - public GPXMetadataExtensions() {} + public GPXMetadataExtensions() { + } public GPXMetadataExtensions(RouteRequest request, SystemMessageProperties systemMessageProperties) { this.systemMessage = SystemMessage.getSystemMessage(request, systemMessageProperties); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteElement.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteElement.java index bd69447b0f..2ce245e478 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteElement.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteElement.java @@ -15,14 +15,14 @@ package org.heigit.ors.api.responses.routing.gpx; -import org.locationtech.jts.geom.Coordinate; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; import org.heigit.ors.routing.RouteResult; import org.heigit.ors.routing.RouteSegment; import org.heigit.ors.routing.RouteStep; +import org.locationtech.jts.geom.Coordinate; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; @@ -66,7 +66,7 @@ public GPXRouteElement(RouteResult result) { } // it may be the case that we did not ask for instructions so there will be no steps - if (steps.isEmpty() && routeCoordinates.length > 0) { + if (steps.isEmpty()) { for (Coordinate coord : routeCoordinates) { routePoints.add(new GPXRoutePointElement(null, coord.x, coord.y, coord.z, -1)); } diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteExtensions.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteExtensions.java index 0140ee9cce..b1070493ce 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteExtensions.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteExtensions.java @@ -15,11 +15,10 @@ package org.heigit.ors.api.responses.routing.gpx; -import org.heigit.ors.routing.RouteResult; -import org.heigit.ors.routing.RouteSummary; - import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; +import org.heigit.ors.routing.RouteResult; +import org.heigit.ors.routing.RouteSummary; @XmlRootElement(name = "extensions") public class GPXRouteExtensions { @@ -36,7 +35,8 @@ public class GPXRouteExtensions { @XmlElement(name = "bounds") private GPXBounds bounds; - public GPXRouteExtensions() {} + public GPXRouteExtensions() { + } public GPXRouteExtensions(RouteResult result) { RouteSummary summary = result.getSummary(); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointElement.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointElement.java index 66ac5aa7f1..d0681d8dc8 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointElement.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointElement.java @@ -15,12 +15,11 @@ package org.heigit.ors.api.responses.routing.gpx; -import org.heigit.ors.routing.RouteStep; -import org.heigit.ors.util.FormatUtility; - import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; +import org.heigit.ors.routing.RouteStep; +import org.heigit.ors.util.FormatUtility; @XmlType(propOrder = {"elevation", "name", "instructionDescription", "element"}) public class GPXRoutePointElement { @@ -39,15 +38,16 @@ public class GPXRoutePointElement { @XmlElement(name = "extensions") private GPXRoutePointExtensionElement element; - public GPXRoutePointElement() { } + public GPXRoutePointElement() { + } - public GPXRoutePointElement( RouteStep step, double longitude, double latitude, double elevation, int stepNumber) { + public GPXRoutePointElement(RouteStep step, double longitude, double latitude, double elevation, int stepNumber) { this.latitude = latitude; this.longitude = longitude; - if(!Double.isNaN(elevation)) + if (!Double.isNaN(elevation)) this.elevation = elevation; - if(step != null) { + if (step != null) { this.name = step.getName(); this.instructionDescription = step.getInstruction(); @@ -57,7 +57,7 @@ public GPXRoutePointElement( RouteStep step, double longitude, double latitude, @XmlElement(name = "ele") public Double getElevation() { - if(elevation != null) + if (elevation != null) return FormatUtility.roundToDecimals(elevation, ELEVATION_DECIMAL_PLACES); else return null; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointExtensionElement.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointExtensionElement.java index f3b524e6f7..398e450118 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointExtensionElement.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRoutePointExtensionElement.java @@ -15,16 +15,15 @@ package org.heigit.ors.api.responses.routing.gpx; -import org.heigit.ors.routing.RouteStep; - import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; +import org.heigit.ors.routing.RouteStep; @XmlRootElement(name = "extensions") public class GPXRoutePointExtensionElement { @XmlElement(name = "distance") private double distance; - @XmlElement(name="duration") + @XmlElement(name = "duration") private double duration; @XmlElement(name = "type") private int type; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteResponse.java index 99ab375840..cacf6715e8 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/gpx/GPXRouteResponse.java @@ -16,6 +16,9 @@ package org.heigit.ors.api.responses.routing.gpx; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.XmlAttribute; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.requests.routing.RouteRequest; @@ -23,9 +26,6 @@ import org.heigit.ors.exceptions.StatusCodeException; import org.heigit.ors.routing.RouteResult; -import jakarta.xml.bind.annotation.XmlAttribute; -import jakarta.xml.bind.annotation.XmlElement; -import jakarta.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONBasedIndividualRouteResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONBasedIndividualRouteResponse.java index b4b367321f..6b0e7b6520 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONBasedIndividualRouteResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONBasedIndividualRouteResponse.java @@ -37,7 +37,7 @@ public class JSONBasedIndividualRouteResponse extends IndividualRouteResponse { public JSONBasedIndividualRouteResponse(RouteResult result, RouteRequest request) throws StatusCodeException { super(result, request); - if(request.hasUseElevation() && request.getUseElevation()) + if (request.hasUseElevation() && request.getUseElevation()) includeElevation = true; bbox = BoundingBoxFactory.constructBoundingBox(result.getSummary().getBBox(), request); @@ -45,7 +45,7 @@ public JSONBasedIndividualRouteResponse(RouteResult result, RouteRequest request protected List constructSegments(RouteResult routeResult, RouteRequest request) { List segments = new ArrayList<>(); - for(RouteSegment routeSegment : routeResult.getSegments()) { + for (RouteSegment routeSegment : routeResult.getSegments()) { segments.add(new JSONSegment(routeSegment, request, routeResult.getSummary().getDistance())); } @@ -54,7 +54,7 @@ protected List constructSegments(RouteResult routeResult, RouteRequ protected List constructLegs(RouteResult routeResult) { List legs = new ArrayList<>(); - for(RouteLeg routeLeg : routeResult.getLegs()) { + for (RouteLeg routeLeg : routeResult.getLegs()) { legs.add(new JSONLeg(routeLeg)); } return legs; @@ -63,7 +63,7 @@ protected List constructLegs(RouteResult routeResult) { protected Map constructExtras(RouteRequest routeRequest, RouteResult routeResult) throws StatusCodeException { Map extras = new HashMap<>(); List responseExtras = routeResult.getExtraInfo(); - if(responseExtras != null) { + if (responseExtras != null) { double routeLength = routeResult.getSummary().getDistance(); DistanceUnit units = DistanceUnit.METERS; if (routeRequest.hasUnits()) diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONExtra.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONExtra.java index ac02f623b9..d4439b3efe 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONExtra.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONExtra.java @@ -31,7 +31,7 @@ public class JSONExtra { public JSONExtra(List segments, List summaryItems) { values = new ArrayList<>(); - for(RouteSegmentItem item : segments) { + for (RouteSegmentItem item : segments) { List segment = new ArrayList<>(); segment.add((long) item.getFrom()); segment.add((long) item.getTo()); @@ -40,7 +40,7 @@ public JSONExtra(List segments, List summary } summary = new ArrayList<>(); - for(ExtraSummaryItem item : summaryItems) { + for (ExtraSummaryItem item : summaryItems) { summary.add(new JSONExtraSummary(item.getValue(), item.getDistance(), item.getAmount())); } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONIndividualRouteResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONIndividualRouteResponse.java index fb72aef0ac..0e11d7e0c2 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONIndividualRouteResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONIndividualRouteResponse.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.annotation.JsonUnwrapped; import io.swagger.v3.oas.annotations.extensions.Extension; import io.swagger.v3.oas.annotations.extensions.ExtensionProperty; -import org.locationtech.jts.geom.Coordinate; import io.swagger.v3.oas.annotations.media.Schema; import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.responses.common.boundingbox.BoundingBoxFactory; @@ -31,6 +30,7 @@ import org.heigit.ors.routing.RouteWarning; import org.heigit.ors.util.DistanceUnitUtil; import org.heigit.ors.util.PolylineEncoder; +import org.locationtech.jts.geom.Coordinate; import java.time.ZonedDateTime; import java.util.ArrayList; @@ -67,14 +67,14 @@ public class JSONIndividualRouteResponse extends JSONBasedIndividualRouteRespons private final Map extras; @Schema(description = "Departure date and time", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "departure"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "2020-01-31T12:45:00+01:00") @JsonProperty(value = "departure") protected ZonedDateTime departure; @Schema(description = "Arrival date and time", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "arrival"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "2020-01-31T13:15:00+01:00") @@ -86,7 +86,7 @@ public JSONIndividualRouteResponse(RouteResult routeResult, RouteRequest request geomResponse = constructEncodedGeometry(this.routeCoordinates); - if(this.includeElevation) + if (this.includeElevation) summary = new JSONSummary(routeResult.getSummary().getDistance(), routeResult.getSummary().getDuration(), routeResult.getSummary().getAscent(), routeResult.getSummary().getDescent()); else summary = new JSONSummary(routeResult.getSummary().getDistance(), routeResult.getSummary().getDuration()); @@ -96,7 +96,7 @@ public JSONIndividualRouteResponse(RouteResult routeResult, RouteRequest request summary.setFare(routeResult.getSummary().getFare()); } - if(routeResult.hasDepartureAndArrival()) { + if (routeResult.hasDepartureAndArrival()) { departure = routeResult.getDeparture(); arrival = routeResult.getArrival(); } @@ -109,18 +109,18 @@ public JSONIndividualRouteResponse(RouteResult routeResult, RouteRequest request extras = new HashMap<>(); List responseExtras = routeResult.getExtraInfo(); - if(responseExtras != null) { + if (responseExtras != null) { double routeLength = routeResult.getSummary().getDistance(); DistanceUnit units = DistanceUnit.METERS; if (request.hasUnits()) - units = DistanceUnitUtil.getFromString(request.getUnits().toString(), DistanceUnit.UNKNOWN); + units = DistanceUnitUtil.getFromString(request.getUnits().toString(), DistanceUnit.UNKNOWN); for (RouteExtraInfo extraInfo : responseExtras) { extras.put(extraInfo.getName(), new JSONExtra(extraInfo.getSegments(), extraInfo.getSummary(units, routeLength, true))); } } if (routeResult.getWarnings() != null && !routeResult.getWarnings().isEmpty()) { - warnings= new ArrayList<>(); + warnings = new ArrayList<>(); for (RouteWarning warning : routeResult.getWarnings()) { warnings.add(new JSONWarning(warning)); } @@ -130,7 +130,7 @@ public JSONIndividualRouteResponse(RouteResult routeResult, RouteRequest request } private String constructEncodedGeometry(final Coordinate[] coordinates) { - if(coordinates != null) + if (coordinates != null) return PolylineEncoder.encode(coordinates, includeElevation, new StringBuilder()); else return ""; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONLeg.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONLeg.java index fdf4b7c9a2..19758d47b9 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONLeg.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONLeg.java @@ -33,7 +33,7 @@ import java.util.ArrayList; import java.util.List; -@Schema(name="JSONLeg", description = "Leg of a route") +@Schema(name = "JSONLeg", description = "Leg of a route") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class JSONLeg { @Schema(description = "The type of the leg, possible values are currently 'walk' and 'pt'.", example = "pt") @@ -65,14 +65,14 @@ public class JSONLeg { @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT, pattern = "%.1d") private final Double duration; @Schema(description = "Departure date and time", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "departure"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "2020-01-31T12:45:00+01:00") @JsonProperty(value = "departure") protected ZonedDateTime departure; @Schema(description = "Arrival date and time", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "arrival"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "2020-01-31T13:15:00+01:00") @@ -127,7 +127,7 @@ public JSONLeg(RouteLeg leg) { } if (leg.getStops() != null) { stops = new ArrayList<>(); - for(RoutePtStop stop : leg.getStops()) { + for (RoutePtStop stop : leg.getStops()) { stops.add(new JSONPtStop(stop)); } } else { @@ -137,7 +137,7 @@ public JSONLeg(RouteLeg leg) { } private String constructEncodedGeometry(final Coordinate[] coordinates, boolean includeElevation) { - if(coordinates != null) + if (coordinates != null) return PolylineEncoder.encode(coordinates, includeElevation, new StringBuilder()); else return ""; diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONPtStop.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONPtStop.java index c296764da8..3951dad8c2 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONPtStop.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONPtStop.java @@ -24,7 +24,7 @@ import java.util.Date; import java.util.List; -@Schema(name="JSONPtStop", description = "Stop of a public transport leg") +@Schema(name = "JSONPtStop", description = "Stop of a public transport leg") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class JSONPtStop { @Schema(description = "The ID of the stop.", example = "de:08221:1138:0:O") diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONRouteResponse.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONRouteResponse.java index f2f09ec0e6..9ebb09669c 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONRouteResponse.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONRouteResponse.java @@ -23,7 +23,6 @@ import org.heigit.ors.api.SystemMessageProperties; import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.responses.common.boundingbox.BoundingBoxFactory; -import org.heigit.ors.api.responses.routing.IndividualRouteResponse; import org.heigit.ors.api.responses.routing.RouteResponse; import org.heigit.ors.api.responses.routing.RouteResponseInfo; import org.heigit.ors.exceptions.StatusCodeException; @@ -41,7 +40,7 @@ public JSONRouteResponse(RouteResult[] routeResults, RouteRequest request, Syste this.routeResults = new ArrayList<>(); List bboxes = new ArrayList<>(); - for(RouteResult result : routeResults) { + for (RouteResult result : routeResults) { this.routeResults.add(new JSONIndividualRouteResponse(result, request)); bboxes.add(result.getSummary().getBBox()); responseInformation.setGraphDate(result.getGraphDate()); @@ -54,7 +53,7 @@ public JSONRouteResponse(RouteResult[] routeResults, RouteRequest request, Syste @JsonProperty("routes") @Schema(description = "A list of routes returned from the request") public JSONIndividualRouteResponse[] getRoutes() { - return (JSONIndividualRouteResponse[]) routeResults.toArray(new JSONIndividualRouteResponse[0]); + return routeResults.toArray(new JSONIndividualRouteResponse[0]); } @JsonProperty("bbox") diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSegment.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSegment.java index 24303d4ed0..c5ae73ed19 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSegment.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSegment.java @@ -20,8 +20,8 @@ import io.swagger.v3.oas.annotations.extensions.Extension; import io.swagger.v3.oas.annotations.extensions.ExtensionProperty; import io.swagger.v3.oas.annotations.media.Schema; -import org.heigit.ors.routing.APIEnums; import org.heigit.ors.api.requests.routing.RouteRequest; +import org.heigit.ors.routing.APIEnums; import org.heigit.ors.routing.RouteSegment; import org.heigit.ors.routing.RouteStep; import org.heigit.ors.util.FormatUtility; @@ -45,28 +45,28 @@ public class JSONSegment { @JsonInclude() private final List steps; @Schema(description = "Contains the deviation compared to a straight line that would have the factor `1`. Double the Distance would be a `2`.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "attributes"), @ExtensionProperty(name = "valueContains", value = "detourfactor")} )}, example = "0.5") @JsonProperty("detourfactor") private Double detourFactor; @Schema(description = "Contains the proportion of the route in percent.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "attributes"), @ExtensionProperty(name = "valueContains", value = "percentage")} )}, example = "43.2") @JsonProperty("percentage") private Double percentage; @Schema(description = "Contains the average speed of this segment in km/h.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "attributes"), @ExtensionProperty(name = "valueContains", value = "avgspeed")} )}, example = "56.3") @JsonProperty("avgspeed") private Double averageSpeed; @Schema(description = " Contains ascent of this segment in metres.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "elevation"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "56.3") @@ -81,18 +81,18 @@ public JSONSegment(RouteSegment routeSegment, RouteRequest request, double route this.distance = routeSegment.getDistance(); this.duration = routeSegment.getDuration(); this.detourFactor = routeSegment.getDetourFactor(); - if(request.hasUseElevation() && request.getUseElevation()) { + if (request.hasUseElevation() && request.getUseElevation()) { this.ascent = routeSegment.getAscent(); this.descent = routeSegment.getDescent(); } steps = new ArrayList<>(); - for(RouteStep routeStep : routeSegment.getSteps()) { + for (RouteStep routeStep : routeSegment.getSteps()) { steps.add(new JSONStep(routeStep)); } - if(request.hasAttributes()) { + if (request.hasAttributes()) { APIEnums.Attributes[] attributes = request.getAttributes(); - for(APIEnums.Attributes attr : attributes) { + for (APIEnums.Attributes attr : attributes) { switch (attr) { case DETOUR_FACTOR -> detourFactor = routeSegment.getDetourFactor(); case AVERAGE_SPEED -> { diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStep.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStep.java index 0a09cc5e58..ff1561c3a1 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStep.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStep.java @@ -27,7 +27,7 @@ import java.util.Arrays; -@Schema(name="JSONStep", description = "Step of a route segment") +@Schema(name = "JSONStep", description = "Step of a route segment") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class JSONStep { @Schema(description = "The distance for the step in metres.", example = "245") @@ -50,7 +50,7 @@ public class JSONStep { @JsonProperty("exit_number") private Integer exitNumber; @Schema(description = "Contains the bearing of the entrance and all passed exits in a roundabout.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "roundabout_exits"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "[10,45,60]") @@ -60,7 +60,7 @@ public class JSONStep { @JsonProperty("way_points") private int[] waypoints; @Schema(description = "The maneuver to be performed.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "maneuvers"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}) diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStepManeuver.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStepManeuver.java index c7974b4954..1b00922e8d 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStepManeuver.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONStepManeuver.java @@ -41,7 +41,7 @@ public class JSONStepManeuver { public JSONStepManeuver(RouteStepManeuver maneuver) { Coordinate coordinate = maneuver.getLocation(); - if(coordinate != null) { + if (coordinate != null) { if (!Double.isNaN(coordinate.z)) { location = new Double[3]; location[2] = FormatUtility.roundToDecimals(coordinate.z, ELEVATION_DECIMAL_PLACES); diff --git a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSummary.java b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSummary.java index f83666280b..617eb1ef83 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSummary.java +++ b/ors-api/src/main/java/org/heigit/ors/api/responses/routing/json/JSONSummary.java @@ -36,7 +36,7 @@ public class JSONSummary { @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT, pattern = "%.1d") protected Double duration; @Schema(description = "Total ascent in meters.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "elevation"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "166.3") @@ -44,7 +44,7 @@ public class JSONSummary { @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT, pattern = "%.1d") protected Double ascent; @Schema(description = "Total descent in meters.", - extensions = { @Extension(name = "validWhen", properties = { + extensions = {@Extension(name = "validWhen", properties = { @ExtensionProperty(name = "ref", value = "elevation"), @ExtensionProperty(name = "value", value = "true", parseValue = true)} )}, example = "201.3") @@ -88,11 +88,11 @@ public JSONSummary(Double distance, Double duration, Double ascent, Double desce } public JSONSummary(RouteResult route, boolean includeElevation, boolean isPtRequest) { - if(includeElevation) { + if (includeElevation) { this.ascent = route.getSummary().getAscent(); this.descent = route.getSummary().getDescent(); } - if(isPtRequest) { + if (isPtRequest) { this.transfers = route.getSummary().getTransfers(); this.fare = route.getSummary().getFare(); } diff --git a/ors-api/src/main/java/org/heigit/ors/api/services/ApiService.java b/ors-api/src/main/java/org/heigit/ors/api/services/ApiService.java index 548190b598..7eb0965b57 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/services/ApiService.java +++ b/ors-api/src/main/java/org/heigit/ors/api/services/ApiService.java @@ -34,11 +34,11 @@ public class ApiService { protected EndpointsProperties endpointsProperties; - double getMaximumAvoidPolygonArea(){ + double getMaximumAvoidPolygonArea() { return 0d; } - double getMaximumAvoidPolygonExtent(){ + double getMaximumAvoidPolygonExtent() { return 0d; } @@ -112,8 +112,7 @@ protected Polygon[] convertAvoidAreas(JSONObject geoJson) throws StatusCodeExcep if (convertedGeom instanceof Polygon) { avoidAreas = new Polygon[]{(Polygon) convertedGeom}; - } else if (convertedGeom instanceof MultiPolygon) { - MultiPolygon multiPoly = (MultiPolygon) convertedGeom; + } else if (convertedGeom instanceof MultiPolygon multiPoly) { avoidAreas = new Polygon[multiPoly.getNumGeometries()]; for (int i = 0; i < multiPoly.getNumGeometries(); i++) avoidAreas[i] = (Polygon) multiPoly.getGeometryN(i); @@ -322,17 +321,17 @@ private VehicleParameters setLoadCharacteristicsParam(RequestProfileParamsRestri private WheelchairParameters convertWheelchairParamRestrictions(RequestProfileParamsRestrictions restrictions) { WheelchairParameters params = new WheelchairParameters(); - if(restrictions.hasSurfaceType()) + if (restrictions.hasSurfaceType()) params.setSurfaceType(WheelchairTypesEncoder.getSurfaceType(restrictions.getSurfaceType())); - if(restrictions.hasTrackType()) + if (restrictions.hasTrackType()) params.setTrackType(WheelchairTypesEncoder.getTrackType(restrictions.getTrackType())); - if(restrictions.hasSmoothnessType()) + if (restrictions.hasSmoothnessType()) params.setSmoothnessType(WheelchairTypesEncoder.getSmoothnessType(restrictions.getSmoothnessType())); - if(restrictions.hasMaxSlopedKerb()) + if (restrictions.hasMaxSlopedKerb()) params.setMaximumSlopedKerb(restrictions.getMaxSlopedKerb()); - if(restrictions.hasMaxIncline()) + if (restrictions.hasMaxIncline()) params.setMaximumIncline(restrictions.getMaxIncline()); - if(restrictions.hasMinWidth()) + if (restrictions.hasMinWidth()) params.setMinimumWidth(restrictions.getMinWidth()); return params; diff --git a/ors-api/src/main/java/org/heigit/ors/api/services/IsochronesService.java b/ors-api/src/main/java/org/heigit/ors/api/services/IsochronesService.java index 122215c527..a231912f5b 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/services/IsochronesService.java +++ b/ors-api/src/main/java/org/heigit/ors/api/services/IsochronesService.java @@ -195,7 +195,7 @@ IsochroneRequest convertIsochroneRequest(IsochronesRequest isochronesRequest) th } - Map constructStatisticsProvidersConfiguration (Map statsProperties) { + Map constructStatisticsProvidersConfiguration(Map statsProperties) { Map statsProviders = new HashMap<>(); if (statsProperties != null) { diff --git a/ors-api/src/main/java/org/heigit/ors/api/services/RoutingService.java b/ors-api/src/main/java/org/heigit/ors/api/services/RoutingService.java index e0d0866697..8422443c19 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/services/RoutingService.java +++ b/ors-api/src/main/java/org/heigit/ors/api/services/RoutingService.java @@ -4,11 +4,9 @@ import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.requests.routing.RouteRequestRoundTripOptions; import org.heigit.ors.common.StatusCode; -import org.heigit.ors.config.AppConfig; import org.heigit.ors.exceptions.*; import org.heigit.ors.localization.LocalizationManager; import org.heigit.ors.routing.*; -import org.heigit.ors.util.StringUtility; import org.locationtech.jts.geom.Coordinate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -34,7 +32,7 @@ public RoutingService(EndpointsProperties endpointsProperties) { @Override double getMaximumAvoidPolygonExtent() { - return this.endpointsProperties.getRouting().getMaximumAvoidPolygonExtent(); + return this.endpointsProperties.getRouting().getMaximumAvoidPolygonExtent(); } public RouteResult[] generateRouteFromRequest(RouteRequest request) throws StatusCodeException { diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/CompressionFilter.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/CompressionFilter.java index 285430a09a..9b09240bfd 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/CompressionFilter.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/CompressionFilter.java @@ -13,44 +13,39 @@ */ package org.heigit.ors.api.servlet.filters; -import java.io.IOException; - -import jakarta.servlet.Filter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.FilterConfig; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; +import jakarta.servlet.*; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; + public class CompressionFilter implements Filter { - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - if (req instanceof HttpServletRequest request) { - HttpServletResponse response = (HttpServletResponse) res; - String acceptEncoding = request.getHeader("accept-encoding"); - - if (acceptEncoding != null) { - if(acceptEncoding.contains(ContentEncodingType.GZIP)) { - GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response); - chain.doFilter(req, wrappedResponse); - wrappedResponse.finishResponse(); - return; - } else if (acceptEncoding.contains(ContentEncodingType.DEFLATE)) { - // not implemented - } - } - chain.doFilter(req, res); - } - } - - @Override - public void init(FilterConfig filterConfig) { - // nothing to do - } - - @Override - public void destroy() { - // nothing to do - } + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { + if (req instanceof HttpServletRequest request) { + HttpServletResponse response = (HttpServletResponse) res; + String acceptEncoding = request.getHeader("accept-encoding"); + + if (acceptEncoding != null) { + if (acceptEncoding.contains(ContentEncodingType.GZIP)) { + GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response); + chain.doFilter(req, wrappedResponse); + wrappedResponse.finishResponse(); + return; + } else if (acceptEncoding.contains(ContentEncodingType.DEFLATE)) { + // not implemented + } + } + chain.doFilter(req, res); + } + } + + @Override + public void init(FilterConfig filterConfig) { + // nothing to do + } + + @Override + public void destroy() { + // nothing to do + } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/ContentEncodingType.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/ContentEncodingType.java index fd4fa78444..ba9feed260 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/ContentEncodingType.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/ContentEncodingType.java @@ -1,22 +1,23 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.api.servlet.filters; public final class ContentEncodingType { - public static final String BROTLI = "br"; - public static final String GZIP = "gzip"; - public static final String DEFLATE = "deflate"; + public static final String BROTLI = "br"; + public static final String GZIP = "gzip"; + public static final String DEFLATE = "deflate"; - private ContentEncodingType() {} + private ContentEncodingType() { + } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseStream.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseStream.java index b12852a561..893a25e6f6 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseStream.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseStream.java @@ -1,104 +1,103 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.api.servlet.filters; -import java.io.IOException; -import java.util.zip.GZIPOutputStream; - import jakarta.servlet.ServletOutputStream; import jakarta.servlet.WriteListener; import jakarta.servlet.http.HttpServletResponse; - import org.heigit.ors.io.ByteArrayOutputStreamEx; -class GZIPResponseStream extends ServletOutputStream { - private ByteArrayOutputStreamEx bufferStream = null; - private GZIPOutputStream gzipOutputStream = null; - private ServletOutputStream servletOutputStream = null; - private HttpServletResponse servletResponse = null; - private boolean closed = false; - - public GZIPResponseStream(HttpServletResponse response) throws IOException { - super(); - - this.servletResponse = response; - this.servletOutputStream = response.getOutputStream(); - bufferStream = new ByteArrayOutputStreamEx(); - gzipOutputStream = new GZIPOutputStream(bufferStream); - } - - @Override - public void close() throws IOException { - if (closed) - throw new IOException("This output stream has already been closed"); - - gzipOutputStream.finish(); - - byte[] bytes = bufferStream.getBuffer(); - int bytesLength = bufferStream.size(); - - servletResponse.setContentLength(bytesLength); +import java.io.IOException; +import java.util.zip.GZIPOutputStream; + +class GZIPResponseStream extends ServletOutputStream { + private ByteArrayOutputStreamEx bufferStream = null; + private GZIPOutputStream gzipOutputStream = null; + private ServletOutputStream servletOutputStream = null; + private HttpServletResponse servletResponse = null; + private boolean closed = false; + + public GZIPResponseStream(HttpServletResponse response) throws IOException { + super(); + + this.servletResponse = response; + this.servletOutputStream = response.getOutputStream(); + bufferStream = new ByteArrayOutputStreamEx(); + gzipOutputStream = new GZIPOutputStream(bufferStream); + } + + @Override + public void close() throws IOException { + if (closed) + throw new IOException("This output stream has already been closed"); + + gzipOutputStream.finish(); + + byte[] bytes = bufferStream.getBuffer(); + int bytesLength = bufferStream.size(); + + servletResponse.setContentLength(bytesLength); servletResponse.addHeader("Content-Encoding", ContentEncodingType.GZIP); servletOutputStream.write(bytes, 0, bytesLength); servletOutputStream.close(); - closed = true; - } - - public boolean isClosed() { - return closed; - } - - @Override - public void flush() throws IOException { - if (closed) - return; // already closed, nothing to do - - gzipOutputStream.flush(); - } - - public void write(int b) throws IOException { - if (closed) - throw new IOException("Cannot write to a closed output stream"); - - gzipOutputStream.write((byte)b); - } - - @Override - public void write(byte[] b) throws IOException { - write(b, 0, b.length); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - if (closed) - throw new IOException("Cannot write to a closed output stream"); - - gzipOutputStream.write(b, off, len); - } - - public void reset() { - // nothing to do - } - - @Override - public boolean isReady() { - return false; - } - - @Override - public void setWriteListener(WriteListener arg0) { - // nothing to do - } + closed = true; + } + + public boolean isClosed() { + return closed; + } + + @Override + public void flush() throws IOException { + if (closed) + return; // already closed, nothing to do + + gzipOutputStream.flush(); + } + + public void write(int b) throws IOException { + if (closed) + throw new IOException("Cannot write to a closed output stream"); + + gzipOutputStream.write((byte) b); + } + + @Override + public void write(byte[] b) throws IOException { + write(b, 0, b.length); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (closed) + throw new IOException("Cannot write to a closed output stream"); + + gzipOutputStream.write(b, off, len); + } + + public void reset() { + // nothing to do + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setWriteListener(WriteListener arg0) { + // nothing to do + } } \ No newline at end of file diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseWrapper.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseWrapper.java index cff92146e1..0e3eeb987e 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseWrapper.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/GZIPResponseWrapper.java @@ -1,86 +1,86 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.api.servlet.filters; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponseWrapper; + import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; -import jakarta.servlet.ServletOutputStream; -import jakarta.servlet.http.HttpServletResponse; -import jakarta.servlet.http.HttpServletResponseWrapper; - class GZIPResponseWrapper extends HttpServletResponseWrapper { - protected HttpServletResponse origResponse; - protected GZIPResponseStream responseStream = null; - protected PrintWriter writer = null; - - public GZIPResponseWrapper(HttpServletResponse response) { - super(response); - origResponse = response; - } - - public GZIPResponseStream createOutputStream() throws IOException { - return new GZIPResponseStream(origResponse); - } - - public void finishResponse() { - try { - if (writer != null) - writer.close(); - else { - if (responseStream != null && !responseStream.isClosed()) - responseStream.close(); - } - } catch (IOException e) { - // do nothing - } - } - - @Override - public void flushBuffer() throws IOException { - if (responseStream != null && !responseStream.isClosed()) - responseStream.flush(); - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - if (writer != null) - throw new IllegalStateException("getWriter() has already been called!"); - - if (responseStream == null) - responseStream = createOutputStream(); - - return (responseStream); - } - - @Override - public PrintWriter getWriter() throws IOException { - if (writer != null) - return (writer); - - if (responseStream != null) - throw new IllegalStateException("getOutputStream() has already been called!"); - - responseStream = createOutputStream(); - writer = new PrintWriter(new OutputStreamWriter(responseStream, StandardCharsets.UTF_8)); - return (writer); - } - - @Override - public void setContentLength(int length) { - // nothing to do - } + protected HttpServletResponse origResponse; + protected GZIPResponseStream responseStream = null; + protected PrintWriter writer = null; + + public GZIPResponseWrapper(HttpServletResponse response) { + super(response); + origResponse = response; + } + + public GZIPResponseStream createOutputStream() throws IOException { + return new GZIPResponseStream(origResponse); + } + + public void finishResponse() { + try { + if (writer != null) + writer.close(); + else { + if (responseStream != null && !responseStream.isClosed()) + responseStream.close(); + } + } catch (IOException e) { + // do nothing + } + } + + @Override + public void flushBuffer() throws IOException { + if (responseStream != null && !responseStream.isClosed()) + responseStream.flush(); + } + + @Override + public ServletOutputStream getOutputStream() throws IOException { + if (writer != null) + throw new IllegalStateException("getWriter() has already been called!"); + + if (responseStream == null) + responseStream = createOutputStream(); + + return (responseStream); + } + + @Override + public PrintWriter getWriter() throws IOException { + if (writer != null) + return (writer); + + if (responseStream != null) + throw new IllegalStateException("getOutputStream() has already been called!"); + + responseStream = createOutputStream(); + writer = new PrintWriter(new OutputStreamWriter(responseStream, StandardCharsets.UTF_8)); + return (writer); + } + + @Override + public void setContentLength(int length) { + // nothing to do + } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/StatusCodeHandlerFilter.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/StatusCodeHandlerFilter.java index a97d4e3d5b..89be9fe43d 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/StatusCodeHandlerFilter.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/filters/StatusCodeHandlerFilter.java @@ -13,50 +13,43 @@ */ package org.heigit.ors.api.servlet.filters; -import java.io.IOException; - -import jakarta.servlet.Filter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.FilterConfig; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; +import jakarta.servlet.*; import jakarta.servlet.http.HttpServletResponse; - import org.heigit.ors.api.servlet.requests.StatusCodeCaptureWrapper; +import java.io.IOException; + public class StatusCodeHandlerFilter implements Filter { - @Override - public void init(FilterConfig filterConfig) throws ServletException { - // do nothing - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException { - StatusCodeCaptureWrapper responseWrapper = new StatusCodeCaptureWrapper((HttpServletResponse)response); - Throwable exception = null; - - try { - chain.doFilter(request, responseWrapper); - } catch (ServletException e) { - exception = e.getRootCause(); - } catch (Throwable e) { // NOSONAR this is an UnhandledExceptionHandler - we need to catch this - exception = e; - } - - if (exception != null) - { - // Add further exception processing if needed - } - - // flush to prevent servlet container to add anymore headers or content - response.flushBuffer(); - } - - @Override - public void destroy() { - // do nothing - } + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // do nothing + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException { + StatusCodeCaptureWrapper responseWrapper = new StatusCodeCaptureWrapper((HttpServletResponse) response); + Throwable exception = null; + + try { + chain.doFilter(request, responseWrapper); + } catch (ServletException e) { + exception = e.getRootCause(); + } catch (Throwable e) { // NOSONAR this is an UnhandledExceptionHandler - we need to catch this + exception = e; + } + + if (exception != null) { + // Add further exception processing if needed + } + + // flush to prevent servlet container to add anymore headers or content + response.flushBuffer(); + } + + @Override + public void destroy() { + // do nothing + } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/listeners/ORSInitContextListener.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/listeners/ORSInitContextListener.java index 4235ad80db..73ee58d245 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/listeners/ORSInitContextListener.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/listeners/ORSInitContextListener.java @@ -20,6 +20,8 @@ */ package org.heigit.ors.api.servlet.listeners; +import jakarta.servlet.ServletContextEvent; +import jakarta.servlet.ServletContextListener; import org.apache.juli.logging.LogFactory; import org.apache.log4j.Logger; import org.heigit.ors.api.EngineProperties; @@ -28,9 +30,6 @@ import org.heigit.ors.routing.RoutingProfileManager; import org.heigit.ors.routing.RoutingProfileManagerStatus; import org.heigit.ors.util.FormatUtility; - -import jakarta.servlet.ServletContextEvent; -import jakarta.servlet.ServletContextListener; import org.heigit.ors.util.StringUtility; import static org.heigit.ors.api.ORSEnvironmentPostProcessor.ORS_CONFIG_LOCATION_ENV; diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/ByteStreamResponseWrapper.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/ByteStreamResponseWrapper.java index 15965e8faa..e0b22280cd 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/ByteStreamResponseWrapper.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/ByteStreamResponseWrapper.java @@ -13,145 +13,139 @@ */ package org.heigit.ors.api.servlet.requests; -import java.io.ByteArrayOutputStream; -import java.io.PrintWriter; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.WriteListener; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponseWrapper; + +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.io.PrintWriter; -public class ByteStreamResponseWrapper extends HttpServletResponseWrapper -{ +public class ByteStreamResponseWrapper extends HttpServletResponseWrapper { private ByteArrayOutputStream byteStream; - public ByteStreamResponseWrapper(HttpServletResponse response) - { + public ByteStreamResponseWrapper(HttpServletResponse response) { super(response); } @Override - public ServletOutputStream getOutputStream() - { + public ServletOutputStream getOutputStream() { ServletOutputStreamImpl outputStream = null; - this.byteStream = (null == this.byteStream) - ? new ByteArrayOutputStream() : this.byteStream; + this.byteStream = (null == this.byteStream) + ? new ByteArrayOutputStream() : this.byteStream; outputStream = new ServletOutputStreamImpl(this.byteStream); return (outputStream); } @Override - public PrintWriter getWriter() - { + public PrintWriter getWriter() { PrintWriter printWriter = null; - this.byteStream = (null == this.byteStream) - ? new ByteArrayOutputStream() : this.byteStream; + this.byteStream = (null == this.byteStream) + ? new ByteArrayOutputStream() : this.byteStream; printWriter = new PrintWriter(this.byteStream); return (printWriter); } @Override - public String toString() - { + public String toString() { return ((null == this.byteStream) ? null : this.byteStream.toString()); } - public byte[] toBytes() - { + public byte[] toBytes() { return ((null == this.byteStream) ? null : this.byteStream.toByteArray()); } - public static class ServletOutputStreamImpl extends ServletOutputStream { - private final OutputStream outputStream; - private byte[] buffer; - - public ServletOutputStreamImpl(OutputStream out) { - outputStream = out; - } - - - /** - * Writes a byte to the output stream. - */ - public final void write(int b) throws IOException { - outputStream.write(b); - } - - /** - * Writes a byte buffer to the output stream. - */ - @Override - public final void write(byte[] buf, int offset, int len) - throws IOException { - outputStream.write(buf, offset, len); - } - - /** - * Prints a string to the stream. Note, this method does not properly - * handle character encoding. - * - * @param s - * the string to write. - */ - @Override - public void print(String s) throws IOException { - if (s == null) - s = "null"; - - try (OutputStream out = outputStream) { - int length = s.length(); - - if (buffer == null) - buffer = new byte[128]; - - byte[] localBuffer = this.buffer; - - // server/0810 - int offset = 0; - - while (length > 0) { - int sublen = localBuffer.length; - if (length < sublen) - sublen = length; - - for (int i = 0; i < sublen; i++) { - localBuffer[i] = (byte) s.charAt(i + offset); - } - - out.write(localBuffer, 0, sublen); - - length -= sublen; - offset += sublen; - } - } - } - - @Override - public final void flush() throws IOException { - outputStream.flush(); - } - - public String toString() { - return getClass().getSimpleName() + "[" + outputStream + "]"; - } - - - @Override - public boolean isReady() { - return true; - } - - - @Override - public void setWriteListener(WriteListener writeListener) { - // do nothing - } - } + public static class ServletOutputStreamImpl extends ServletOutputStream { + private final OutputStream outputStream; + private byte[] buffer; + + public ServletOutputStreamImpl(OutputStream out) { + outputStream = out; + } + + + /** + * Writes a byte to the output stream. + */ + public final void write(int b) throws IOException { + outputStream.write(b); + } + + /** + * Writes a byte buffer to the output stream. + */ + @Override + public final void write(byte[] buf, int offset, int len) + throws IOException { + outputStream.write(buf, offset, len); + } + + /** + * Prints a string to the stream. Note, this method does not properly + * handle character encoding. + * + * @param s the string to write. + */ + @Override + public void print(String s) throws IOException { + if (s == null) + s = "null"; + + try (OutputStream out = outputStream) { + int length = s.length(); + + if (buffer == null) + buffer = new byte[128]; + + byte[] localBuffer = this.buffer; + + // server/0810 + int offset = 0; + + while (length > 0) { + int sublen = localBuffer.length; + if (length < sublen) + sublen = length; + + for (int i = 0; i < sublen; i++) { + localBuffer[i] = (byte) s.charAt(i + offset); + } + + out.write(localBuffer, 0, sublen); + + length -= sublen; + offset += sublen; + } + } + } + + @Override + public final void flush() throws IOException { + outputStream.flush(); + } + + public String toString() { + return getClass().getSimpleName() + "[" + outputStream + "]"; + } + + + @Override + public boolean isReady() { + return true; + } + + + @Override + public void setWriteListener(WriteListener writeListener) { + // do nothing + } + } } diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/MultiReadHttpServletRequest.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/MultiReadHttpServletRequest.java index 7001d757ac..89a638614f 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/MultiReadHttpServletRequest.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/MultiReadHttpServletRequest.java @@ -1,27 +1,26 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.api.servlet.requests; -import jakarta.servlet.http.HttpServletRequestWrapper; -import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.ReadListener; import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import org.heigit.ors.util.StreamUtility; import java.io.*; -import org.heigit.ors.util.StreamUtility; - public class MultiReadHttpServletRequest extends HttpServletRequestWrapper { private final byte[] body; @@ -41,7 +40,7 @@ public ServletInputStream getInputStream() throws IOException { @Override public BufferedReader getReader() throws IOException { String enc = getCharacterEncoding(); - if(enc == null) enc = "UTF-8"; + if (enc == null) enc = "UTF-8"; return new BufferedReader(new InputStreamReader(getInputStream(), enc)); } @@ -72,20 +71,20 @@ public synchronized void reset() throws IOException { throw new IOException("mark/reset not supported"); } - @Override - public boolean isFinished() { - return false; - } + @Override + public boolean isFinished() { + return false; + } - @Override - public boolean isReady() { - return true; - } + @Override + public boolean isReady() { + return true; + } - @Override - public void setReadListener(ReadListener readListener) { + @Override + public void setReadListener(ReadListener readListener) { // do nothing - } + } } } \ No newline at end of file diff --git a/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/StatusCodeCaptureWrapper.java b/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/StatusCodeCaptureWrapper.java index 43a7e49327..8b95a2acbd 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/StatusCodeCaptureWrapper.java +++ b/ors-api/src/main/java/org/heigit/ors/api/servlet/requests/StatusCodeCaptureWrapper.java @@ -20,7 +20,7 @@ * Suppresses calls to sendError() and uses setStatus() instead to avoid sending a html error page. * See {@link jakarta.servlet.http.HttpServletResponse#sendError(int)} */ -public class StatusCodeCaptureWrapper extends HttpServletResponseWrapper { +public class StatusCodeCaptureWrapper extends HttpServletResponseWrapper { public StatusCodeCaptureWrapper(HttpServletResponse response) { super(response); diff --git a/ors-api/src/main/java/org/heigit/ors/api/util/AppConfigMigration.java b/ors-api/src/main/java/org/heigit/ors/api/util/AppConfigMigration.java index 76dc0d147d..2b0fafaedb 100644 --- a/ors-api/src/main/java/org/heigit/ors/api/util/AppConfigMigration.java +++ b/ors-api/src/main/java/org/heigit/ors/api/util/AppConfigMigration.java @@ -20,7 +20,7 @@ public class AppConfigMigration { public static final String PARAM_STATISTICS_PROVIDERS = "statistics_providers."; public static final String SERVICE_NAME_MATRIX = "matrix"; public static final String SERVICE_NAME_ROUTING = "routing"; - private static AppConfig config = AppConfig.getGlobal(); + private static final AppConfig config = AppConfig.getGlobal(); private AppConfigMigration() { } @@ -235,8 +235,7 @@ private static int parseProfileValues(List params, MapSystem.getProperty("java.version"). * - */ - public static final String JAVA_VERSION = System.getProperty("java.version"); - /** - * The value of System.getProperty("os.name"). * - */ - public static final String OS_NAME = System.getProperty("os.name", "unknown"); - /** - * True iff running on Linux. - */ - public static final boolean LINUX = OS_NAME.startsWith("Linux"); - /** - * True iff running on Windows. - */ - public static final boolean WINDOWS = OS_NAME.startsWith("Windows"); - /** - * True iff running on SunOS. - */ - public static final boolean SUN_OS = OS_NAME.startsWith("SunOS"); - /** - * True iff running on Mac OS X - */ - public static final boolean MAC_OS_X = OS_NAME.startsWith("Mac OS X"); - public static final String OS_ARCH = System.getProperty("os.arch"); - public static final String OS_VERSION = System.getProperty("os.version"); - public static final String JAVA_VENDOR = System.getProperty("java.vendor"); + private static final Logger LOGGER = Logger.getLogger(AppInfo.class.getName()); + /** + * The value of System.getProperty("java.version"). * + */ + public static final String JAVA_VERSION = System.getProperty("java.version"); + /** + * The value of System.getProperty("os.name"). * + */ + public static final String OS_NAME = System.getProperty("os.name", "unknown"); + /** + * True iff running on Linux. + */ + public static final boolean LINUX = OS_NAME.startsWith("Linux"); + /** + * True iff running on Windows. + */ + public static final boolean WINDOWS = OS_NAME.startsWith("Windows"); + /** + * True iff running on SunOS. + */ + public static final boolean SUN_OS = OS_NAME.startsWith("SunOS"); + /** + * True iff running on Mac OS X + */ + public static final boolean MAC_OS_X = OS_NAME.startsWith("Mac OS X"); + public static final String OS_ARCH = System.getProperty("os.arch"); + public static final String OS_VERSION = System.getProperty("os.version"); + public static final String JAVA_VENDOR = System.getProperty("java.vendor"); - public static final String VERSION; - public static final String BUILD_DATE; - public static final boolean SNAPSHOT; + public static final String VERSION; + public static final String BUILD_DATE; + public static final boolean SNAPSHOT; - static { - String version = "0.0"; - Properties prop = new Properties(); + static { + String version = "0.0"; + Properties prop = new Properties(); - try (InputStream in = Thread.currentThread().getContextClassLoader().getResource("version.properties").openStream()) { - prop.load(in); - version = prop.getProperty("version"); - } catch (Exception e) { - LOGGER.error("Initialization ERROR: cannot read version!? " + e.getMessage()); - } + try (InputStream in = Thread.currentThread().getContextClassLoader().getResource("version.properties").openStream()) { + prop.load(in); + version = prop.getProperty("version"); + } catch (Exception e) { + LOGGER.error("Initialization ERROR: cannot read version!? " + e.getMessage()); + } - int indexM = version.indexOf('-'); - if ("${project.version}".equals(version)) { - VERSION = "0.0"; - SNAPSHOT = true; - LOGGER.error("OpenRouteService Initialization WARNING: maven did not preprocess the version file! Do not use the jar for a release!"); - } else if ("0.0".equals(version)) { - VERSION = "0.0"; - SNAPSHOT = true; - LOGGER.error("OpenRouteService Initialization WARNING: cannot get version!?"); - } else { - String tmp = version; - // throw away the "-SNAPSHOT" - if (indexM >= 0) - tmp = version.substring(0, indexM); + int indexM = version.indexOf('-'); + if ("${project.version}".equals(version)) { + VERSION = "0.0"; + SNAPSHOT = true; + LOGGER.error("OpenRouteService Initialization WARNING: maven did not preprocess the version file! Do not use the jar for a release!"); + } else if ("0.0".equals(version)) { + VERSION = "0.0"; + SNAPSHOT = true; + LOGGER.error("OpenRouteService Initialization WARNING: cannot get version!?"); + } else { + String tmp = version; + // throw away the "-SNAPSHOT" + if (indexM >= 0) + tmp = version.substring(0, indexM); - SNAPSHOT = version.toLowerCase().contains("-snapshot"); - VERSION = tmp; - } + SNAPSHOT = version.toLowerCase().contains("-snapshot"); + VERSION = tmp; + } - String buildDate = ""; - try { - buildDate = prop.getProperty("buildDate"); - } catch (Exception e) { - LOGGER.error(e); - } + String buildDate = ""; + try { + buildDate = prop.getProperty("buildDate"); + } catch (Exception e) { + LOGGER.error(e); + } - BUILD_DATE = buildDate; - } + BUILD_DATE = buildDate; + } - private AppInfo() {} + private AppInfo() { + } - public static JSONObject getEngineInfo() { - JSONObject json = new JSONObject(true); - json.put("version", VERSION); - json.put("build_date", BUILD_DATE); - return json; - } + public static JSONObject getEngineInfo() { + JSONObject json = new JSONObject(true); + json.put("version", VERSION); + json.put("build_date", BUILD_DATE); + return json; + } } diff --git a/ors-api/src/main/resources/log4j.properties b/ors-api/src/main/resources/log4j.properties index 1fc6b1e4d5..352d9b5154 100644 --- a/ors-api/src/main/resources/log4j.properties +++ b/ors-api/src/main/resources/log4j.properties @@ -1,11 +1,9 @@ # Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 - # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d{dd MMM HH:mm:ss} %p [%c{2}] - %m%n - log4j.logger.org.heigit=WARN log4j.logger.org.apache=WARN log4j.logger.com.graphhopper=WARN diff --git a/ors-api/src/main/resources/logs/DEBUG_LOGGING.json b/ors-api/src/main/resources/logs/DEBUG_LOGGING.json index 61ed20298f..174cb26c9d 100644 --- a/ors-api/src/main/resources/logs/DEBUG_LOGGING.json +++ b/ors-api/src/main/resources/logs/DEBUG_LOGGING.json @@ -17,7 +17,10 @@ "PatternLayout": { "pattern": "%d %p [%c{2}] - %m%n" }, - "TimeBasedTriggeringPolicy": { "interval": "1", "modulate": "true" } + "TimeBasedTriggeringPolicy": { + "interval": "1", + "modulate": "true" + } } }, "loggers": { diff --git a/ors-api/src/main/resources/logs/DEFAULT_LOGGING.json b/ors-api/src/main/resources/logs/DEFAULT_LOGGING.json index 34516c5a39..4227200350 100644 --- a/ors-api/src/main/resources/logs/DEFAULT_LOGGING.json +++ b/ors-api/src/main/resources/logs/DEFAULT_LOGGING.json @@ -17,7 +17,10 @@ "PatternLayout": { "pattern": "%d %p [%c{2}] - %m%n" }, - "TimeBasedTriggeringPolicy": { "interval": "1", "modulate": "true" } + "TimeBasedTriggeringPolicy": { + "interval": "1", + "modulate": "true" + } } }, "loggers": { diff --git a/ors-api/src/main/resources/logs/PRODUCTION_LOGGING.json b/ors-api/src/main/resources/logs/PRODUCTION_LOGGING.json index 57e092794d..80035e81bc 100644 --- a/ors-api/src/main/resources/logs/PRODUCTION_LOGGING.json +++ b/ors-api/src/main/resources/logs/PRODUCTION_LOGGING.json @@ -17,7 +17,10 @@ "PatternLayout": { "pattern": "%d %p [%c{2}] - %m%n" }, - "TimeBasedTriggeringPolicy": { "interval": "1", "modulate": "true" } + "TimeBasedTriggeringPolicy": { + "interval": "1", + "modulate": "true" + } } }, "loggers": { diff --git a/ors-api/src/test/java/org/heigit/ors/api/requests/isochrones/IsochronesRequestTest.java b/ors-api/src/test/java/org/heigit/ors/api/requests/isochrones/IsochronesRequestTest.java index 8091292c63..4047e52c18 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/requests/isochrones/IsochronesRequestTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/requests/isochrones/IsochronesRequestTest.java @@ -1,8 +1,8 @@ package org.heigit.ors.api.requests.isochrones; -import org.heigit.ors.routing.APIEnums; import org.heigit.ors.api.requests.routing.RouteRequestOptions; import org.heigit.ors.exceptions.ParameterValueException; +import org.heigit.ors.routing.APIEnums; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/ors-api/src/test/java/org/heigit/ors/api/requests/matrix/MatrixRequestTest.java b/ors-api/src/test/java/org/heigit/ors/api/requests/matrix/MatrixRequestTest.java index b6b1f9ddec..e5e45fdb60 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/requests/matrix/MatrixRequestTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/requests/matrix/MatrixRequestTest.java @@ -163,9 +163,9 @@ void setAndGetDestinationsTest() throws ParameterValueException { matrixLocationsRequest = new MatrixRequest(bareCoordinates, endpointsProperties); matrixLocationsListRequest = new MatrixRequest(listOfBareCoordinatesList); matrixLocationsRequest.setDestinations(new String[]{"all"}); - matrixLocationsListRequest.setDestinations(new String[]{"1","2"}); + matrixLocationsListRequest.setDestinations(new String[]{"1", "2"}); assertArrayEquals(new String[]{"all"}, matrixLocationsRequest.getDestinations()); - assertArrayEquals(new String[]{"1","2"}, matrixLocationsListRequest.getDestinations()); + assertArrayEquals(new String[]{"1", "2"}, matrixLocationsListRequest.getDestinations()); } @Test diff --git a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/APIEnumsTest.java b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/APIEnumsTest.java index cd476d4676..6cec201ed3 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/APIEnumsTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/APIEnumsTest.java @@ -1,7 +1,7 @@ package org.heigit.ors.api.requests.routing; -import org.heigit.ors.routing.APIEnums; import org.heigit.ors.exceptions.ParameterValueException; +import org.heigit.ors.routing.APIEnums; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; diff --git a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutesTest.java b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutesTest.java index 5d7aaa2fbc..f06e055e37 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutesTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestAlternativeRoutesTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + import static org.junit.jupiter.api.Assertions.*; class RouteRequestAlternativeRoutesTest { diff --git a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptionsTest.java b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptionsTest.java index 8fdcf7920c..168803aa7d 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptionsTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestRoundTripOptionsTest.java @@ -18,7 +18,7 @@ void testSetLength() { assertFalse(options.hasLength()); options.setLength(123.4f); assertTrue(options.hasLength()); - assertEquals((Float)123.4f, options.getLength()); + assertEquals((Float) 123.4f, options.getLength()); } @Test diff --git a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestTest.java b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestTest.java index d3c2506645..24bda767ba 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/requests/routing/RouteRequestTest.java @@ -15,8 +15,8 @@ package org.heigit.ors.api.requests.routing; -import org.heigit.ors.routing.APIEnums; import org.heigit.ors.exceptions.ParameterValueException; +import org.heigit.ors.routing.APIEnums; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; @@ -31,7 +31,7 @@ class RouteRequestTest { @BeforeEach void setup() throws ParameterValueException { - request = new RouteRequest(new Double[][] {new Double[] {1.0,1.0}, new Double[] {2.0,2.0}}); + request = new RouteRequest(new Double[][]{new Double[]{1.0, 1.0}, new Double[]{2.0, 2.0}}); } @Test @@ -67,19 +67,19 @@ void testHasIncludeRoundaboutExitInfo() { @Test void testHasAttributes() { - request.setAttributes(new APIEnums.Attributes[] {APIEnums.Attributes.AVERAGE_SPEED}); + request.setAttributes(new APIEnums.Attributes[]{APIEnums.Attributes.AVERAGE_SPEED}); assertTrue(request.hasAttributes()); } @Test void testHasMaximumSearchRadii() { - request.setMaximumSearchRadii(new Double[] { 1.0 }); + request.setMaximumSearchRadii(new Double[]{1.0}); assertTrue(request.hasMaximumSearchRadii()); } @Test void testHasBearings() { - request.setBearings(new Double[][] {new Double[] {0.0, 90.0}}); + request.setBearings(new Double[][]{new Double[]{0.0, 90.0}}); assertTrue(request.hasBearings()); } @@ -103,7 +103,7 @@ void testHasUseContractionHierarchies() { @Test void testHasExtraInfo() { - request.setExtraInfo(new APIEnums.ExtraInfo[] { APIEnums.ExtraInfo.SURFACE }); + request.setExtraInfo(new APIEnums.ExtraInfo[]{APIEnums.ExtraInfo.SURFACE}); assertTrue(request.hasExtraInfo()); } diff --git a/ors-api/src/test/java/org/heigit/ors/api/responses/matrix/json/JSONBasedIndividualMatrixResponseTest.java b/ors-api/src/test/java/org/heigit/ors/api/responses/matrix/json/JSONBasedIndividualMatrixResponseTest.java index caab56e1ca..db4cbbbced 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/responses/matrix/json/JSONBasedIndividualMatrixResponseTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/responses/matrix/json/JSONBasedIndividualMatrixResponseTest.java @@ -1,11 +1,11 @@ package org.heigit.ors.api.responses.matrix.json; -import org.heigit.ors.routing.APIEnums; import org.heigit.ors.api.requests.matrix.MatrixRequest; import org.heigit.ors.api.requests.matrix.MatrixRequestEnums; import org.heigit.ors.matrix.MatrixMetricsType; import org.heigit.ors.matrix.MatrixResult; import org.heigit.ors.matrix.ResolvedLocation; +import org.heigit.ors.routing.APIEnums; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; @@ -26,9 +26,9 @@ class JSONBasedIndividualMatrixResponseTest { @BeforeEach void setUp() { matrixRequest.setResolveLocations(true); - matrixRequest.setMetrics(new MatrixRequestEnums.Metrics[] {MatrixRequestEnums.Metrics.DISTANCE}); - matrixRequest.setSources(new String[] {"all"}); - matrixRequest.setDestinations(new String[] {"all"}); + matrixRequest.setMetrics(new MatrixRequestEnums.Metrics[]{MatrixRequestEnums.Metrics.DISTANCE}); + matrixRequest.setSources(new String[]{"all"}); + matrixRequest.setDestinations(new String[]{"all"}); matrixRequest.setProfile(APIEnums.Profile.CYCLING_REGULAR); matrixRequest.setUnits(APIEnums.Units.METRES); jsonBasedIndividualMatrixResponse = new JSONBasedIndividualMatrixResponse(matrixRequest); diff --git a/ors-api/src/test/java/org/heigit/ors/api/responses/routing/boundingbox/BoundingBoxFactoryTest.java b/ors-api/src/test/java/org/heigit/ors/api/responses/routing/boundingbox/BoundingBoxFactoryTest.java index 56712808ff..edaa72d7c5 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/responses/routing/boundingbox/BoundingBoxFactoryTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/responses/routing/boundingbox/BoundingBoxFactoryTest.java @@ -1,13 +1,13 @@ package org.heigit.ors.api.responses.routing.boundingbox; import com.graphhopper.util.shapes.BBox; -import org.heigit.ors.routing.APIEnums; import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.responses.common.boundingbox.BoundingBox; import org.heigit.ors.api.responses.common.boundingbox.BoundingBoxFactory; import org.heigit.ors.api.responses.routing.gpx.GPXBounds; import org.heigit.ors.api.responses.routing.json.JSON3DBoundingBox; import org.heigit.ors.api.responses.routing.json.JSONBoundingBox; +import org.heigit.ors.routing.APIEnums; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,12 +27,12 @@ void testCorrectTypeCreated() throws Exception { coord2.add(38.6);*/ Double[][] coords = new Double[2][2]; - coords[0] = new Double[] {24.5,39.2}; - coords[1] = new Double[] {27.4,38.6}; + coords[0] = new Double[]{24.5, 39.2}; + coords[1] = new Double[]{27.4, 38.6}; RouteRequest request = new RouteRequest(coords); - BBox bbox = new BBox(1,2,3,4,5,6); + BBox bbox = new BBox(1, 2, 3, 4, 5, 6); request.setUseElevation(true); request.setResponseType(APIEnums.RouteResponseType.JSON); diff --git a/ors-api/src/test/java/org/heigit/ors/api/services/APIServiceTest.java b/ors-api/src/test/java/org/heigit/ors/api/services/APIServiceTest.java index 3515876f8d..d0c568ae8c 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/services/APIServiceTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/services/APIServiceTest.java @@ -30,7 +30,7 @@ void setUp() throws Exception { @Test void convertAPIEnumListToStrings() { - String[] strVals = ApiService.convertAPIEnumListToStrings(new APIEnums.ExtraInfo[] {APIEnums.ExtraInfo.STEEPNESS, APIEnums.ExtraInfo.SURFACE}); + String[] strVals = ApiService.convertAPIEnumListToStrings(new APIEnums.ExtraInfo[]{APIEnums.ExtraInfo.STEEPNESS, APIEnums.ExtraInfo.SURFACE}); assertEquals(2, strVals.length); assertEquals("steepness", strVals[0]); assertEquals("surface", strVals[1]); @@ -98,8 +98,8 @@ void convertAvoidAreas() throws StatusCodeException { polys2.add(0, poly); coords = new JSONArray(); - coords.add(0,polys1); - coords.add(0,polys2); + coords.add(0, polys1); + coords.add(0, polys2); geomJSONMulti.put("coordinates", coords); @@ -161,7 +161,7 @@ private JSONArray generateGeoJSONPolyCoords() { @Test void convertFeatureTypes() throws UnknownParameterValueException, IncompatibleParameterException { - APIEnums.AvoidFeatures[] avoids = new APIEnums.AvoidFeatures[] { APIEnums.AvoidFeatures.FERRIES, APIEnums.AvoidFeatures.FORDS }; + APIEnums.AvoidFeatures[] avoids = new APIEnums.AvoidFeatures[]{APIEnums.AvoidFeatures.FERRIES, APIEnums.AvoidFeatures.FORDS}; int converted = ApiService.convertFeatureTypes(avoids, 1); assertEquals(24, converted); } @@ -186,7 +186,7 @@ void convertParameters() throws StatusCodeException { ProfileParameters generatedParams = apiService.convertParameters(opts, 2); - assertEquals(10.0f, ((VehicleParameters)generatedParams).getHeight(), 0.0); + assertEquals(10.0f, ((VehicleParameters) generatedParams).getHeight(), 0.0); } @Test @@ -195,6 +195,6 @@ void convertSpecificProfileParameters() { restrictions.setHeight(10.0f); ProfileParameters params = apiService.convertSpecificProfileParameters(2, restrictions, APIEnums.VehicleType.HGV); assertTrue(params instanceof VehicleParameters); - assertEquals(10.0f, ((VehicleParameters)params).getHeight(), 0.0); + assertEquals(10.0f, ((VehicleParameters) params).getHeight(), 0.0); } } diff --git a/ors-api/src/test/java/org/heigit/ors/api/services/IsochronesServiceTest.java b/ors-api/src/test/java/org/heigit/ors/api/services/IsochronesServiceTest.java index b0cf3f8774..b4ef9f9639 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/services/IsochronesServiceTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/services/IsochronesServiceTest.java @@ -30,7 +30,6 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest @ActiveProfiles("unittest") @@ -52,10 +51,10 @@ private JSONObject constructGeoJson() { JSONObject geoJsonPolygon = new JSONObject(); geoJsonPolygon.put("type", "Polygon"); JSONArray coordsArray = new JSONArray(); - coordsArray.add(new Double[] { 49.0, 8.0}); - coordsArray.add(new Double[] { 49.005, 8.01}); - coordsArray.add(new Double[] { 49.01, 8.0}); - coordsArray.add(new Double[] { 49.0, 8.0}); + coordsArray.add(new Double[]{49.0, 8.0}); + coordsArray.add(new Double[]{49.005, 8.01}); + coordsArray.add(new Double[]{49.01, 8.0}); + coordsArray.add(new Double[]{49.0, 8.0}); JSONArray coordinates = new JSONArray(); coordinates.add(coordsArray); diff --git a/ors-api/src/test/java/org/heigit/ors/api/services/MatrixServiceTest.java b/ors-api/src/test/java/org/heigit/ors/api/services/MatrixServiceTest.java index 1565111a11..6377e173a1 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/services/MatrixServiceTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/services/MatrixServiceTest.java @@ -1,7 +1,6 @@ package org.heigit.ors.api.services; import org.heigit.ors.api.EndpointsProperties; -import org.heigit.ors.api.requests.common.APIRequest; import org.heigit.ors.api.requests.matrix.MatrixRequestEnums; import org.heigit.ors.api.util.HelperFunctions; import org.heigit.ors.common.DistanceUnit; @@ -348,9 +347,9 @@ void convertWrongIndexToLocationsTest() { @Test void convertUnitsTest() throws ParameterValueException { - assertEquals(DistanceUnit.METERS, matrixService.convertUnits(APIEnums.Units.METRES)); - assertEquals(DistanceUnit.KILOMETERS, matrixService.convertUnits(APIEnums.Units.KILOMETRES)); - assertEquals(DistanceUnit.MILES, matrixService.convertUnits(APIEnums.Units.MILES)); + assertEquals(DistanceUnit.METERS, ApiService.convertUnits(APIEnums.Units.METRES)); + assertEquals(DistanceUnit.KILOMETERS, ApiService.convertUnits(APIEnums.Units.KILOMETRES)); + assertEquals(DistanceUnit.MILES, ApiService.convertUnits(APIEnums.Units.MILES)); } @Test diff --git a/ors-api/src/test/java/org/heigit/ors/api/services/RoutingServiceTest.java b/ors-api/src/test/java/org/heigit/ors/api/services/RoutingServiceTest.java index 275ba13a2a..969c9de991 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/services/RoutingServiceTest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/services/RoutingServiceTest.java @@ -18,7 +18,6 @@ import org.heigit.ors.api.EndpointsProperties; import org.heigit.ors.api.requests.routing.*; import org.heigit.ors.common.DistanceUnit; -import org.heigit.ors.config.AppConfig; import org.heigit.ors.exceptions.*; import org.heigit.ors.routing.*; import org.heigit.ors.routing.graphhopper.extensions.VehicleLoadCharacteristicsFlags; @@ -47,8 +46,10 @@ @ActiveProfiles("unittest") class RoutingServiceTest { - @Autowired RoutingService routingService; - @Autowired EndpointsProperties endpointsProperties = new EndpointsProperties(); + @Autowired + RoutingService routingService; + @Autowired + EndpointsProperties endpointsProperties = new EndpointsProperties(); RouteRequest request; private RequestProfileParamsRestrictions vehicleParams; private RequestProfileParamsRestrictions wheelchairParams; @@ -64,10 +65,10 @@ private JSONObject constructGeoJson() { JSONObject geoJsonPolygon = new JSONObject(); geoJsonPolygon.put("type", "Polygon"); JSONArray coordsArray = new JSONArray(); - coordsArray.add(new Double[] { 49.0, 8.0}); - coordsArray.add(new Double[] { 49.005, 8.01}); - coordsArray.add(new Double[] { 49.01, 8.0}); - coordsArray.add(new Double[] { 49.0, 8.0}); + coordsArray.add(new Double[]{49.0, 8.0}); + coordsArray.add(new Double[]{49.005, 8.01}); + coordsArray.add(new Double[]{49.01, 8.0}); + coordsArray.add(new Double[]{49.0, 8.0}); JSONArray coordinates = new JSONArray(); coordinates.add(coordsArray); @@ -97,16 +98,16 @@ void init() throws Exception { coords.add(coord3);*/ Double[][] coords = new Double[3][2]; - coords[0] = new Double[] {24.5,39.2}; - coords[1] = new Double[] {27.4,38.6}; - coords[2] = new Double[] {26.5,37.2}; + coords[0] = new Double[]{24.5, 39.2}; + coords[1] = new Double[]{27.4, 38.6}; + coords[2] = new Double[]{26.5, 37.2}; request = new RouteRequest(coords); request.setProfile(APIEnums.Profile.DRIVING_CAR); - request.setAttributes(new APIEnums.Attributes[] { APIEnums.Attributes.AVERAGE_SPEED, APIEnums.Attributes.DETOUR_FACTOR}); + request.setAttributes(new APIEnums.Attributes[]{APIEnums.Attributes.AVERAGE_SPEED, APIEnums.Attributes.DETOUR_FACTOR}); request.setContinueStraightAtWaypoints(true); - request.setExtraInfo(new APIEnums.ExtraInfo[] { APIEnums.ExtraInfo.OSM_ID}); + request.setExtraInfo(new APIEnums.ExtraInfo[]{APIEnums.ExtraInfo.OSM_ID}); request.setIncludeGeometry(true); request.setIncludeInstructionsInResponse(true); request.setIncludeRoundaboutExitInfo(true); @@ -121,8 +122,8 @@ void init() throws Exception { RouteRequestOptions options = new RouteRequestOptions(); options.setAvoidBorders(APIEnums.AvoidBorders.CONTROLLED); - options.setAvoidCountries(new String[] { "115" }); - options.setAvoidFeatures(new APIEnums.AvoidFeatures[] {APIEnums.AvoidFeatures.FORDS}); + options.setAvoidCountries(new String[]{"115"}); + options.setAvoidFeatures(new APIEnums.AvoidFeatures[]{APIEnums.AvoidFeatures.FORDS}); options.setAvoidPolygonFeatures(geoJsonPolygon); @@ -166,7 +167,7 @@ void convertRouteRequestTest() throws Exception { assertEquals(3, routingRequest.getCoordinates().length); assertEquals(RoutingProfileType.getFromString("driving-car"), routingRequest.getSearchParameters().getProfileType()); - assertArrayEquals(new String[] {"avgspeed", "detourfactor"}, routingRequest.getAttributes()); + assertArrayEquals(new String[]{"avgspeed", "detourfactor"}, routingRequest.getAttributes()); assertTrue(routingRequest.getContinueStraight()); @@ -186,7 +187,7 @@ void convertRouteRequestTest() throws Exception { assertTrue(routingRequest.getSearchParameters().hasFlexibleMode()); assertEquals(BordersExtractor.Avoid.CONTROLLED, routingRequest.getSearchParameters().getAvoidBorders()); - assertArrayEquals(new int[] {115}, routingRequest.getSearchParameters().getAvoidCountries()); + assertArrayEquals(new int[]{115}, routingRequest.getSearchParameters().getAvoidCountries()); assertEquals(AvoidFeatureFlags.getFromString("fords"), routingRequest.getSearchParameters().getAvoidFeatureTypes()); checkPolygon(routingRequest.getSearchParameters().getAvoidAreas(), geoJsonPolygon); @@ -243,7 +244,7 @@ void TestWheelchairParameters() throws Exception { @Test void testBearings() throws StatusCodeException { - request.setBearings(new Double[][] {{10.0,10.0},{260.0, 90.0},{45.0, 30.0}}); + request.setBearings(new Double[][]{{10.0, 10.0}, {260.0, 90.0}, {45.0, 30.0}}); RoutingRequest routingRequest = routingService.convertRouteRequest(request); @@ -255,7 +256,7 @@ void testBearings() throws StatusCodeException { @Test void skippedBearingTest() throws Exception { - request.setBearings(new Double[][] {{120.0, 90.0}, { , }, {90.0, 30.0}}); + request.setBearings(new Double[][]{{120.0, 90.0}, {,}, {90.0, 30.0}}); RoutingRequest routingRequest = routingService.convertRouteRequest(request); @@ -272,10 +273,10 @@ void invalidBearingLength() throws Exception { @Test void testRadius() throws StatusCodeException { - request.setMaximumSearchRadii(new Double[] { 50.0, 20.0, 100.0}); + request.setMaximumSearchRadii(new Double[]{50.0, 20.0, 100.0}); RoutingRequest routingRequest = routingService.convertRouteRequest(request); - assertTrue(Arrays.equals(new double[] { 50.0, 20.0, 100.0 }, routingRequest.getSearchParameters().getMaximumRadiuses())); + assertArrayEquals(new double[]{50.0, 20.0, 100.0}, routingRequest.getSearchParameters().getMaximumRadiuses()); } @Test @@ -291,7 +292,7 @@ void testSingleRadius() throws Exception { request.setMaximumSearchRadii(new Double[]{50d}); RoutingRequest routingRequest = routingService.convertRouteRequest(request); - assertTrue(Arrays.equals(new double[] {50.0, 50.0, 50.0}, routingRequest.getSearchParameters().getMaximumRadiuses())); + assertArrayEquals(new double[]{50.0, 50.0, 50.0}, routingRequest.getSearchParameters().getMaximumRadiuses()); } @Test @@ -303,7 +304,7 @@ void onlySetOptimizationToFalse() throws Exception { } @Test - void vehicleType() throws Exception{ + void vehicleType() throws Exception { RouteRequestOptions opts = request.getRouteOptions(); opts.setVehicleType(APIEnums.VehicleType.AGRICULTURAL); @@ -382,8 +383,8 @@ void skipSegmentsValueTooSmall() throws StatusCodeException { @Test void convertRouteRequestTestForAlternativeRoutes() throws Exception { Double[][] coords = new Double[2][2]; - coords[0] = new Double[] {24.5,39.2}; - coords[1] = new Double[] {26.5,37.2}; + coords[0] = new Double[]{24.5, 39.2}; + coords[1] = new Double[]{26.5, 37.2}; RouteRequest arRequest = new RouteRequest(coords); arRequest.setProfile(APIEnums.Profile.DRIVING_CAR); @@ -446,8 +447,8 @@ void testSingleCoordinateValidForRoundTrip() throws StatusCodeException { private void checkPolygon(Polygon[] requestPolys, JSONObject apiPolys) { assertEquals(1, requestPolys.length); - JSONArray jsonCoords = (JSONArray)((JSONArray)apiPolys.get("coordinates")).get(0); - for (int i=0; i>} with fake coordinates. * The size depends on maximumSize. * - * @param maximumSize number of maximum coordinates in the {@link List>} + * @param maximumSize number of maximum coordinates in the {@link List>} * @param coordDimension defines the size of the coords 1. only x; 2. x,y; 3. x,y,z * @return {@link List>} */ @@ -81,7 +81,7 @@ public static Double[][] fakeArrayLocations(int maximumSize, int coordDimension) * This function creates a {@link JSONArray} with fake coordinates. * The size depends on maximumSize. * - * @param maximumSize number of maximum coordinates in the {@link JSONArray} + * @param maximumSize number of maximum coordinates in the {@link JSONArray} * @param coordDimension defines the size of the coords 1. only x; 2. x,y; 3. x,y,z * @return {@link JSONArray} */ diff --git a/ors-api/src/test/java/org/heigit/ors/api/util/OpenAPITest.java b/ors-api/src/test/java/org/heigit/ors/api/util/OpenAPITest.java index ee7812c76d..eee4f001a8 100644 --- a/ors-api/src/test/java/org/heigit/ors/api/util/OpenAPITest.java +++ b/ors-api/src/test/java/org/heigit/ors/api/util/OpenAPITest.java @@ -12,7 +12,6 @@ import org.springframework.test.context.ActiveProfiles; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest @ActiveProfiles("unittest") diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/common/ServiceTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/common/ServiceTest.java index f2159017aa..afca343341 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/common/ServiceTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/common/ServiceTest.java @@ -38,58 +38,58 @@ @ExtendWith(InitializeGraphsOnce.class) @ActiveProfiles("test") public abstract class ServiceTest { - private final Map dictUrlParams; - private String endPointName; - private String version; + private final Map dictUrlParams; + private String endPointName; + private String version; - @Autowired - private TestRestTemplate testRestTemplate; + @Autowired + private TestRestTemplate testRestTemplate; - @LocalServerPort - private Integer port; + @LocalServerPort + private Integer port; - @BeforeEach - void setupRestAssured() { - RestAssured.port = port; - RestAssured.baseURI = testRestTemplate.getRootUri(); - } + @BeforeEach + void setupRestAssured() { + RestAssured.port = port; + RestAssured.baseURI = testRestTemplate.getRootUri(); + } - public ServiceTest() { - dictUrlParams = new HashMap<>(); + public ServiceTest() { + dictUrlParams = new HashMap<>(); - Annotation[] annotations = getClass().getAnnotations(); - for(Annotation annotation : annotations){ - if(annotation instanceof EndPointAnnotation epa){ - endPointName = epa.name(); - } - if(annotation instanceof VersionAnnotation va) { - version = va.version(); - } - } - } + Annotation[] annotations = getClass().getAnnotations(); + for (Annotation annotation : annotations) { + if (annotation instanceof EndPointAnnotation epa) { + endPointName = epa.name(); + } + if (annotation instanceof VersionAnnotation va) { + version = va.version(); + } + } + } - protected Object getParameter(String paramName) { - return dictUrlParams.get(paramName); - } + protected Object getParameter(String paramName) { + return dictUrlParams.get(paramName); + } - protected void addParameter(String paramName, Object paramValue) { - dictUrlParams.put(paramName, paramValue); - } + protected void addParameter(String paramName, Object paramValue) { + dictUrlParams.put(paramName, paramValue); + } - protected String getEndPointPath(String altName) { - String tmp = endPointName; - endPointName = altName; - String ret = getEndPointPath(); - endPointName = tmp; - return ret; - } + protected String getEndPointPath(String altName) { + String tmp = endPointName; + endPointName = altName; + String ret = getEndPointPath(); + endPointName = tmp; + return ret; + } - protected String getEndPointPath() { - String path = ""; - if(version != null && !version.isEmpty()) - path = version + "/"; - path = path + endPointName; + protected String getEndPointPath() { + String path = ""; + if (version != null && !version.isEmpty()) + path = version + "/"; + path = path + endPointName; - return path; - } + return path; + } } diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/common/Utils.java b/ors-api/src/test/java/org/heigit/ors/apitests/common/Utils.java index c4e37f2c0d..9064e3a399 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/common/Utils.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/common/Utils.java @@ -32,27 +32,26 @@ public class Utils { - public synchronized static final String getORSVersion() { - - String version = null; - - try { - String curDir = System.getProperty("user.dir"); - Path pomFile = Paths.get(Paths.get(curDir).getParent().toString(), "openrouteservice").resolve("pom.xml"); - - try (InputStream is = Files.newInputStream(pomFile)) - { - Document doc = DocumentBuilderFactory.newInstance() - .newDocumentBuilder().parse(is); - doc.getDocumentElement().normalize(); - version = (String) XPathFactory.newInstance().newXPath().compile("/project/version").evaluate(doc, XPathConstants.STRING); - if (version != null) { - version = version.trim(); - } - } - } catch (Exception ignored) { - } - - return version; - } + public synchronized static final String getORSVersion() { + + String version = null; + + try { + String curDir = System.getProperty("user.dir"); + Path pomFile = Paths.get(Paths.get(curDir).getParent().toString(), "openrouteservice").resolve("pom.xml"); + + try (InputStream is = Files.newInputStream(pomFile)) { + Document doc = DocumentBuilderFactory.newInstance() + .newDocumentBuilder().parse(is); + doc.getDocumentElement().normalize(); + version = (String) XPathFactory.newInstance().newXPath().compile("/project/version").evaluate(doc, XPathConstants.STRING); + if (version != null) { + version = version.trim(); + } + } + } catch (Exception ignored) { + } + + return version; + } } diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/cors/CORSSettingsTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/cors/CORSSettingsTest.java index 885a62f8c7..f118feb24c 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/cors/CORSSettingsTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/cors/CORSSettingsTest.java @@ -25,7 +25,6 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ActiveProfiles; import java.util.List; diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/ResultTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/ResultTest.java index 93a166a4bc..95d39a4552 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/ResultTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/ResultTest.java @@ -16,14 +16,13 @@ import io.restassured.RestAssured; import io.restassured.config.RestAssuredConfig; import io.restassured.path.json.config.JsonPathConfig; +import org.heigit.ors.apitests.common.EndPointAnnotation; import org.heigit.ors.apitests.common.ServiceTest; import org.heigit.ors.apitests.common.VersionAnnotation; import org.heigit.ors.apitests.utils.CommonHeaders; -import org.heigit.ors.apitests.common.EndPointAnnotation; import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; import static io.restassured.RestAssured.given; import static io.restassured.config.JsonConfig.jsonConfig; diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ParamsTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ParamsTest.java index 7b54590f0d..3808b18e94 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ParamsTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ParamsTest.java @@ -311,7 +311,7 @@ void testUnknownAttributes() { .pathParam("profile", getParameter("hgvProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/geojson") + .post(getEndPointPath() + "/{profile}/geojson") .then() .assertThat() .body("error.code", Matchers.is(IsochronesErrorCodes.INVALID_PARAMETER_VALUE)) @@ -324,7 +324,7 @@ void testUnknownAttributes() { .pathParam("profile", getParameter("hgvProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/geojson") + .post(getEndPointPath() + "/{profile}/geojson") .then() .assertThat() .body("error.code", Matchers.is(IsochronesErrorCodes.INVALID_PARAMETER_VALUE)) @@ -349,7 +349,7 @@ void expectUnknownAvoidFeatures() { .pathParam("profile", getParameter("hgvProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/geojson") + .post(getEndPointPath() + "/{profile}/geojson") .then() .assertThat() .body("error.code", Matchers.is(IsochronesErrorCodes.INVALID_PARAMETER_VALUE)) @@ -373,7 +373,7 @@ void expectUnknownAvoidBorders() { .pathParam("profile", getParameter("hgvProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/geojson") + .post(getEndPointPath() + "/{profile}/geojson") .then() .assertThat() .body("error.code", Matchers.is(IsochronesErrorCodes.INVALID_PARAMETER_VALUE)) @@ -392,7 +392,7 @@ void expectInvalidResponseFormat() { .pathParam("profile", getParameter("hgvProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/blah") + .post(getEndPointPath() + "/{profile}/blah") .then() .assertThat() .body("error.code", Matchers.is(IsochronesErrorCodes.UNSUPPORTED_EXPORT_FORMAT)) @@ -403,7 +403,7 @@ void expectInvalidResponseFormat() { .pathParam("profile", getParameter("hgvProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/geojson") + .post(getEndPointPath() + "/{profile}/geojson") .then() .assertThat() .body("error.code", Matchers.is(IsochronesErrorCodes.UNSUPPORTED_EXPORT_FORMAT)) diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ResultTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ResultTest.java index db3b25666a..045b135084 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ResultTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/isochrones/fast/ResultTest.java @@ -16,9 +16,9 @@ import io.restassured.RestAssured; import io.restassured.path.json.config.JsonPathConfig; import org.hamcrest.Matchers; +import org.heigit.ors.apitests.common.EndPointAnnotation; import org.heigit.ors.apitests.common.ServiceTest; import org.heigit.ors.apitests.common.VersionAnnotation; -import org.heigit.ors.apitests.common.EndPointAnnotation; import org.heigit.ors.apitests.isochrones.IsochronesErrorCodes; import org.json.JSONArray; import org.json.JSONObject; diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ParamsTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ParamsTest.java index b57ce9158a..ea2ca3104d 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ParamsTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ParamsTest.java @@ -14,9 +14,9 @@ package org.heigit.ors.apitests.matrix; import org.hamcrest.Matchers; +import org.heigit.ors.apitests.common.EndPointAnnotation; import org.heigit.ors.apitests.common.ServiceTest; import org.heigit.ors.apitests.common.VersionAnnotation; -import org.heigit.ors.apitests.common.EndPointAnnotation; import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -219,7 +219,7 @@ void expectInvalidResponseFormat() { .pathParam("profile", getParameter("carProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/blah") + .post(getEndPointPath() + "/{profile}/blah") .then() .assertThat() .body("error.code", Matchers.is(MatrixErrorCodes.UNSUPPORTED_EXPORT_FORMAT)) @@ -230,7 +230,7 @@ void expectInvalidResponseFormat() { .pathParam("profile", getParameter("carProfile")) .body(body.toString()) .when() - .post(getEndPointPath()+"/{profile}/json") + .post(getEndPointPath() + "/{profile}/json") .then() .assertThat() .body("error.code", Matchers.is(MatrixErrorCodes.UNSUPPORTED_EXPORT_FORMAT)) @@ -521,7 +521,7 @@ void expectQueryResponseType() { void expectQuerySources() { JSONObject body = new JSONObject(); body.put("locations", getParameter("locations")); - body.put("sources", new String[] {"all"}); + body.put("sources", new String[]{"all"}); given() .headers(jsonContent) .pathParam("profile", getParameter("carProfile")) @@ -539,7 +539,7 @@ void expectQuerySources() { void expectQueryDestinations() { JSONObject body = new JSONObject(); body.put("locations", getParameter("locations")); - body.put("destinations", new String[] {"all"}); + body.put("destinations", new String[]{"all"}); given() .headers(jsonContent) .pathParam("profile", getParameter("carProfile")) diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ResultTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ResultTest.java index e74be33762..133202989a 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ResultTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/matrix/ResultTest.java @@ -16,9 +16,9 @@ import io.restassured.RestAssured; import io.restassured.config.RestAssuredConfig; import io.restassured.path.json.config.JsonPathConfig; -import org.heigit.ors.apitests.common.VersionAnnotation; import org.heigit.ors.apitests.common.EndPointAnnotation; import org.heigit.ors.apitests.common.ServiceTest; +import org.heigit.ors.apitests.common.VersionAnnotation; import org.heigit.ors.apitests.utils.HelperFunctions; import org.json.JSONArray; import org.json.JSONObject; @@ -28,12 +28,13 @@ import static io.restassured.config.JsonConfig.jsonConfig; import static org.hamcrest.Matchers.*; import static org.heigit.ors.apitests.utils.CommonHeaders.jsonContent; -import static org.heigit.ors.matrix.MatrixErrorCodes.*; +import static org.heigit.ors.matrix.MatrixErrorCodes.MAX_VISITED_NODES_EXCEEDED; @EndPointAnnotation(name = "matrix") @VersionAnnotation(version = "v2") class ResultTest extends ServiceTest { public static final RestAssuredConfig JSON_CONFIG_DOUBLE_NUMBERS = RestAssured.config().jsonConfig(jsonConfig().numberReturnType(JsonPathConfig.NumberReturnType.DOUBLE)); + public ResultTest() { // Three locations JSONArray locations3 = new JSONArray(); @@ -344,7 +345,7 @@ void expectAllMetrics() { .body("distances[1][1]", is(closeTo(0.0, 0.001))) .body("distances[1][2]", is(closeTo(479.08, 5))) .body("distances[2][0]", is(closeTo(1274.4, 12))) - .body("distances[2][1]", is(closeTo(376.77,4))) + .body("distances[2][1]", is(closeTo(376.77, 4))) .body("distances[2][2]", is(closeTo(0.0, 0.001))) .statusCode(200); @@ -770,7 +771,8 @@ void expectSourcesItemsWithResolveLocations() { @Test void testIdInSummary() { - JSONObject body = new JSONObject();body.put("locations", getParameter("locations")); + JSONObject body = new JSONObject(); + body.put("locations", getParameter("locations")); body.put("id", "request123"); given() @@ -791,7 +793,7 @@ void testIdInSummary() { void testDefinedSources() { JSONObject body = new JSONObject(); body.put("locations", getParameter("locations")); - body.put("sources", new JSONArray(new int[] {1,2})); + body.put("sources", new JSONArray(new int[]{1, 2})); body.put("metrics", getParameter("metricsDuration")); given() @@ -819,7 +821,7 @@ void testDefinedSources() { void testDefinedDestinations() { JSONObject body = new JSONObject(); body.put("locations", getParameter("locations")); - body.put("destinations", new JSONArray(new int[] {1,2})); + body.put("destinations", new JSONArray(new int[]{1, 2})); body.put("metrics", getParameter("metricsDuration")); given() @@ -849,8 +851,8 @@ void testDefinedSourcesAndDestinations() { JSONObject body = new JSONObject(); body.put("locations", getParameter("locations5")); - body.put("sources", new JSONArray(new int[] {0,1})); - body.put("destinations", new JSONArray(new int[] {2,3,4})); + body.put("sources", new JSONArray(new int[]{0, 1})); + body.put("destinations", new JSONArray(new int[]{2, 3, 4})); given() .config(JSON_CONFIG_DOUBLE_NUMBERS) diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/routing/ParamsTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/routing/ParamsTest.java index 5b3bdb38a9..fbeea66d65 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/routing/ParamsTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/routing/ParamsTest.java @@ -18,7 +18,6 @@ import org.heigit.ors.apitests.common.ServiceTest; import org.heigit.ors.apitests.common.VersionAnnotation; import org.heigit.ors.apitests.utils.HelperFunctions; -import org.heigit.ors.config.AppConfig; import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.Test; diff --git a/ors-api/src/test/java/org/heigit/ors/apitests/routing/ResultTest.java b/ors-api/src/test/java/org/heigit/ors/apitests/routing/ResultTest.java index 2636536ce2..348e1ae348 100644 --- a/ors-api/src/test/java/org/heigit/ors/apitests/routing/ResultTest.java +++ b/ors-api/src/test/java/org/heigit/ors/apitests/routing/ResultTest.java @@ -17,11 +17,11 @@ import io.restassured.config.RestAssuredConfig; import io.restassured.path.json.config.JsonPathConfig; import io.restassured.response.Response; +import org.heigit.ors.apitests.common.EndPointAnnotation; import org.heigit.ors.apitests.common.ServiceTest; import org.heigit.ors.apitests.common.VersionAnnotation; import org.heigit.ors.apitests.utils.CommonHeaders; import org.heigit.ors.apitests.utils.HelperFunctions; -import org.heigit.ors.apitests.common.EndPointAnnotation; import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.Disabled; @@ -804,7 +804,7 @@ void testSegmentDistances() { @Test void testEncodedPolyline() { // check if route is the same as before, then the value can be adjusted - // need to check if polyline generation is sufficiently covered by unit tests, then this test can be omitted + // need to check if polyline generation is sufficiently covered by unit tests, then this test can be omitted JSONObject body = new JSONObject(); body.put("coordinates", getParameter("coordinatesLong")); body.put("preference", getParameter("preference")); @@ -865,7 +865,7 @@ void testBbox() { // wait for elevation smoothing check, rewrite coordinates as .then() .assertThat() .body("any { it.key == 'routes' }", is(true)) - .body("routes[0].bbox", hasItems(closeTo(8.678615,0.1), closeTo(49.388405,0.5), closeTo(107.83,1), closeTo(8.719662,0.1), closeTo(49.424603,0.5), closeTo(404.73,4))) + .body("routes[0].bbox", hasItems(closeTo(8.678615, 0.1), closeTo(49.388405, 0.5), closeTo(107.83, 1), closeTo(8.719662, 0.1), closeTo(49.424603, 0.5), closeTo(404.73, 4))) .statusCode(200); } @@ -888,13 +888,13 @@ void testManeuver() { .then().log().ifValidationFails() .assertThat() .body("any { it.key == 'routes' }", is(true)) - .body("routes[0].bbox", hasItems(closeTo(8.678615,0.1), closeTo(49.388405f,0.5), closeTo(107.83f, 1), closeTo(8.719662f, 0.1), closeTo(49.424603f,0.5), closeTo(404.73f, 4))) + .body("routes[0].bbox", hasItems(closeTo(8.678615, 0.1), closeTo(49.388405f, 0.5), closeTo(107.83f, 1), closeTo(8.719662f, 0.1), closeTo(49.424603f, 0.5), closeTo(404.73f, 4))) .body("routes[0].segments[0].steps[0].maneuver.bearing_before", is(0)) .body("routes[0].segments[0].steps[0].maneuver.bearing_after", is(175)) .body("routes[0].segments[0].steps[0].maneuver.containsKey('location')", is(true)) .body("routes[0].segments[0].steps[1].maneuver.bearing_before", is(175)) .body("routes[0].segments[0].steps[1].maneuver.bearing_after", is(80)) - .body("routes[0].segments[0].steps[1].maneuver.location", hasItems(closeTo(8.678618,0.1), closeTo(49.411697,0.5))) + .body("routes[0].segments[0].steps[1].maneuver.location", hasItems(closeTo(8.678618, 0.1), closeTo(49.411697, 0.5))) .statusCode(200); } @@ -2188,7 +2188,7 @@ void testWheelchairDebugExport() { .assertThat() .statusCode(200); -} + } @Test void testWheelchairSurfaceQualityKnown() { @@ -2948,7 +2948,7 @@ void testRouteMergeInstructionsWithoutGeometry() { // need to check route geomet } @Test - void testCountryTraversalNoBorderCrossing(){ + void testCountryTraversalNoBorderCrossing() { JSONObject body = new JSONObject(); JSONArray noBorderCrossing = new JSONArray(); JSONArray coord = new JSONArray(); @@ -3129,21 +3129,21 @@ void testAlternativeRoutes() { body.put("alternative_routes", ar); body.put("extra_info", getParameter("extra_info")); given() - .config(JSON_CONFIG_DOUBLE_NUMBERS) - .headers(CommonHeaders.jsonContent) - .pathParam("profile", getParameter("carProfile")) - .body(body.toString()) - .when() - .post(getEndPointPath() + "/{profile}") - .then() - .assertThat() - .body("any { it.key == 'routes' }", is(true)) - .body("routes.size()", is(2)) - .body("routes[0].summary.distance", is(closeTo(5942.2, 5))) - .body("routes[0].summary.duration", is(closeTo(776.1, 1))) - .body("routes[1].summary.distance", is( closeTo(6435.1, 6))) - .body("routes[1].summary.duration", is(closeTo(801.5, 1))) - .statusCode(200); + .config(JSON_CONFIG_DOUBLE_NUMBERS) + .headers(CommonHeaders.jsonContent) + .pathParam("profile", getParameter("carProfile")) + .body(body.toString()) + .when() + .post(getEndPointPath() + "/{profile}") + .then() + .assertThat() + .body("any { it.key == 'routes' }", is(true)) + .body("routes.size()", is(2)) + .body("routes[0].summary.distance", is(closeTo(5942.2, 5))) + .body("routes[0].summary.duration", is(closeTo(776.1, 1))) + .body("routes[1].summary.distance", is(closeTo(6435.1, 6))) + .body("routes[1].summary.duration", is(closeTo(801.5, 1))) + .statusCode(200); JSONObject avoidGeom = new JSONObject("{\"type\":\"Polygon\",\"coordinates\":[[[8.685873,49.414421], [8.688169,49.403978], [8.702095,49.407762], [8.695185,49.416013], [8.685873,49.414421]]]}}"); JSONObject options = new JSONObject(); @@ -3161,7 +3161,7 @@ void testAlternativeRoutes() { .assertThat() .body("any { it.key == 'routes' }", is(true)) .body("routes.size()", is(1)) - .body("routes[0].summary.distance", is( closeTo(6435.1, 6))) + .body("routes[0].summary.distance", is(closeTo(6435.1, 6))) .body("routes[0].summary.duration", is(closeTo(801.5, 1))) .statusCode(200); @@ -3254,7 +3254,7 @@ void testRoundTrip() { .body("any { it.key == 'routes' }", is(true)) .body("routes.size()", is(1)) .body("routes[0].summary.distance", anyOf(is(closeTo(2519.8, 2)), is(closeTo(2496.8, 2)))) - .body("routes[0].summary.duration", anyOf(is(closeTo(1814.2, 2)), is(closeTo(1797.6, 2) ))) + .body("routes[0].summary.duration", anyOf(is(closeTo(1814.2, 2)), is(closeTo(1797.6, 2)))) .statusCode(200); } @@ -3312,7 +3312,7 @@ void testWaypointCount() { @Test void expectNoInterpolationOfBridgesAndTunnels() { // consider rewriting as unit test - // wait for elevation smoothing check + // wait for elevation smoothing check JSONObject body = new JSONObject(); body.put("coordinates", getParameter("coordinatesWalking")); body.put("preference", getParameter("preference")); @@ -3380,7 +3380,7 @@ void expectDepartureAndArrival() { @Test void testConditionalAccess() { - JSONArray coordinates = new JSONArray(); + JSONArray coordinates = new JSONArray(); JSONArray coord1 = new JSONArray(); coord1.put(8.645178); coord1.put(49.399496); @@ -3457,7 +3457,7 @@ void testConditionalAccess() { @Test void testConditionalSpeed() { - JSONArray coordinates = new JSONArray(); + JSONArray coordinates = new JSONArray(); JSONArray coord1 = new JSONArray(); coord1.put(8.689993); coord1.put(49.399208); @@ -3605,7 +3605,7 @@ void testTrafficSpeed() { @Test void testTrafficSpeedMultipleMatches() { - JSONArray coordinatesTheodorHeuss = new JSONArray(); + JSONArray coordinatesTheodorHeuss = new JSONArray(); JSONArray coordTh1 = new JSONArray(); coordTh1.put(8.6928696); coordTh1.put(49.4115257); @@ -3669,7 +3669,7 @@ void testTrafficSpeedMultipleMatches() { @Test void expectZoneMaxpeed() { - JSONArray coordinates = new JSONArray(); + JSONArray coordinates = new JSONArray(); JSONArray coord1 = new JSONArray(); coord1.put(8.676031); coord1.put(49.417011); @@ -3713,7 +3713,7 @@ void expectZoneMaxpeed() { @Test void expectMaxpeedHgvForward() { - JSONArray coordinates = new JSONArray(); + JSONArray coordinates = new JSONArray(); JSONArray coord1 = new JSONArray(); coord1.put(8.696237); coord1.put(49.37186); @@ -3754,9 +3754,10 @@ void expectMaxpeedHgvForward() { .body("routes[0].summary.duration", is(81.1f)) .statusCode(200); } + @Test void testPTJSON() { - JSONArray coordinates = new JSONArray(); + JSONArray coordinates = new JSONArray(); JSONArray coord1 = new JSONArray(); coord1.put(8.6729581); coord1.put(49.4468535); @@ -3772,34 +3773,34 @@ void testPTJSON() { body.put("departure", "2022-07-04T13:02:26Z"); body.put("walking_time", "PT30M"); Response res = given() - .header("Accept", "application/json") - .header("Content-Type", "application/json") - .pathParam("profile", getParameter("ptProfile")) - .body(body.toString()) - .when() - .post(getEndPointPath() + "/{profile}") - .then().log().ifValidationFails() - .assertThat() - .body("any { it.key == 'routes' }", is(true)) - .body("routes.size()", is(3)) - .body("routes[0].summary.transfers", is(2)) - .body("routes[0].legs.size()", is(6)) - .body("routes[0].legs[0].containsKey('arrival')", is(true)) - .body("routes[0].legs[0].containsKey('departure')", is(true)) - .body("routes[0].legs[0].containsKey('instructions')", is(true)) - .body("routes[0].legs[0].containsKey('geometry')", is(true)) - .body("routes[0].legs[1].containsKey('feed_id')", is(true)) - .body("routes[0].legs[1].containsKey('trip_id')", is(true)) - .body("routes[0].legs[1].containsKey('route_id')", is(true)) - .body("routes[0].legs[1].containsKey('route_type')", is(true)) - .body("routes[0].legs[1].containsKey('route_desc')", is(true)) - .body("routes[0].legs[1].containsKey('geometry')", is(true)) - .statusCode(200).extract().response(); + .header("Accept", "application/json") + .header("Content-Type", "application/json") + .pathParam("profile", getParameter("ptProfile")) + .body(body.toString()) + .when() + .post(getEndPointPath() + "/{profile}") + .then().log().ifValidationFails() + .assertThat() + .body("any { it.key == 'routes' }", is(true)) + .body("routes.size()", is(3)) + .body("routes[0].summary.transfers", is(2)) + .body("routes[0].legs.size()", is(6)) + .body("routes[0].legs[0].containsKey('arrival')", is(true)) + .body("routes[0].legs[0].containsKey('departure')", is(true)) + .body("routes[0].legs[0].containsKey('instructions')", is(true)) + .body("routes[0].legs[0].containsKey('geometry')", is(true)) + .body("routes[0].legs[1].containsKey('feed_id')", is(true)) + .body("routes[0].legs[1].containsKey('trip_id')", is(true)) + .body("routes[0].legs[1].containsKey('route_id')", is(true)) + .body("routes[0].legs[1].containsKey('route_type')", is(true)) + .body("routes[0].legs[1].containsKey('route_desc')", is(true)) + .body("routes[0].legs[1].containsKey('geometry')", is(true)) + .statusCode(200).extract().response(); } @Test void testPTGeoJSON() { - JSONArray coordinates = new JSONArray(); + JSONArray coordinates = new JSONArray(); JSONArray coord1 = new JSONArray(); coord1.put(8.6729581); coord1.put(49.4468535); @@ -3815,40 +3816,40 @@ void testPTGeoJSON() { body.put("departure", "2022-07-04T13:02:26Z"); body.put("walking_time", "PT30M"); Response res = given() - .header("Accept", "application/geo+json") - .header("Content-Type", "application/json") - .pathParam("profile", getParameter("ptProfile")) - .body(body.toString()) - .when() - .post(getEndPointPath() + "/{profile}/geojson") - .then().log().ifValidationFails() - .assertThat() - .body("any { it.key == 'features' }", is(true)) - .body("features.size()", is(3)) - .body("features[0].properties.transfers", is(2)) - .body("features[0].properties.legs.size()", is(6)) - .body("features[0].properties.legs[0].containsKey('arrival')", is(true)) - .body("features[0].properties.legs[0].containsKey('departure')", is(true)) - .body("features[0].properties.legs[0].containsKey('instructions')", is(true)) - .body("features[0].properties.legs[0].containsKey('geometry')", is(true)) - .body("features[0].properties.legs[1].containsKey('feed_id')", is(true)) - .body("features[0].properties.legs[1].containsKey('trip_id')", is(true)) - .body("features[0].properties.legs[1].containsKey('route_id')", is(true)) - .body("features[0].properties.legs[1].containsKey('route_type')", is(true)) - .body("features[0].properties.legs[1].containsKey('route_desc')", is(true)) - .body("features[0].properties.legs[1].containsKey('geometry')", is(true)) - .statusCode(200).extract().response(); + .header("Accept", "application/geo+json") + .header("Content-Type", "application/json") + .pathParam("profile", getParameter("ptProfile")) + .body(body.toString()) + .when() + .post(getEndPointPath() + "/{profile}/geojson") + .then().log().ifValidationFails() + .assertThat() + .body("any { it.key == 'features' }", is(true)) + .body("features.size()", is(3)) + .body("features[0].properties.transfers", is(2)) + .body("features[0].properties.legs.size()", is(6)) + .body("features[0].properties.legs[0].containsKey('arrival')", is(true)) + .body("features[0].properties.legs[0].containsKey('departure')", is(true)) + .body("features[0].properties.legs[0].containsKey('instructions')", is(true)) + .body("features[0].properties.legs[0].containsKey('geometry')", is(true)) + .body("features[0].properties.legs[1].containsKey('feed_id')", is(true)) + .body("features[0].properties.legs[1].containsKey('trip_id')", is(true)) + .body("features[0].properties.legs[1].containsKey('route_id')", is(true)) + .body("features[0].properties.legs[1].containsKey('route_type')", is(true)) + .body("features[0].properties.legs[1].containsKey('route_desc')", is(true)) + .body("features[0].properties.legs[1].containsKey('geometry')", is(true)) + .statusCode(200).extract().response(); } @ParameterizedTest @CsvSource({"coordinatesPT,PT1M,2013,0", "coordinatesPTFlipped,PT1M,2014,1", "coordinatesPTFlipped,PT10S,2015,2", "coordinatesPTFlipped,PT10M,2016,3", "coordinatesPT2,PT4H,2017,4"}) void testPTFail(String coords, String walkingTime, int errorCode, int messageIndex) { String[] messages = { - "PT entry point cannot be reached within given street time.", - "PT exit point cannot be reached within given street time.", - "PT exit point cannot be reached within given street time. PT entry point cannot be reached within given street time.", - "PT entry and exit points found but no connecting route. Increase walking time to explore more results.", - "Maximum number of nodes exceeded: 15000" + "PT entry point cannot be reached within given street time.", + "PT exit point cannot be reached within given street time.", + "PT exit point cannot be reached within given street time. PT entry point cannot be reached within given street time.", + "PT entry and exit points found but no connecting route. Increase walking time to explore more results.", + "Maximum number of nodes exceeded: 15000" }; JSONObject body = new JSONObject(); @@ -3856,18 +3857,18 @@ void testPTFail(String coords, String walkingTime, int errorCode, int messageInd body.put("departure", "2022-09-26T07:30:26Z"); body.put("walking_time", walkingTime); given() - .header("Accept", "application/json") - .header("Content-Type", "application/json") - .pathParam("profile", getParameter("ptProfile")) - .body(body.toString()) - .when() - .post(getEndPointPath() + "/{profile}") - .then().log().ifValidationFails() - .assertThat() - .body("any { it.key == 'error' }", is(true)) - .body("error.code", is(errorCode)) - .body("error.message", containsString(messages[messageIndex])) - .statusCode(404); + .header("Accept", "application/json") + .header("Content-Type", "application/json") + .pathParam("profile", getParameter("ptProfile")) + .body(body.toString()) + .when() + .post(getEndPointPath() + "/{profile}") + .then().log().ifValidationFails() + .assertThat() + .body("any { it.key == 'error' }", is(true)) + .body("error.code", is(errorCode)) + .body("error.message", containsString(messages[messageIndex])) + .statusCode(404); } private JSONArray constructBearings(String coordString) { diff --git a/ors-api/src/test/resources/logs/TEST_LOGGING.json b/ors-api/src/test/resources/logs/TEST_LOGGING.json index b2f6ab65ff..37f0e7909f 100644 --- a/ors-api/src/test/resources/logs/TEST_LOGGING.json +++ b/ors-api/src/test/resources/logs/TEST_LOGGING.json @@ -17,7 +17,10 @@ "PatternLayout": { "pattern": "%d %p [%c{2}] - %m%n" }, - "TimeBasedTriggeringPolicy": { "interval": "1", "modulate": "true" } + "TimeBasedTriggeringPolicy": { + "interval": "1", + "modulate": "true" + } } }, "loggers": { diff --git a/ors-engine/src/main/java/org/heigit/ors/common/ArrivalDirection.java b/ors-engine/src/main/java/org/heigit/ors/common/ArrivalDirection.java index 1c9ecbf91d..1535464d2d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/ArrivalDirection.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/ArrivalDirection.java @@ -4,14 +4,14 @@ * http://www.giscience.uni-hd.de * http://www.heigit.org * - * under one or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information regarding copyright - * ownership. The GIScience licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in compliance + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. The GIScience licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,8 +21,8 @@ package org.heigit.ors.common; public enum ArrivalDirection { - UNKNOWN, - LEFT, - RIGHT, - STRAIGHT_AHEAD + UNKNOWN, + LEFT, + RIGHT, + STRAIGHT_AHEAD } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/AttributeValue.java b/ors-engine/src/main/java/org/heigit/ors/common/AttributeValue.java index f587737f17..b610e223db 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/AttributeValue.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/AttributeValue.java @@ -1,42 +1,38 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.common; public class AttributeValue { - private final String name; - private final double value; - private final String source; + private final String name; + private final double value; + private final String source; - public AttributeValue(String name, double value, String source) - { - this.name = name; - this.value = value; - this.source = source; - } + public AttributeValue(String name, double value, String source) { + this.name = name; + this.value = value; + this.source = source; + } - public String getName() - { - return name; - } + public String getName() { + return name; + } - public double getValue() - { - return value; - } + public double getValue() { + return value; + } - public String getSource() - { - return source; - } + public String getSource() { + return source; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/CardinalDirection.java b/ors-engine/src/main/java/org/heigit/ors/common/CardinalDirection.java index 7d18a01693..bdb930f7bf 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/CardinalDirection.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/CardinalDirection.java @@ -4,14 +4,14 @@ * http://www.giscience.uni-hd.de * http://www.heigit.org * - * under one or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information regarding copyright - * ownership. The GIScience licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in compliance + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. The GIScience licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,12 +21,12 @@ package org.heigit.ors.common; public enum CardinalDirection { - NORTH, - NORTH_EAST, - EAST, - SOUTH_EAST, - SOUTH, - SOUTH_WEST, - WEST, - NORTH_WEST + NORTH, + NORTH_EAST, + EAST, + SOUTH_EAST, + SOUTH, + SOUTH_WEST, + WEST, + NORTH_WEST } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/DistanceUnit.java b/ors-engine/src/main/java/org/heigit/ors/common/DistanceUnit.java index fbf60a97c4..5f5481bed2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/DistanceUnit.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/DistanceUnit.java @@ -1,22 +1,22 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.common; public enum DistanceUnit { - METERS, - KILOMETERS, - MILES, - UNKNOWN + METERS, + KILOMETERS, + MILES, + UNKNOWN } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/NamedLocation.java b/ors-engine/src/main/java/org/heigit/ors/common/NamedLocation.java index 6a23762544..4202bdfddc 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/NamedLocation.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/NamedLocation.java @@ -1,36 +1,34 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.common; import org.locationtech.jts.geom.Coordinate; public class NamedLocation { - private final Coordinate coordinate; - private final String name; - - public NamedLocation(Coordinate coord, String name) { - coordinate = coord; - this.name = name; - } - - public Coordinate getCoordinate() - { - return coordinate; - } - - public String getName() - { - return name; - } + private final Coordinate coordinate; + private final String name; + + public NamedLocation(Coordinate coord, String name) { + coordinate = coord; + this.name = name; + } + + public Coordinate getCoordinate() { + return coordinate; + } + + public String getName() { + return name; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/Pair.java b/ors-engine/src/main/java/org/heigit/ors/common/Pair.java index 0e12c1e39b..3d535d5314 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/Pair.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/Pair.java @@ -37,7 +37,7 @@ public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } - public static Pair create(A a, B b) { + public static Pair create(A a, B b) { return new Pair<>(a, b); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/ServiceRequest.java b/ors-engine/src/main/java/org/heigit/ors/common/ServiceRequest.java index 3fa2cf2f29..00835ec62b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/ServiceRequest.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/ServiceRequest.java @@ -1,26 +1,26 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.common; public class ServiceRequest { - private String id; + private String id; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/StatusCode.java b/ors-engine/src/main/java/org/heigit/ors/common/StatusCode.java index 1150f9e15d..d12fb17a81 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/StatusCode.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/StatusCode.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.common; @@ -20,41 +20,42 @@ public class StatusCode { * Status code (200) indicating the request succeeded normally. */ public static final int OK = HttpURLConnection.HTTP_OK; - /** + /** * Status code (400) indicating the request sent by the client was * syntactically incorrect. */ - public static final int BAD_REQUEST = HttpURLConnection.HTTP_BAD_REQUEST; - /** - * Status code (405) indicating that the method specified in the - * Request-Line is not allowed for the resource - * identified by the Request-URI. - */ - public static final int METHOD_NOT_ALLOWED = HttpURLConnection.HTTP_BAD_METHOD; - - /** - * Status code (500) indicating an error inside the HTTP server - * which prevented it from fulfilling the request. - */ - public static final int INTERNAL_SERVER_ERROR = HttpURLConnection.HTTP_INTERNAL_ERROR; - - /** - * Status code (501) indicating the HTTP server does not support - * the functionality needed to fulfill the request. - */ - public static final int NOT_IMPLEMENTED = HttpURLConnection.HTTP_NOT_IMPLEMENTED; - - /** - * Status code (503) indicating that the End Point is - * temporarily overloaded, and unable to handle the request. - */ - public static final int SERVICE_UNAVAILABLE = HttpURLConnection.HTTP_UNAVAILABLE; - - /** - * Status code (404) indicating that the request was processed but - * no information was found (i.e. a geocoding request that did not find a corresponding address) - */ - public static final int NOT_FOUND = HttpURLConnection.HTTP_NOT_FOUND; - - private StatusCode() {} + public static final int BAD_REQUEST = HttpURLConnection.HTTP_BAD_REQUEST; + /** + * Status code (405) indicating that the method specified in the + * Request-Line is not allowed for the resource + * identified by the Request-URI. + */ + public static final int METHOD_NOT_ALLOWED = HttpURLConnection.HTTP_BAD_METHOD; + + /** + * Status code (500) indicating an error inside the HTTP server + * which prevented it from fulfilling the request. + */ + public static final int INTERNAL_SERVER_ERROR = HttpURLConnection.HTTP_INTERNAL_ERROR; + + /** + * Status code (501) indicating the HTTP server does not support + * the functionality needed to fulfill the request. + */ + public static final int NOT_IMPLEMENTED = HttpURLConnection.HTTP_NOT_IMPLEMENTED; + + /** + * Status code (503) indicating that the End Point is + * temporarily overloaded, and unable to handle the request. + */ + public static final int SERVICE_UNAVAILABLE = HttpURLConnection.HTTP_UNAVAILABLE; + + /** + * Status code (404) indicating that the request was processed but + * no information was found (i.e. a geocoding request that did not find a corresponding address) + */ + public static final int NOT_FOUND = HttpURLConnection.HTTP_NOT_FOUND; + + private StatusCode() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/TravelRangeType.java b/ors-engine/src/main/java/org/heigit/ors/common/TravelRangeType.java index 47080c8560..6017bc7c1f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/TravelRangeType.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/TravelRangeType.java @@ -1,19 +1,19 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.common; public enum TravelRangeType { - DISTANCE, - TIME + DISTANCE, + TIME } diff --git a/ors-engine/src/main/java/org/heigit/ors/common/TravellerInfo.java b/ors-engine/src/main/java/org/heigit/ors/common/TravellerInfo.java index 3ed939597f..d0194ae739 100644 --- a/ors-engine/src/main/java/org/heigit/ors/common/TravellerInfo.java +++ b/ors-engine/src/main/java/org/heigit/ors/common/TravellerInfo.java @@ -1,156 +1,145 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.common; -import org.locationtech.jts.geom.Coordinate; - import org.heigit.ors.routing.RouteSearchParameters; +import org.locationtech.jts.geom.Coordinate; -public class TravellerInfo { - private String id = "0"; - private Coordinate location; - private String locationType = "start"; // either start or destination - private double[] ranges; - private TravelRangeType rangeType = TravelRangeType.TIME; - private RouteSearchParameters routeSearchParams; - - public TravellerInfo() - { - routeSearchParams = new RouteSearchParameters(); - } - - public TravellerInfo(TravellerInfo old) { - this.id = old.id; - this.location = old.location; - this.locationType = old.locationType; - this.ranges = old.ranges; - this.rangeType = old.rangeType; - this.routeSearchParams = old.routeSearchParams; - } - - public String getId() - { - return id; - } - - public void setId(String id) - { - this.id = id; - } - - public Coordinate getLocation() - { - return location; - } - - public void setLocation(Coordinate location) - { - this.location = location; - } - - public double[] getRanges() - { - return ranges; - } - - /** - * Returns the range specified in the unit given by the user. The algorithm converts - * the input range to m so we need to convert it back. - * - * @param unit the unit to return in - * @return the ranges array in the specified unit - */ - - public double[] getRangesInUnit(String unit){ - // convert ranges from meters to user specified unit - double[] rangesInUnit = new double[ranges.length]; - - if (!(unit == null || "m".equalsIgnoreCase(unit))) { - double scale = 1.0; - if (rangeType == TravelRangeType.DISTANCE) { - switch(unit) { - case "km": - scale = 1/1000.0; - break; - case "mi": - scale = 1/1609.34; - break; - default: - case "m": - break; - } - } - - if (scale != 1.0) { - for (int i = 0; i < ranges.length; i++) - rangesInUnit[i] = ranges[i]*scale; - return rangesInUnit; - } - return ranges; - } - return ranges; - } - - public void setRanges(double range, double interval) { - int nRanges = (int) Math.ceil(range / interval); - ranges = new double[nRanges]; - for (int i = 0; i < nRanges - 1; i++) - ranges[i] = (i + 1) * interval; - - ranges[nRanges - 1]= range; - } - - public void setRanges(double[] ranges) - { - this.ranges = ranges; - } - - public double getMaximumRange() { - double maxRange = Double.MIN_VALUE; - - for(double range : ranges) { - if (maxRange < range) - maxRange = range; - } - - return maxRange; - } - - public TravelRangeType getRangeType() - { - return rangeType; - } - - public void setRangeType(TravelRangeType rangeType) - { - this.rangeType = rangeType; - } - - public RouteSearchParameters getRouteSearchParameters() - { - return routeSearchParams; - } - - public void setRouteSearchParameters(RouteSearchParameters routeSearchParams) { - this.routeSearchParams = routeSearchParams; - } - - public String getLocationType() { - return locationType; - } - - public void setLocationType(String locationType) { - this.locationType = locationType; - } +public class TravellerInfo { + private String id = "0"; + private Coordinate location; + private String locationType = "start"; // either start or destination + private double[] ranges; + private TravelRangeType rangeType = TravelRangeType.TIME; + private RouteSearchParameters routeSearchParams; + + public TravellerInfo() { + routeSearchParams = new RouteSearchParameters(); + } + + public TravellerInfo(TravellerInfo old) { + this.id = old.id; + this.location = old.location; + this.locationType = old.locationType; + this.ranges = old.ranges; + this.rangeType = old.rangeType; + this.routeSearchParams = old.routeSearchParams; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Coordinate getLocation() { + return location; + } + + public void setLocation(Coordinate location) { + this.location = location; + } + + public double[] getRanges() { + return ranges; + } + + /** + * Returns the range specified in the unit given by the user. The algorithm converts + * the input range to m so we need to convert it back. + * + * @param unit the unit to return in + * @return the ranges array in the specified unit + */ + + public double[] getRangesInUnit(String unit) { + // convert ranges from meters to user specified unit + double[] rangesInUnit = new double[ranges.length]; + + if (!(unit == null || "m".equalsIgnoreCase(unit))) { + double scale = 1.0; + if (rangeType == TravelRangeType.DISTANCE) { + switch (unit) { + case "km": + scale = 1 / 1000.0; + break; + case "mi": + scale = 1 / 1609.34; + break; + default: + case "m": + break; + } + } + + if (scale != 1.0) { + for (int i = 0; i < ranges.length; i++) + rangesInUnit[i] = ranges[i] * scale; + return rangesInUnit; + } + return ranges; + } + return ranges; + } + + public void setRanges(double range, double interval) { + int nRanges = (int) Math.ceil(range / interval); + ranges = new double[nRanges]; + for (int i = 0; i < nRanges - 1; i++) + ranges[i] = (i + 1) * interval; + + ranges[nRanges - 1] = range; + } + + public void setRanges(double[] ranges) { + this.ranges = ranges; + } + + public double getMaximumRange() { + double maxRange = Double.MIN_VALUE; + + for (double range : ranges) { + if (maxRange < range) + maxRange = range; + } + + return maxRange; + } + + public TravelRangeType getRangeType() { + return rangeType; + } + + public void setRangeType(TravelRangeType rangeType) { + this.rangeType = rangeType; + } + + public RouteSearchParameters getRouteSearchParameters() { + return routeSearchParams; + } + + public void setRouteSearchParameters(RouteSearchParameters routeSearchParams) { + this.routeSearchParams = routeSearchParams; + } + + public String getLocationType() { + return locationType; + } + + public void setLocationType(String locationType) { + this.locationType = locationType; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/EmptyElementException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/EmptyElementException.java index b6499bf588..ab55f4e24f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/EmptyElementException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/EmptyElementException.java @@ -1,26 +1,24 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; import org.heigit.ors.common.StatusCode; -public class EmptyElementException extends StatusCodeException -{ - private static final long serialVersionUID = -2004840251219099113L; +public class EmptyElementException extends StatusCodeException { + private static final long serialVersionUID = -2004840251219099113L; - public EmptyElementException(int errorCode, String message) - { - super(StatusCode.INTERNAL_SERVER_ERROR, errorCode, message); - } + public EmptyElementException(int errorCode, String message) { + super(StatusCode.INTERNAL_SERVER_ERROR, errorCode, message); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/IncompatibleParameterException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/IncompatibleParameterException.java index e5d57b1416..de2f954043 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/IncompatibleParameterException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/IncompatibleParameterException.java @@ -5,13 +5,11 @@ public class IncompatibleParameterException extends StatusCodeException { private static final long serialVersionUID = 1527301848566685803L; - public IncompatibleParameterException(int errorCode, String paramName, String paramValue, String invalidWithName, String invalidWithValue) - { + public IncompatibleParameterException(int errorCode, String paramName, String paramValue, String invalidWithName, String invalidWithValue) { super(StatusCode.BAD_REQUEST, errorCode, paramName + " - " + paramValue + " is not valid with " + invalidWithName + " - " + invalidWithValue); } - public IncompatibleParameterException(int errorCode, String param1, String param2) - { + public IncompatibleParameterException(int errorCode, String param1, String param2) { super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + param1 + "' is incompatible with parameter '" + param2 + "'."); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/InternalServerException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/InternalServerException.java index d8712dd996..f5d218eda7 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/InternalServerException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/InternalServerException.java @@ -1,40 +1,36 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; import org.heigit.ors.common.StatusCode; -public class InternalServerException extends StatusCodeException -{ - private static final long serialVersionUID = -1504840251219099113L; - - public InternalServerException() - { - this(1); - } - - public InternalServerException(int errorCode) - { - super(StatusCode.INTERNAL_SERVER_ERROR, errorCode, "Unknown internal server error has occured."); - } - - public InternalServerException(int errorCode, String message) - { - super(StatusCode.INTERNAL_SERVER_ERROR, errorCode, message); - } - - public InternalServerException(String message) { - super(StatusCode.INTERNAL_SERVER_ERROR, message); - } +public class InternalServerException extends StatusCodeException { + private static final long serialVersionUID = -1504840251219099113L; + + public InternalServerException() { + this(1); + } + + public InternalServerException(int errorCode) { + super(StatusCode.INTERNAL_SERVER_ERROR, errorCode, "Unknown internal server error has occured."); + } + + public InternalServerException(int errorCode, String message) { + super(StatusCode.INTERNAL_SERVER_ERROR, errorCode, message); + } + + public InternalServerException(String message) { + super(StatusCode.INTERNAL_SERVER_ERROR, message); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/MissingParameterException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/MissingParameterException.java index e4eab48af7..cd9c7a5a4d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/MissingParameterException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/MissingParameterException.java @@ -1,31 +1,28 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; import org.heigit.ors.common.StatusCode; -public class MissingParameterException extends StatusCodeException -{ - private static final long serialVersionUID = 507243355121086541L; +public class MissingParameterException extends StatusCodeException { + private static final long serialVersionUID = 507243355121086541L; - public MissingParameterException(int errorCode, String paramName) - { - super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "' is missing."); - } - - public MissingParameterException(String paramName) - { - this(0, paramName); - } + public MissingParameterException(int errorCode, String paramName) { + super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "' is missing."); + } + + public MissingParameterException(String paramName) { + this(0, paramName); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterOutOfRangeException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterOutOfRangeException.java index a95e2a2649..6fb94c1456 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterOutOfRangeException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterOutOfRangeException.java @@ -1,40 +1,36 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; import org.heigit.ors.common.StatusCode; -public class ParameterOutOfRangeException extends StatusCodeException -{ - private static final long serialVersionUID = 7728944138955234463L; - - public ParameterOutOfRangeException(int errorCode, String paramName) - { - super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "' is out of range."); - } - - public ParameterOutOfRangeException(int errorCode, String paramName, String customMessage) - { - super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "' is out of range: " + customMessage); - } - public ParameterOutOfRangeException(int errorCode, String paramName, String value, String maxRangeValue) - { - super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "="+ value +"' is out of range. Maximum possible value is " + maxRangeValue + "."); - } - - public ParameterOutOfRangeException(String paramName, String value, String maxRangeValue) - { - this(-1, paramName, value, maxRangeValue); - } +public class ParameterOutOfRangeException extends StatusCodeException { + private static final long serialVersionUID = 7728944138955234463L; + + public ParameterOutOfRangeException(int errorCode, String paramName) { + super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "' is out of range."); + } + + public ParameterOutOfRangeException(int errorCode, String paramName, String customMessage) { + super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "' is out of range: " + customMessage); + } + + public ParameterOutOfRangeException(int errorCode, String paramName, String value, String maxRangeValue) { + super(StatusCode.BAD_REQUEST, errorCode, "Parameter '" + paramName + "=" + value + "' is out of range. Maximum possible value is " + maxRangeValue + "."); + } + + public ParameterOutOfRangeException(String paramName, String value, String maxRangeValue) { + this(-1, paramName, value, maxRangeValue); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterValueException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterValueException.java index d969b315cc..f309c38784 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterValueException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/ParameterValueException.java @@ -1,37 +1,36 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; import org.heigit.ors.common.StatusCode; -public class ParameterValueException extends StatusCodeException { - private static final long serialVersionUID = 507243355121086541L; +public class ParameterValueException extends StatusCodeException { + private static final long serialVersionUID = 507243355121086541L; - public ParameterValueException(int errorCode, String paramName) { - super(StatusCode.BAD_REQUEST, errorCode, "Parameter '%s' has incorrect value or format.".formatted(paramName)); - } - - public ParameterValueException(int errorCode, String paramName, String paramValue) { - super(StatusCode.BAD_REQUEST, errorCode, "Parameter '%s' has incorrect value of '%s'.".formatted(paramName, paramValue)); - } + public ParameterValueException(int errorCode, String paramName) { + super(StatusCode.BAD_REQUEST, errorCode, "Parameter '%s' has incorrect value or format.".formatted(paramName)); + } - public ParameterValueException(int errorCode, String paramName, String paramValue, String extraInformation) { + public ParameterValueException(int errorCode, String paramName, String paramValue) { + super(StatusCode.BAD_REQUEST, errorCode, "Parameter '%s' has incorrect value of '%s'.".formatted(paramName, paramValue)); + } + + public ParameterValueException(int errorCode, String paramName, String paramValue, String extraInformation) { super(StatusCode.BAD_REQUEST, errorCode, "Parameter '%s' has incorrect value of '%s'. %s".formatted(paramName, paramValue, extraInformation)); - } - - public ParameterValueException(String paramName) - { - this(0, paramName); - } + } + + public ParameterValueException(String paramName) { + this(0, paramName); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/RouteNotFoundException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/RouteNotFoundException.java index abdca6685d..9df460f425 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/RouteNotFoundException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/RouteNotFoundException.java @@ -14,8 +14,7 @@ public RouteNotFoundException(int errorCode) { this(errorCode, ""); } - public RouteNotFoundException() - { + public RouteNotFoundException() { this(0); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/ServerLimitExceededException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/ServerLimitExceededException.java index cdd39116dc..e79a4401b5 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/ServerLimitExceededException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/ServerLimitExceededException.java @@ -1,31 +1,28 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; import org.heigit.ors.common.StatusCode; -public class ServerLimitExceededException extends StatusCodeException -{ - private static final long serialVersionUID = 7128944138955234463L; +public class ServerLimitExceededException extends StatusCodeException { + private static final long serialVersionUID = 7128944138955234463L; - public ServerLimitExceededException(int errorCode, String message) - { - super(StatusCode.BAD_REQUEST, errorCode, "Request parameters exceed the server configuration limits. " + message); - } - - public ServerLimitExceededException(String message) - { - this(-1, message); - } + public ServerLimitExceededException(int errorCode, String message) { + super(StatusCode.BAD_REQUEST, errorCode, "Request parameters exceed the server configuration limits. " + message); + } + + public ServerLimitExceededException(String message) { + this(-1, message); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/StatusCodeException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/StatusCodeException.java index 9352df6bb3..16b2d4a77c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/StatusCodeException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/StatusCodeException.java @@ -1,53 +1,51 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; -public class StatusCodeException extends Exception { - private static final long serialVersionUID = 5306540089149750357L; - - private int statusCode = 200; - private int internalCode = 0; - - public StatusCodeException(int statusCode, int internalCode) { - super(); - this.statusCode = statusCode; - this.internalCode = internalCode; - } - - public StatusCodeException(int statusCode) { - super(); - this.statusCode = statusCode; - } - - public StatusCodeException(int statusCode, String message) { - super(message); - this.statusCode = statusCode; - } - - public StatusCodeException(int statusCode, int internalCode, String message) { - super(message); - this.statusCode = statusCode; - this.internalCode = internalCode; - } - - public int getStatusCode() - { - return statusCode; - } - - public int getInternalCode() - { - return internalCode; - } +public class StatusCodeException extends Exception { + private static final long serialVersionUID = 5306540089149750357L; + + private int statusCode = 200; + private int internalCode = 0; + + public StatusCodeException(int statusCode, int internalCode) { + super(); + this.statusCode = statusCode; + this.internalCode = internalCode; + } + + public StatusCodeException(int statusCode) { + super(); + this.statusCode = statusCode; + } + + public StatusCodeException(int statusCode, String message) { + super(message); + this.statusCode = statusCode; + } + + public StatusCodeException(int statusCode, int internalCode, String message) { + super(message); + this.statusCode = statusCode; + this.internalCode = internalCode; + } + + public int getStatusCode() { + return statusCode; + } + + public int getInternalCode() { + return internalCode; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterException.java index 2f4a7e8668..29b91da4af 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterException.java @@ -5,8 +5,7 @@ public class UnknownParameterException extends StatusCodeException { private static final long serialVersionUID = 4866998272349837464L; - public UnknownParameterException(int errorCode, String paramName) - { + public UnknownParameterException(int errorCode, String paramName) { super(StatusCode.BAD_REQUEST, errorCode, "Unknown parameter '" + paramName + "'."); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterValueException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterValueException.java index c8fb300399..dd63aecbb6 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterValueException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/UnknownParameterValueException.java @@ -1,25 +1,24 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; import org.heigit.ors.common.StatusCode; -public class UnknownParameterValueException extends StatusCodeException{ - private static final long serialVersionUID = 4866998272349837464L; +public class UnknownParameterValueException extends StatusCodeException { + private static final long serialVersionUID = 4866998272349837464L; - public UnknownParameterValueException(int errorCode, String paramName, String paramValue) - { - super(StatusCode.BAD_REQUEST, errorCode, "Unknown parameter value '" + paramValue + "' for '" + paramName + "'."); - } + public UnknownParameterValueException(int errorCode, String paramName, String paramValue) { + super(StatusCode.BAD_REQUEST, errorCode, "Unknown parameter value '" + paramValue + "' for '" + paramName + "'."); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/exceptions/UnsetParameterException.java b/ors-engine/src/main/java/org/heigit/ors/exceptions/UnsetParameterException.java index 8fd0678e52..6ce7567ed9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/exceptions/UnsetParameterException.java +++ b/ors-engine/src/main/java/org/heigit/ors/exceptions/UnsetParameterException.java @@ -1,23 +1,22 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.exceptions; public class UnsetParameterException extends Exception { - private static final long serialVersionUID = 162435684563245L; - - public UnsetParameterException(String paramName) - { - super("'" + paramName + "' parameter is not set."); - } + private static final long serialVersionUID = 162435684563245L; + + public UnsetParameterException(String paramName) { + super("'" + paramName + "' parameter is not set."); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/export/ExportErrorCodes.java b/ors-engine/src/main/java/org/heigit/ors/export/ExportErrorCodes.java index 8df39aeada..0a8c13d349 100644 --- a/ors-engine/src/main/java/org/heigit/ors/export/ExportErrorCodes.java +++ b/ors-engine/src/main/java/org/heigit/ors/export/ExportErrorCodes.java @@ -10,6 +10,8 @@ public class ExportErrorCodes { public static final int MISMATCHED_INPUT = 7005; public static final int UNSUPPORTED_EXPORT_FORMAT = 7006; public static final int UNKNOWN = 7099; - private ExportErrorCodes() {} + + private ExportErrorCodes() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/export/ExportRequest.java b/ors-engine/src/main/java/org/heigit/ors/export/ExportRequest.java index c0abbe57a0..51375f2dd9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/export/ExportRequest.java +++ b/ors-engine/src/main/java/org/heigit/ors/export/ExportRequest.java @@ -3,20 +3,28 @@ import com.graphhopper.util.shapes.BBox; import org.heigit.ors.common.ServiceRequest; -public class ExportRequest extends ServiceRequest { +public class ExportRequest extends ServiceRequest { private BBox bbox; private int profileType = -1; private boolean debug; - public BBox getBoundingBox() { return this.bbox; } + public BBox getBoundingBox() { + return this.bbox; + } - public void setBoundingBox(BBox bbox) { this.bbox = bbox; } + public void setBoundingBox(BBox bbox) { + this.bbox = bbox; + } - public int getProfileType() { return profileType; } + public int getProfileType() { + return profileType; + } - public void setProfileType(int profileType) { this.profileType = profileType; } + public void setProfileType(int profileType) { + this.profileType = profileType; + } public void setDebug(boolean debug) { this.debug = debug; diff --git a/ors-engine/src/main/java/org/heigit/ors/export/ExportResult.java b/ors-engine/src/main/java/org/heigit/ors/export/ExportResult.java index 7bdacf2f54..797a23cbf1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/export/ExportResult.java +++ b/ors-engine/src/main/java/org/heigit/ors/export/ExportResult.java @@ -1,7 +1,7 @@ package org.heigit.ors.export; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.common.Pair; +import org.locationtech.jts.geom.Coordinate; import java.util.HashMap; import java.util.Map; @@ -13,50 +13,60 @@ public class ExportResult { private ExportWarning warning; - public ExportResult() { - this.locations = new HashMap<>(); - this.edgeWeigths = new HashMap<>(); - this.warning = null; - } + public ExportResult() { + this.locations = new HashMap<>(); + this.edgeWeigths = new HashMap<>(); + this.warning = null; + } - public Map, Double> getEdgeWeigths() { - return edgeWeigths; - } + public Map, Double> getEdgeWeigths() { + return edgeWeigths; + } - public void setEdgeWeigths(Map, Double> edgeWeigths) { - this.edgeWeigths = edgeWeigths; - } + public void setEdgeWeigths(Map, Double> edgeWeigths) { + this.edgeWeigths = edgeWeigths; + } - public void addEdge(Pair edge, Double weight) { - this.edgeWeigths.put(edge, weight); - } + public void addEdge(Pair edge, Double weight) { + this.edgeWeigths.put(edge, weight); + } - public Map getLocations() {return locations; } + public Map getLocations() { + return locations; + } - public void setLocations(Map locations) { - this.locations = locations; - } + public void setLocations(Map locations) { + this.locations = locations; + } - public void addLocation(Integer node, Coordinate coord) { - this.locations.put(node, coord); - } + public void addLocation(Integer node, Coordinate coord) { + this.locations.put(node, coord); + } - public ExportWarning getWarning() { return warning;} + public ExportWarning getWarning() { + return warning; + } - public void setWarning(ExportWarning warning) { this.warning = warning; } + public void setWarning(ExportWarning warning) { + this.warning = warning; + } - public boolean hasWarning() {return this.warning != null; } + public boolean hasWarning() { + return this.warning != null; + } - public Map, Map> getEdgeExtras() { - return edgeExtras; - } + public Map, Map> getEdgeExtras() { + return edgeExtras; + } - public void addEdgeExtra(Pair edge, Map extra) { - if (edgeExtras == null) { - edgeExtras = new HashMap<>(); - } - this.edgeExtras.put(edge, extra); + public void addEdgeExtra(Pair edge, Map extra) { + if (edgeExtras == null) { + edgeExtras = new HashMap<>(); } + this.edgeExtras.put(edge, extra); + } - public boolean hasEdgeExtras() {return edgeExtras != null; } + public boolean hasEdgeExtras() { + return edgeExtras != null; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/export/ExportWarning.java b/ors-engine/src/main/java/org/heigit/ors/export/ExportWarning.java index b7e7f018d1..987014390f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/export/ExportWarning.java +++ b/ors-engine/src/main/java/org/heigit/ors/export/ExportWarning.java @@ -8,7 +8,8 @@ public class ExportWarning { /** * Generate the warning object and initialize the message based on the warning code passed - * @param warning The warning code for the warning that should be generated + * + * @param warning The warning code for the warning that should be generated */ public ExportWarning(int warning) { warningCode = warning; diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/AbstractIsochroneAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/AbstractIsochroneAlgorithm.java index ebdcc02540..16735227cc 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/AbstractIsochroneAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/AbstractIsochroneAlgorithm.java @@ -21,10 +21,10 @@ import com.graphhopper.storage.Graph; import com.graphhopper.storage.NodeAccess; import com.graphhopper.util.EdgeExplorer; -import org.heigit.ors.fastisochrones.storage.BorderNodeDistanceStorage; import org.heigit.ors.fastisochrones.partitioning.storage.CellStorage; -import org.heigit.ors.fastisochrones.storage.EccentricityStorage; import org.heigit.ors.fastisochrones.partitioning.storage.IsochroneNodeStorage; +import org.heigit.ors.fastisochrones.storage.BorderNodeDistanceStorage; +import org.heigit.ors.fastisochrones.storage.EccentricityStorage; /** * Calculates an isochrone using a partitioned and graph. @@ -54,13 +54,13 @@ public abstract class AbstractIsochroneAlgorithm { private boolean alreadyRun; protected AbstractIsochroneAlgorithm(Graph graph, - Weighting weighting, - TraversalMode tMode, - CellStorage cellStorage, - IsochroneNodeStorage isochroneNodeStorage, - EccentricityStorage eccentricityStorage, - BorderNodeDistanceStorage borderNodeDistanceStorage, - EdgeFilter additionalEdgeFilter) { + Weighting weighting, + TraversalMode tMode, + CellStorage cellStorage, + IsochroneNodeStorage isochroneNodeStorage, + EccentricityStorage eccentricityStorage, + BorderNodeDistanceStorage borderNodeDistanceStorage, + EdgeFilter additionalEdgeFilter) { this.weighting = weighting; this.flagEncoder = weighting.getFlagEncoder(); this.traversalMode = tMode; @@ -150,7 +150,8 @@ public void calcIsochroneNodes(int from, double isochroneLimit) { /** * Calculate nodes for a given set of (virtual) from node and non-virtual basenode. Necessary for precomputed information that cannot process virtual nodes. - * @param from virtual start node + * + * @param from virtual start node * @param fromNonVirtual real node closest to virtual start node * @param isochroneLimit limit */ diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Contour.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Contour.java index 66af435298..6850b561b2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Contour.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Contour.java @@ -14,11 +14,11 @@ import com.graphhopper.util.EdgeIterator; import com.graphhopper.util.FetchMode; import com.graphhopper.util.PointList; -import org.locationtech.jts.geom.*; -import org.locationtech.jts.index.quadtree.Quadtree; import org.heigit.ors.fastisochrones.partitioning.storage.CellStorage; import org.heigit.ors.fastisochrones.partitioning.storage.IsochroneNodeStorage; import org.heigit.ors.isochrones.builders.concaveballs.PointItemVisitor; +import org.locationtech.jts.geom.*; +import org.locationtech.jts.index.quadtree.Quadtree; import org.opensphere.geometry.algorithm.ConcaveHullOpenSphere; import java.util.*; diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Eccentricity.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Eccentricity.java index 1ff1ec0bda..d57de68c2b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Eccentricity.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/Eccentricity.java @@ -3,6 +3,7 @@ import com.carrotsearch.hppc.IntHashSet; import com.carrotsearch.hppc.IntObjectHashMap; import com.carrotsearch.hppc.cursors.IntCursor; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.util.AccessFilter; import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.routing.util.FlagEncoder; @@ -10,7 +11,6 @@ import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; import com.graphhopper.storage.GraphHopperStorage; -import com.graphhopper.routing.SPTEntry; import com.graphhopper.storage.index.LocationIndex; import org.heigit.ors.fastisochrones.partitioning.storage.CellStorage; import org.heigit.ors.fastisochrones.partitioning.storage.IsochroneNodeStorage; diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/FastIsochroneAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/FastIsochroneAlgorithm.java index 247dd618c7..b88e03eaf6 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/FastIsochroneAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/FastIsochroneAlgorithm.java @@ -16,11 +16,11 @@ import com.carrotsearch.hppc.IntObjectMap; import com.carrotsearch.hppc.cursors.IntObjectCursor; import com.graphhopper.coll.GHIntObjectHashMap; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; -import com.graphhopper.routing.SPTEntry; import org.heigit.ors.fastisochrones.partitioning.storage.CellStorage; import org.heigit.ors.fastisochrones.partitioning.storage.IsochroneNodeStorage; import org.heigit.ors.fastisochrones.storage.BorderNodeDistanceStorage; diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/FastIsochroneFactory.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/FastIsochroneFactory.java index 53fd58ab36..09e580fbe4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/FastIsochroneFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/FastIsochroneFactory.java @@ -43,7 +43,7 @@ public class FastIsochroneFactory { private List fastIsochroneProfiles; private PreparePartition partition; - private boolean disablingAllowed = true; + private final boolean disablingAllowed = true; private boolean enabled = false; private IsochroneNodeStorage isochroneNodeStorage; private CellStorage cellStorage; @@ -88,7 +88,6 @@ public PreparePartition getPartition() { } - public void prepare(final StorableProperties properties) { ExecutorService threadPool = Executors.newFixedThreadPool(1); ExecutorCompletionService completionService = new ExecutorCompletionService<>(threadPool); diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/InertialFlow.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/InertialFlow.java index 66e94ab5a1..08984ef57f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/InertialFlow.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/partitioning/InertialFlow.java @@ -250,7 +250,7 @@ public Set separateDisconnected(IntHashSet nodeSet) { EdgeIterator edgeIterator; EdgeFilterSequence edgeFilterSequence = new EdgeFilterSequence(); edgeFilterSequence.add(AccessFilter.allEdges(flagEncoder.getAccessEnc())); - if(edgeFilter != null) + if (edgeFilter != null) edgeFilterSequence.add(edgeFilter); while (!nodeSet.isEmpty()) { diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/BorderNodeDistanceStorage.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/BorderNodeDistanceStorage.java index ca445ad191..e9be16a8d4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/BorderNodeDistanceStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/BorderNodeDistanceStorage.java @@ -73,7 +73,7 @@ public boolean loadExisting() { public void init() { borderNodes.create(1000); getNumBorderNodes(); - borderNodes.ensureCapacity((long) borderNodeCount * byteCount + necessaryCapacity * byteCount + borderNodeCount * 4); + borderNodes.ensureCapacity((long) borderNodeCount * byteCount + (long) necessaryCapacity * byteCount + borderNodeCount * 4L); borderNodes.setHeader(0, borderNodeCount); borderNodeIndexOffset = borderNodeCount * byteCount; borderNodePointer = borderNodeIndexOffset; diff --git a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/EccentricityStorage.java b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/EccentricityStorage.java index 234fcf0485..c69054bd38 100644 --- a/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/EccentricityStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/fastisochrones/storage/EccentricityStorage.java @@ -19,7 +19,6 @@ import com.carrotsearch.hppc.IntLongHashMap; import com.carrotsearch.hppc.cursors.IntLongCursor; -import com.graphhopper.routing.weighting.AbstractWeighting; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.DataAccess; import com.graphhopper.storage.Directory; @@ -27,7 +26,8 @@ import org.heigit.ors.fastisochrones.partitioning.storage.IsochroneNodeStorage; import org.heigit.ors.util.FileUtility; -import static org.heigit.ors.fastisochrones.storage.ByteConversion.*; +import static org.heigit.ors.fastisochrones.storage.ByteConversion.byteArrayToLong; +import static org.heigit.ors.fastisochrones.storage.ByteConversion.longToByteArray; /** * Stores eccentricities of cell border nodes for fast isochrones. Eccentricities are weighting dependent, therefore they are stored separately from cells. @@ -91,7 +91,7 @@ public void init() { borderNodePointer = borderNodeIndexOffset; borderNodeToPointerMap = new IntLongHashMap(); generateBorderNodeToPointerMap(); - eccentricities.ensureCapacity((long) borderNodeIndexOffset + borderNodeCount * eccentricityBytes); + eccentricities.ensureCapacity((long) borderNodeIndexOffset + (long) borderNodeCount * eccentricityBytes); } private int getNumBorderNodes() { diff --git a/ors-engine/src/main/java/org/heigit/ors/geojson/GeometryJSON.java b/ors-engine/src/main/java/org/heigit/ors/geojson/GeometryJSON.java index 41c1d74901..ad79ef8395 100644 --- a/ors-engine/src/main/java/org/heigit/ors/geojson/GeometryJSON.java +++ b/ors-engine/src/main/java/org/heigit/ors/geojson/GeometryJSON.java @@ -22,160 +22,161 @@ @SuppressWarnings("unchecked") public class GeometryJSON { - private static final int COORDINATE_PRECISION = 6; - private static final GeometryFactory factory = new GeometryFactory(); - - private GeometryJSON() {} - - public static org.json.simple.JSONArray toJSON(Polygon poly) { - org.json.simple.JSONArray coords = new org.json.simple.JSONArray(); - - LineString shell = poly.getExteriorRing(); - - boolean inverse = shell.getNumPoints() > 1 && !CoordinateSequences.isCCW(shell.getCoordinateSequence()); - coords.add(toJSON(shell, inverse)); - - if (poly.getNumInteriorRing() > 0) { - int nRings = poly.getNumInteriorRing(); - - for (int j = 0; j < nRings; ++j) { - LineString ring = poly.getInteriorRingN(j); - inverse = ring.getNumPoints() > 1 && CoordinateSequences.isCCW(ring.getCoordinateSequence()); - coords.add(toJSON(ring, inverse)); - } - } - - return coords; - } - - private static org.json.simple.JSONArray toJSON(LineString line, boolean inverseSeq) { - // "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] - int size = line.getNumPoints(); - - org.json.simple.JSONArray arrCoords = new org.json.simple.JSONArray(); - - CoordinateSequence seq = line.getCoordinateSequence(); - - for (int i = 0; i < size; ++i) { - Coordinate coord = seq.getCoordinate(inverseSeq ? size - i - 1: i); - arrCoords.add(toJSON(coord)); - } - - return arrCoords; - } - - private static org.json.simple.JSONArray toJSON(Point point) { - return toJSON(point.getCoordinate()); - } - - public static org.json.simple.JSONArray toJSON(Coordinate c) { - org.json.simple.JSONArray arrCoords = new org.json.simple.JSONArray(); - arrCoords.add(FormatUtility.roundToDecimals(c.x, COORDINATE_PRECISION)); - arrCoords.add(FormatUtility.roundToDecimals(c.y, COORDINATE_PRECISION)); - - return arrCoords; - } - - public static org.json.simple.JSONArray toJSON(Coordinate[] coords, boolean includeElevation) { - org.json.simple.JSONArray arrCoords = new org.json.simple.JSONArray(); - for (Coordinate c : coords) { - org.json.simple.JSONArray coord = new org.json.simple.JSONArray(); - coord.add(FormatUtility.roundToDecimals(c.x, COORDINATE_PRECISION)); - coord.add(FormatUtility.roundToDecimals(c.y, COORDINATE_PRECISION)); - if (includeElevation) - coord.add(FormatUtility.roundToDecimals(c.z, 1)); - arrCoords.add(coord); - } - return arrCoords; - } - - public static Geometry parse(JSONObject json) throws Exception { - if (!json.has("type")) - throw new Exception("type element is missing."); - - if (!json.has("coordinates")) - throw new Exception("coordinates element is missing."); - - String type = json.getString("type"); - JSONArray arrCoords = json.getJSONArray("coordinates"); - return switch (type) { - case "Point" -> readPoint(arrCoords); - case "MultiPoint" -> readMultiPoint(arrCoords); - case "LineString" -> readLineString(arrCoords); - case "MultiLineString" -> readMultiLineString(arrCoords); - case "Polygon" -> readPolygon(arrCoords); - case "MultiPolygon" -> readMultiPolygon(arrCoords); - default -> throw new Exception("invalid type: " + type); - }; - } - - private static Point readPoint(JSONArray value) { - Coordinate c = new Coordinate(value.getDouble(0), value.getDouble(1)); - return factory.createPoint(c); - } - - private static MultiPoint readMultiPoint(JSONArray value) { - return factory.createMultiPointFromCoords(readCoordinates(value)); - } - - private static LineString readLineString(JSONArray value) { - return factory.createLineString(readCoordinates(value)); - } - - private static MultiLineString readMultiLineString(JSONArray value) { - int n = value.length(); - LineString[] lineStrings = new LineString[n]; - - for (int i = 0; i < n; i++) { - JSONArray arrLineString = (JSONArray) value.get(i); - lineStrings[i] = readLineString(arrLineString); - } - - return factory.createMultiLineString(lineStrings); - } - - private static MultiPolygon readMultiPolygon(JSONArray value) { - int n = value.length(); - Polygon[] polys = new Polygon[n]; - - for (int i = 0; i < n; i++) { - JSONArray arrPoly = (JSONArray) value.get(i); - polys[i] = readPolygon(arrPoly); - } - - return factory.createMultiPolygon(polys); - } - - private static Polygon readPolygon(JSONArray value) { - int n = value.length(); - - LinearRing shell = null; - LinearRing[] holes = new LinearRing[n-1]; - - for (int i = 0; i < n; i++) { - JSONArray arrLineString = (JSONArray) value.get(i); - if (i == 0) - shell = factory.createLinearRing(readCoordinates(arrLineString)); - else - holes[i-1] = factory.createLinearRing(readCoordinates(arrLineString)); - } - - if (holes.length == 0) - return factory.createPolygon(shell); - else - return factory.createPolygon(shell, holes); - } - - private static Coordinate[] readCoordinates(JSONArray value) { - int n = value.length(); - - Coordinate[] coords = new Coordinate[n]; - - for (int i = 0; i < n; i++) { - JSONArray arrCoord = value.getJSONArray(i); - coords[i] = new Coordinate(arrCoord.getDouble(0), arrCoord.getDouble(1)); - } - - return coords; - } + private static final int COORDINATE_PRECISION = 6; + private static final GeometryFactory factory = new GeometryFactory(); + + private GeometryJSON() { + } + + public static org.json.simple.JSONArray toJSON(Polygon poly) { + org.json.simple.JSONArray coords = new org.json.simple.JSONArray(); + + LineString shell = poly.getExteriorRing(); + + boolean inverse = shell.getNumPoints() > 1 && !CoordinateSequences.isCCW(shell.getCoordinateSequence()); + coords.add(toJSON(shell, inverse)); + + if (poly.getNumInteriorRing() > 0) { + int nRings = poly.getNumInteriorRing(); + + for (int j = 0; j < nRings; ++j) { + LineString ring = poly.getInteriorRingN(j); + inverse = ring.getNumPoints() > 1 && CoordinateSequences.isCCW(ring.getCoordinateSequence()); + coords.add(toJSON(ring, inverse)); + } + } + + return coords; + } + + private static org.json.simple.JSONArray toJSON(LineString line, boolean inverseSeq) { + // "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] + int size = line.getNumPoints(); + + org.json.simple.JSONArray arrCoords = new org.json.simple.JSONArray(); + + CoordinateSequence seq = line.getCoordinateSequence(); + + for (int i = 0; i < size; ++i) { + Coordinate coord = seq.getCoordinate(inverseSeq ? size - i - 1 : i); + arrCoords.add(toJSON(coord)); + } + + return arrCoords; + } + + private static org.json.simple.JSONArray toJSON(Point point) { + return toJSON(point.getCoordinate()); + } + + public static org.json.simple.JSONArray toJSON(Coordinate c) { + org.json.simple.JSONArray arrCoords = new org.json.simple.JSONArray(); + arrCoords.add(FormatUtility.roundToDecimals(c.x, COORDINATE_PRECISION)); + arrCoords.add(FormatUtility.roundToDecimals(c.y, COORDINATE_PRECISION)); + + return arrCoords; + } + + public static org.json.simple.JSONArray toJSON(Coordinate[] coords, boolean includeElevation) { + org.json.simple.JSONArray arrCoords = new org.json.simple.JSONArray(); + for (Coordinate c : coords) { + org.json.simple.JSONArray coord = new org.json.simple.JSONArray(); + coord.add(FormatUtility.roundToDecimals(c.x, COORDINATE_PRECISION)); + coord.add(FormatUtility.roundToDecimals(c.y, COORDINATE_PRECISION)); + if (includeElevation) + coord.add(FormatUtility.roundToDecimals(c.z, 1)); + arrCoords.add(coord); + } + return arrCoords; + } + + public static Geometry parse(JSONObject json) throws Exception { + if (!json.has("type")) + throw new Exception("type element is missing."); + + if (!json.has("coordinates")) + throw new Exception("coordinates element is missing."); + + String type = json.getString("type"); + JSONArray arrCoords = json.getJSONArray("coordinates"); + return switch (type) { + case "Point" -> readPoint(arrCoords); + case "MultiPoint" -> readMultiPoint(arrCoords); + case "LineString" -> readLineString(arrCoords); + case "MultiLineString" -> readMultiLineString(arrCoords); + case "Polygon" -> readPolygon(arrCoords); + case "MultiPolygon" -> readMultiPolygon(arrCoords); + default -> throw new Exception("invalid type: " + type); + }; + } + + private static Point readPoint(JSONArray value) { + Coordinate c = new Coordinate(value.getDouble(0), value.getDouble(1)); + return factory.createPoint(c); + } + + private static MultiPoint readMultiPoint(JSONArray value) { + return factory.createMultiPointFromCoords(readCoordinates(value)); + } + + private static LineString readLineString(JSONArray value) { + return factory.createLineString(readCoordinates(value)); + } + + private static MultiLineString readMultiLineString(JSONArray value) { + int n = value.length(); + LineString[] lineStrings = new LineString[n]; + + for (int i = 0; i < n; i++) { + JSONArray arrLineString = (JSONArray) value.get(i); + lineStrings[i] = readLineString(arrLineString); + } + + return factory.createMultiLineString(lineStrings); + } + + private static MultiPolygon readMultiPolygon(JSONArray value) { + int n = value.length(); + Polygon[] polys = new Polygon[n]; + + for (int i = 0; i < n; i++) { + JSONArray arrPoly = (JSONArray) value.get(i); + polys[i] = readPolygon(arrPoly); + } + + return factory.createMultiPolygon(polys); + } + + private static Polygon readPolygon(JSONArray value) { + int n = value.length(); + + LinearRing shell = null; + LinearRing[] holes = new LinearRing[n - 1]; + + for (int i = 0; i < n; i++) { + JSONArray arrLineString = (JSONArray) value.get(i); + if (i == 0) + shell = factory.createLinearRing(readCoordinates(arrLineString)); + else + holes[i - 1] = factory.createLinearRing(readCoordinates(arrLineString)); + } + + if (holes.length == 0) + return factory.createPolygon(shell); + else + return factory.createPolygon(shell, holes); + } + + private static Coordinate[] readCoordinates(JSONArray value) { + int n = value.length(); + + Coordinate[] coords = new Coordinate[n]; + + for (int i = 0; i < n; i++) { + JSONArray arrCoord = value.getJSONArray(i); + coords[i] = new Coordinate(arrCoord.getDouble(0), arrCoord.getDouble(1)); + } + + return coords; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/io/ByteArrayOutputStreamEx.java b/ors-engine/src/main/java/org/heigit/ors/io/ByteArrayOutputStreamEx.java index 4d39b1a189..f6ac8565af 100644 --- a/ors-engine/src/main/java/org/heigit/ors/io/ByteArrayOutputStreamEx.java +++ b/ors-engine/src/main/java/org/heigit/ors/io/ByteArrayOutputStreamEx.java @@ -1,35 +1,33 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.io; import java.io.ByteArrayOutputStream; -public class ByteArrayOutputStreamEx extends ByteArrayOutputStream -{ - public ByteArrayOutputStreamEx() - { - super(); - } +public class ByteArrayOutputStreamEx extends ByteArrayOutputStream { + public ByteArrayOutputStreamEx() { + super(); + } - public ByteArrayOutputStreamEx(int size) - { - super(size); - } + public ByteArrayOutputStreamEx(int size) { + super(size); + } - /** Returns the internal buffer of this ByteArrayOutputStream, without copying. */ - public synchronized byte[] getBuffer() - { - return this.buf; - } + /** + * Returns the internal buffer of this ByteArrayOutputStream, without copying. + */ + public synchronized byte[] getBuffer() { + return this.buf; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/EdgeInfo.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/EdgeInfo.java index a423ebb7ab..e81fe5564e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/EdgeInfo.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/EdgeInfo.java @@ -1,58 +1,52 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.isochrones; import com.graphhopper.util.PointList; public class EdgeInfo { - private final PointList geometry; - private final float v1; - private final float v2; - private final float dist; - private final long edgeId; - - public EdgeInfo(long id, PointList geom, float v1, float v2, float dist) - { - this.edgeId = id; - this.geometry = geom; - this.v1 = v1; - this.v2 = v2; - this.dist = dist; - } - - public long getEdge() - { - return edgeId; - } - - public PointList getGeometry() - { - return this.geometry; - } - - public float getV1() - { - return this.v1; - } - - public float getV2() - { - return this.v2; - } - - public float getDistance() - { - return this.dist; - } + private final PointList geometry; + private final float v1; + private final float v2; + private final float dist; + private final long edgeId; + + public EdgeInfo(long id, PointList geom, float v1, float v2, float dist) { + this.edgeId = id; + this.geometry = geom; + this.v1 = v1; + this.v2 = v2; + this.dist = dist; + } + + public long getEdge() { + return edgeId; + } + + public PointList getGeometry() { + return this.geometry; + } + + public float getV1() { + return this.v1; + } + + public float getV2() { + return this.v2; + } + + public float getDistance() { + return this.dist; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/GraphEdgeMapFinder.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/GraphEdgeMapFinder.java index 01f6a26288..4059284349 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/GraphEdgeMapFinder.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/GraphEdgeMapFinder.java @@ -15,6 +15,7 @@ import com.carrotsearch.hppc.IntObjectMap; import com.graphhopper.GraphHopper; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.querygraph.QueryGraph; import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.routing.util.FlagEncoder; @@ -22,10 +23,8 @@ import com.graphhopper.routing.weighting.FastestWeighting; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.GraphHopperStorage; -import com.graphhopper.routing.SPTEntry; import com.graphhopper.storage.index.Snap; import com.graphhopper.util.shapes.GHPoint3D; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.common.TravelRangeType; import org.heigit.ors.exceptions.InternalServerException; import org.heigit.ors.routing.RouteSearchContext; @@ -35,6 +34,7 @@ import org.heigit.ors.routing.graphhopper.extensions.ORSEdgeFilterFactory; import org.heigit.ors.routing.graphhopper.extensions.weighting.DistanceWeighting; import org.heigit.ors.routing.traffic.TrafficSpeedCalculator; +import org.locationtech.jts.geom.Coordinate; import java.time.ZonedDateTime; import java.util.ArrayList; @@ -49,14 +49,14 @@ public static AccessibilityMap findEdgeMap(RouteSearchContext searchCntx, Isochr FlagEncoder encoder = searchCntx.getEncoder(); GraphHopperStorage graph = gh.getGraphHopperStorage(); - ORSEdgeFilterFactory edgeFilterFactory = new ORSEdgeFilterFactory(); - EdgeFilter edgeFilter = edgeFilterFactory.createEdgeFilter(searchCntx.getProperties(), encoder, graph); + ORSEdgeFilterFactory edgeFilterFactory = new ORSEdgeFilterFactory(); + EdgeFilter edgeFilter = edgeFilterFactory.createEdgeFilter(searchCntx.getProperties(), encoder, graph); - Coordinate loc = parameters.getLocation(); - Snap res = gh.getLocationIndex().findClosest(loc.y, loc.x, edgeFilter); - List snaps = new ArrayList<>(1); - snaps.add(res); - QueryGraph queryGraph = QueryGraph.create(graph, snaps); + Coordinate loc = parameters.getLocation(); + Snap res = gh.getLocationIndex().findClosest(loc.y, loc.x, edgeFilter); + List snaps = new ArrayList<>(1); + snaps.add(res); + QueryGraph queryGraph = QueryGraph.create(graph, snaps); GHPoint3D snappedPosition = res.getSnappedPoint(); diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/Isochrone.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/Isochrone.java index 7ebcfae7fd..63455b56f4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/Isochrone.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/Isochrone.java @@ -13,12 +13,12 @@ */ package org.heigit.ors.isochrones; -import org.locationtech.jts.geom.Envelope; -import org.locationtech.jts.geom.Geometry; import org.heigit.ors.common.AttributeValue; import org.heigit.ors.util.FormatUtility; import org.heigit.ors.util.GeomUtility; import org.heigit.ors.util.UnitsConverter; +import org.locationtech.jts.geom.Envelope; +import org.locationtech.jts.geom.Geometry; import java.util.ArrayList; import java.util.List; diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMap.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMap.java index 10da4644ff..2c3826e610 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMap.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMap.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.isochrones; @@ -20,63 +20,57 @@ import java.util.List; public class IsochroneMap { - private final int travellerId; - private final Envelope envelope; - private final List isochrones; - private final Coordinate center; - private String graphDate; + private final int travellerId; + private final Envelope envelope; + private final List isochrones; + private final Coordinate center; + private String graphDate; public IsochroneMap(int travellerId, Coordinate center) { - this.travellerId = travellerId; - this.center = center; - isochrones = new ArrayList<>(); - envelope = new Envelope(); - } - - public int getTravellerId() - { - return travellerId; - } - - public boolean isEmpty() - { - return isochrones.isEmpty(); - } - - public Coordinate getCenter() - { - return center; - } - - public Iterable getIsochrones() - { - return isochrones; - } - - public int getIsochronesCount() - { - return isochrones.size(); - } - - public Isochrone getIsochrone(int index) - { - return isochrones.get(index); - } - - public void addIsochrone(Isochrone isochrone) { - isochrones.add(isochrone); - envelope.expandToInclude(isochrone.getGeometry().getEnvelopeInternal()); - } - public Envelope getEnvelope() - { - return envelope; - } - - public String getGraphDate () { - return graphDate; - } - - public void setGraphDate(String graphDate) { - this.graphDate = graphDate; - } + this.travellerId = travellerId; + this.center = center; + isochrones = new ArrayList<>(); + envelope = new Envelope(); + } + + public int getTravellerId() { + return travellerId; + } + + public boolean isEmpty() { + return isochrones.isEmpty(); + } + + public Coordinate getCenter() { + return center; + } + + public Iterable getIsochrones() { + return isochrones; + } + + public int getIsochronesCount() { + return isochrones.size(); + } + + public Isochrone getIsochrone(int index) { + return isochrones.get(index); + } + + public void addIsochrone(Isochrone isochrone) { + isochrones.add(isochrone); + envelope.expandToInclude(isochrone.getGeometry().getEnvelopeInternal()); + } + + public Envelope getEnvelope() { + return envelope; + } + + public String getGraphDate() { + return graphDate; + } + + public void setGraphDate(String graphDate) { + this.graphDate = graphDate; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMapCollection.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMapCollection.java index 2262bf8033..cf5b30e801 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMapCollection.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneMapCollection.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.isochrones; @@ -17,31 +17,27 @@ import java.util.List; public class IsochroneMapCollection { - private int nIsochrones = 0; - private final List isochroneMaps = new ArrayList<>(); - - public void add(IsochroneMap map) { - isochroneMaps.add(map); - nIsochrones += map.getIsochronesCount(); - } - - public Iterable getIsochroneMaps() - { - return isochroneMaps; - } - - public IsochroneMap getIsochrone(int index) - { - return isochroneMaps.get(index); - } - - public int getIsochronesCount() - { - return nIsochrones; - } - - public int size() - { - return isochroneMaps.size(); - } + private int nIsochrones = 0; + private final List isochroneMaps = new ArrayList<>(); + + public void add(IsochroneMap map) { + isochroneMaps.add(map); + nIsochrones += map.getIsochronesCount(); + } + + public Iterable getIsochroneMaps() { + return isochroneMaps; + } + + public IsochroneMap getIsochrone(int index) { + return isochroneMaps.get(index); + } + + public int getIsochronesCount() { + return nIsochrones; + } + + public int size() { + return isochroneMaps.size(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneSearchParameters.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneSearchParameters.java index 08ff47337a..2378d70bad 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneSearchParameters.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneSearchParameters.java @@ -13,11 +13,10 @@ */ package org.heigit.ors.isochrones; -import org.heigit.ors.isochrones.statistics.StatisticsProviderConfiguration; -import org.locationtech.jts.geom.Coordinate; - import org.heigit.ors.common.TravelRangeType; +import org.heigit.ors.isochrones.statistics.StatisticsProviderConfiguration; import org.heigit.ors.routing.RouteSearchParameters; +import org.locationtech.jts.geom.Coordinate; import java.util.Map; diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneUtility.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneUtility.java index 8b2b48a755..6dbfcf640e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochroneUtility.java @@ -1,103 +1,103 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.isochrones; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - +import org.heigit.ors.common.Pair; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; -import org.heigit.ors.common.Pair; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; public class IsochroneUtility { - private IsochroneUtility() {} + private IsochroneUtility() { + } - public static List computeIntersections(IsochroneMapCollection isochroneMaps) { - List result = new ArrayList<>(); - if (isochroneMaps.size() == 1) - return result; + public static List computeIntersections(IsochroneMapCollection isochroneMaps) { + List result = new ArrayList<>(); + if (isochroneMaps.size() == 1) + return result; - int im = 0; - for (IsochroneMap isoMap : isochroneMaps.getIsochroneMaps()) { - int ii = 0; - for (Isochrone isoLine : isoMap.getIsochrones()) { - List isoIntersection = computeIntersection(isoLine, ii, isoMap, im, isochroneMaps); - if (!isoIntersection.isEmpty()) { - result.addAll(isoIntersection); - } - ii++; - } - im++; - } + int im = 0; + for (IsochroneMap isoMap : isochroneMaps.getIsochroneMaps()) { + int ii = 0; + for (Isochrone isoLine : isoMap.getIsochrones()) { + List isoIntersection = computeIntersection(isoLine, ii, isoMap, im, isochroneMaps); + if (!isoIntersection.isEmpty()) { + result.addAll(isoIntersection); + } + ii++; + } + im++; + } - // Find intersections between IsochronesIntersection objects - if (result.size() > 1) { - List isoIntersections = new ArrayList<>(); - int i = 0; - for (IsochronesIntersection isoIntersection : result) { - List overlaps = computeIntersection(isoIntersection, i, result); - if (!overlaps.isEmpty()) { - isoIntersections.addAll(overlaps); - } + // Find intersections between IsochronesIntersection objects + if (result.size() > 1) { + List isoIntersections = new ArrayList<>(); + int i = 0; + for (IsochronesIntersection isoIntersection : result) { + List overlaps = computeIntersection(isoIntersection, i, result); + if (!overlaps.isEmpty()) { + isoIntersections.addAll(overlaps); + } i++; - } - if (!isoIntersections.isEmpty()) - result.addAll(isoIntersections); - } - return result; - } + } + if (!isoIntersections.isEmpty()) + result.addAll(isoIntersections); + } + return result; + } - private static List computeIntersection(IsochronesIntersection isoIntersection, Integer intersectionIndex, List intersections) { - List result = new ArrayList<>(); - for (int i = intersectionIndex + 1 ; i < intersections.size(); i++) { - IsochronesIntersection isoIntersection2 = intersections.get(i); - if (isoIntersection.intersects(isoIntersection2)) { - Geometry geomIntersection = isoIntersection.getGeometry().intersection(isoIntersection2.getGeometry()); - if (geomIntersection != null) { - IsochronesIntersection isoIntersectionNew = new IsochronesIntersection(geomIntersection); - isoIntersectionNew.addContourRefs(isoIntersection.getContourRefs()); - isoIntersectionNew.addContourRefs(isoIntersection2.getContourRefs()); - } - } - } - return result; - } + private static List computeIntersection(IsochronesIntersection isoIntersection, Integer intersectionIndex, List intersections) { + List result = new ArrayList<>(); + for (int i = intersectionIndex + 1; i < intersections.size(); i++) { + IsochronesIntersection isoIntersection2 = intersections.get(i); + if (isoIntersection.intersects(isoIntersection2)) { + Geometry geomIntersection = isoIntersection.getGeometry().intersection(isoIntersection2.getGeometry()); + if (geomIntersection != null) { + IsochronesIntersection isoIntersectionNew = new IsochronesIntersection(geomIntersection); + isoIntersectionNew.addContourRefs(isoIntersection.getContourRefs()); + isoIntersectionNew.addContourRefs(isoIntersection2.getContourRefs()); + } + } + } + return result; + } - private static List computeIntersection(Isochrone isoLine, Integer isoIndex, IsochroneMap isoMap, Integer isoMapIndex, IsochroneMapCollection isochroneMaps) { - List result = new ArrayList<>(); - Envelope isoEnvelope = isoLine.getEnvelope(); - Geometry isoGeometry = isoLine.getGeometry(); - for (int im = isoMapIndex + 1; im < isochroneMaps.size(); im++) { - IsochroneMap isoMap2 = isochroneMaps.getIsochrone(im); - if (!Objects.equals(isoMap2, isoMap) && isoMap2.getEnvelope().intersects(isoEnvelope)) { - int ii = 0; - for (Isochrone isoLine2 : isoMap2.getIsochrones()) { - if (isoEnvelope.intersects(isoLine2.getEnvelope())) { - Geometry geomIntersection = isoGeometry.intersection(isoLine2.getGeometry()); - if (geomIntersection != null && !geomIntersection.isEmpty()) { - IsochronesIntersection isoIntersection = new IsochronesIntersection(geomIntersection); - isoIntersection.addContourRefs(new Pair<>(isoMapIndex, isoIndex)); - isoIntersection.addContourRefs(new Pair<>(im, ii)); - result.add(isoIntersection); - } - } - ii++; - } - } - } - return result; - } + private static List computeIntersection(Isochrone isoLine, Integer isoIndex, IsochroneMap isoMap, Integer isoMapIndex, IsochroneMapCollection isochroneMaps) { + List result = new ArrayList<>(); + Envelope isoEnvelope = isoLine.getEnvelope(); + Geometry isoGeometry = isoLine.getGeometry(); + for (int im = isoMapIndex + 1; im < isochroneMaps.size(); im++) { + IsochroneMap isoMap2 = isochroneMaps.getIsochrone(im); + if (!Objects.equals(isoMap2, isoMap) && isoMap2.getEnvelope().intersects(isoEnvelope)) { + int ii = 0; + for (Isochrone isoLine2 : isoMap2.getIsochrones()) { + if (isoEnvelope.intersects(isoLine2.getEnvelope())) { + Geometry geomIntersection = isoGeometry.intersection(isoLine2.getGeometry()); + if (geomIntersection != null && !geomIntersection.isEmpty()) { + IsochronesIntersection isoIntersection = new IsochronesIntersection(geomIntersection); + isoIntersection.addContourRefs(new Pair<>(isoMapIndex, isoIndex)); + isoIntersection.addContourRefs(new Pair<>(im, ii)); + result.add(isoIntersection); + } + } + ii++; + } + } + } + return result; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesErrorCodes.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesErrorCodes.java index 4c4bb8e153..6fc80aee44 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesErrorCodes.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesErrorCodes.java @@ -34,5 +34,6 @@ public class IsochronesErrorCodes { public static final int PARAMETER_VALUE_EXCEEDS_MINIMUM = 3012; public static final int UNKNOWN = 3099; - private IsochronesErrorCodes() {} + private IsochronesErrorCodes() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesIntersection.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesIntersection.java index 1f8a273489..46269ba69e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesIntersection.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/IsochronesIntersection.java @@ -13,75 +13,70 @@ */ package org.heigit.ors.isochrones; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.locationtech.jts.geom.Envelope; -import org.locationtech.jts.geom.Geometry; - +import org.heigit.ors.common.Pair; import org.heigit.ors.exceptions.InternalServerException; import org.heigit.ors.util.FormatUtility; import org.heigit.ors.util.GeomUtility; import org.heigit.ors.util.UnitsConverter; -import org.heigit.ors.common.Pair; - -public class IsochronesIntersection { - private final Geometry geometry; - private Envelope envelope; - private double area = 0.0; - private final List> contourRefs; - - public IsochronesIntersection(Geometry geometry) { - this.geometry = geometry; - contourRefs = new ArrayList<>(); - } - - public List> getContourRefs() - { - return contourRefs; - } - - public void addContourRefs(Pair ref) - { - contourRefs.add(ref); - } - - public void addContourRefs(Collection> refs) - { - contourRefs.addAll(refs); - } - - public Geometry getGeometry() - { - return geometry; - } - - public double getArea(String units) throws InternalServerException { - if (area == 0.0) { - area = FormatUtility.roundToDecimals(GeomUtility.getArea(geometry, true), 2); - } - if (units == null) - units = "m"; - return switch (units) { - case "m" -> area; - case "mi" -> UnitsConverter.sqMetersToSqMiles(this.area); - case "km" -> UnitsConverter.sqMetersToSqKilometers(this.area); - default -> area; - }; - } - - public boolean intersects(IsochronesIntersection other) { - if (!getEnvelope().intersects(other.getEnvelope())) - return false; - - return geometry.intersects(other.geometry); - } +import org.locationtech.jts.geom.Envelope; +import org.locationtech.jts.geom.Geometry; - public Envelope getEnvelope() { - if(envelope == null) - envelope = geometry.getEnvelopeInternal(); +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; - return envelope; - } +public class IsochronesIntersection { + private final Geometry geometry; + private Envelope envelope; + private double area = 0.0; + private final List> contourRefs; + + public IsochronesIntersection(Geometry geometry) { + this.geometry = geometry; + contourRefs = new ArrayList<>(); + } + + public List> getContourRefs() { + return contourRefs; + } + + public void addContourRefs(Pair ref) { + contourRefs.add(ref); + } + + public void addContourRefs(Collection> refs) { + contourRefs.addAll(refs); + } + + public Geometry getGeometry() { + return geometry; + } + + public double getArea(String units) throws InternalServerException { + if (area == 0.0) { + area = FormatUtility.roundToDecimals(GeomUtility.getArea(geometry, true), 2); + } + if (units == null) + units = "m"; + return switch (units) { + case "m" -> area; + case "mi" -> UnitsConverter.sqMetersToSqMiles(this.area); + case "km" -> UnitsConverter.sqMetersToSqKilometers(this.area); + default -> area; + }; + } + + public boolean intersects(IsochronesIntersection other) { + if (!getEnvelope().intersects(other.getEnvelope())) + return false; + + return geometry.intersects(other.geometry); + } + + public Envelope getEnvelope() { + if (envelope == null) + envelope = geometry.getEnvelopeInternal(); + + return envelope; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/IsochroneMapBuilder.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/IsochroneMapBuilder.java index 6d9a86c4f6..45d7355bbe 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/IsochroneMapBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/IsochroneMapBuilder.java @@ -1,25 +1,25 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.isochrones.builders; +import org.heigit.ors.isochrones.IsochroneMap; import org.heigit.ors.isochrones.IsochroneSearchParameters; import org.heigit.ors.routing.RouteSearchContext; -import org.heigit.ors.isochrones.IsochroneMap; public interface IsochroneMapBuilder { - - void initialize(RouteSearchContext searchContext); - - IsochroneMap compute(IsochroneSearchParameters parameters) throws Exception; + + void initialize(RouteSearchContext searchContext); + + IsochroneMap compute(IsochroneSearchParameters parameters) throws Exception; } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/ConcaveBallsIsochroneMapBuilder.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/ConcaveBallsIsochroneMapBuilder.java index e0f70f694d..fc78bd1e07 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/ConcaveBallsIsochroneMapBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/ConcaveBallsIsochroneMapBuilder.java @@ -16,15 +16,13 @@ import com.carrotsearch.hppc.IntObjectMap; import com.carrotsearch.hppc.cursors.IntObjectCursor; import com.graphhopper.coll.GHIntObjectHashMap; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.routing.util.HikeFlagEncoder; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.storage.NodeAccess; -import com.graphhopper.routing.SPTEntry; import com.graphhopper.util.*; import com.graphhopper.util.shapes.GHPoint3D; -import org.locationtech.jts.geom.*; -import org.locationtech.jts.index.quadtree.Quadtree; import org.apache.log4j.Logger; import org.heigit.ors.common.TravelRangeType; import org.heigit.ors.isochrones.GraphEdgeMapFinder; @@ -38,8 +36,9 @@ import org.heigit.ors.routing.graphhopper.extensions.flagencoders.ORSAbstractFlagEncoder; import org.heigit.ors.routing.graphhopper.extensions.flagencoders.WheelchairFlagEncoder; import org.heigit.ors.routing.graphhopper.extensions.flagencoders.bike.CommonBikeFlagEncoder; -import org.heigit.ors.util.DebugUtility; import org.heigit.ors.util.GeomUtility; +import org.locationtech.jts.geom.*; +import org.locationtech.jts.index.quadtree.Quadtree; import org.opensphere.geometry.algorithm.ConcaveHullOpenSphere; import java.util.ArrayList; @@ -49,11 +48,11 @@ public class ConcaveBallsIsochroneMapBuilder implements IsochroneMapBuilder { private static final Logger LOGGER = Logger.getLogger(ConcaveBallsIsochroneMapBuilder.class.getName()); private static final boolean BUFFERED_OUTPUT = true; - private static DistanceCalc dcFast = new DistancePlaneProjection(); + private static final DistanceCalc dcFast = new DistancePlaneProjection(); private double searchWidth = 0.0007; private double pointWidth = 0.0005; private double visitorThreshold = 0.0013; - private Envelope searchEnv = new Envelope(); + private final Envelope searchEnv = new Envelope(); private GeometryFactory geometryFactory; private PointItemVisitor visitor = null; private List prevIsoPoints = null; diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/PointItemVisitor.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/PointItemVisitor.java index ce69eb078b..cdef602dc7 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/PointItemVisitor.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/concaveballs/PointItemVisitor.java @@ -1,65 +1,63 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.isochrones.builders.concaveballs; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.index.ItemVisitor; -public class PointItemVisitor implements ItemVisitor -{ - private double threshold; - private boolean bFound; - private double lat; - private double lon; - - public PointItemVisitor(double lon, double lat, double threshold) { - this.lat = lat; - this.lon = lon; - this.threshold = threshold; - } - - public void setThreshold(double value) - { - threshold = value; - } - - public void setPoint(double lon, double lat) { - this.lat = lat; - this.lon = lon; - bFound = false; - } - - public void visitItem(Object item) { - if (!bFound) { - Coordinate p = (Coordinate) item; - - double dx = p.x - lon; - if (dx > threshold) - return; - - double dy = p.y - lat; - if (Math.abs(dy) > threshold) - return; - - double dist = Math.sqrt(dx*dx+dy*dy); - if (dist < threshold) - bFound = true; - } - } - - public boolean isNeighbourFound() { - return bFound; - } +public class PointItemVisitor implements ItemVisitor { + private double threshold; + private boolean bFound; + private double lat; + private double lon; + + public PointItemVisitor(double lon, double lat, double threshold) { + this.lat = lat; + this.lon = lon; + this.threshold = threshold; + } + + public void setThreshold(double value) { + threshold = value; + } + + public void setPoint(double lon, double lat) { + this.lat = lat; + this.lon = lon; + bFound = false; + } + + public void visitItem(Object item) { + if (!bFound) { + Coordinate p = (Coordinate) item; + + double dx = p.x - lon; + if (dx > threshold) + return; + + double dy = p.y - lat; + if (Math.abs(dy) > threshold) + return; + + double dist = Math.sqrt(dx * dx + dy * dy); + if (dist < threshold) + bFound = true; + } + } + + public boolean isNeighbourFound() { + return bFound; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/fast/FastIsochroneMapBuilder.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/fast/FastIsochroneMapBuilder.java index 537289b60a..2da9392c87 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/fast/FastIsochroneMapBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/builders/fast/FastIsochroneMapBuilder.java @@ -28,9 +28,6 @@ import com.graphhopper.storage.index.Snap; import com.graphhopper.util.*; import com.graphhopper.util.shapes.GHPoint3D; -import org.locationtech.jts.geom.*; -import org.locationtech.jts.index.quadtree.Quadtree; -import org.locationtech.jts.operation.union.UnaryUnionOp; import org.apache.log4j.Logger; import org.heigit.ors.common.TravelRangeType; import org.heigit.ors.exceptions.InternalServerException; @@ -56,6 +53,9 @@ import org.heigit.ors.routing.graphhopper.extensions.flagencoders.WheelchairFlagEncoder; import org.heigit.ors.util.DebugUtility; import org.heigit.ors.util.GeomUtility; +import org.locationtech.jts.geom.*; +import org.locationtech.jts.index.quadtree.Quadtree; +import org.locationtech.jts.operation.union.UnaryUnionOp; import org.opensphere.geometry.algorithm.ConcaveHullOpenSphere; import java.util.*; @@ -325,7 +325,7 @@ private List createCoordinateListFromGeometry(Geometry preprocessedGeome continue; } - LinearRing ring = (LinearRing) ((Polygon) preprocessedGeometry.getGeometryN(j)).getExteriorRing(); + LinearRing ring = ((Polygon) preprocessedGeometry.getGeometryN(j)).getExteriorRing(); for (int i = 0; i < ring.getNumPoints(); i++) { contourCoordinates.add(ring.getCoordinateN(i).y); contourCoordinates.add(ring.getCoordinateN(i).x); @@ -401,7 +401,7 @@ private void createPolyFromPoints(Set isochroneGeometries, GeometryCol ConcaveHullOpenSphere ch = new ConcaveHullOpenSphere(points, convertSmoothingFactorToDistance(smoothingFactor, maxRadius), false); concaveHull = ch.getConcaveHull(); if (concaveHull instanceof Polygon polygon) { - ring = (LinearRing) polygon.getExteriorRing(); + ring = polygon.getExteriorRing(); List coordinates = new ArrayList<>(ring.getNumPoints()); for (int i = 0; i < ring.getNumPoints(); i++) { coordinates.add(ring.getCoordinateN(i)); @@ -731,9 +731,9 @@ private String printCell(List coordinates, int cellId) { statement.append("{\"type\": \"Feature\",\"properties\": {\"name\": \"").append(cellId).append("\"},\"geometry\": {\"type\": \"Polygon\",\"coordinates\": [["); int i; for (i = coordinates.size() - 2; i > 0; i -= 2) { - statement.append("[").append(String.valueOf(coordinates.get(i + 1)).substring(0, Math.min(8, String.valueOf(coordinates.get(i + 1)).length()))).append(",").append(String.valueOf(coordinates.get(i)).substring(0, Math.min(8, String.valueOf(coordinates.get(i)).length()))).append("],"); + statement.append("[").append(String.valueOf(coordinates.get(i + 1)), 0, Math.min(8, String.valueOf(coordinates.get(i + 1)).length())).append(",").append(String.valueOf(coordinates.get(i)), 0, Math.min(8, String.valueOf(coordinates.get(i)).length())).append("],"); } - statement.append("[").append(String.valueOf(coordinates.get(coordinates.size() - 1)).substring(0, Math.min(8, String.valueOf(coordinates.get(coordinates.size() - 1)).length()))).append(",").append(String.valueOf(coordinates.get(coordinates.size() - 2)).substring(0, Math.min(8, String.valueOf(coordinates.get(coordinates.size() - 2)).length()))).append("]"); + statement.append("[").append(String.valueOf(coordinates.get(coordinates.size() - 1)), 0, Math.min(8, String.valueOf(coordinates.get(coordinates.size() - 1)).length())).append(",").append(String.valueOf(coordinates.get(coordinates.size() - 2)), 0, Math.min(8, String.valueOf(coordinates.get(coordinates.size() - 2)).length())).append("]"); statement.append("]]}},"); statement.append(System.lineSeparator()); @@ -782,7 +782,7 @@ private PointList expandAndBufferPointList(PointList list, double bufferSize, do double dy2 = dx * scale; extendedList.add(lat0 + dy2, lon0 + dx2); extendedList.add(lat0 - dy2, lon0 - dx2); - if(i == list.size() - 2) { + if (i == list.size() - 2) { extendedList.add(lat1 + dy2, lon1 + dx2); extendedList.add(lat1 - dy2, lon1 - dx2); } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProvider.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProvider.java index f0affbd3e0..1d1cb77368 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProvider.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProvider.java @@ -4,14 +4,14 @@ * http://www.giscience.uni-hd.de * http://www.heigit.org * - * under one or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information regarding copyright - * ownership. The GIScience licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in compliance + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. The GIScience licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +20,16 @@ */ package org.heigit.ors.isochrones.statistics; -import java.util.Map; - import org.heigit.ors.isochrones.Isochrone; +import java.util.Map; + public interface StatisticsProvider { - void init(Map parameters) throws Exception; - void close() throws Exception; - String getName(); - + void init(Map parameters) throws Exception; + + void close() throws Exception; + + String getName(); + double[] getStatistics(Isochrone isochrone, String[] properties) throws Exception; } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderConfiguration.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderConfiguration.java index aedc9e228c..169e6d9011 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderConfiguration.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderConfiguration.java @@ -4,14 +4,14 @@ * http://www.giscience.uni-hd.de * http://www.heigit.org * - * under one or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information regarding copyright - * ownership. The GIScience licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in compliance + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. The GIScience licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,53 +24,51 @@ import java.util.Map; public class StatisticsProviderConfiguration { - private final int id; - private final String name; - private final Map parameters; - private final Map mapping; - private final String attribution; - - public StatisticsProviderConfiguration(int id, String name, Map parameters, Map mapping, String attribution) { - this.id = id; - this.name = name; - this.parameters = parameters; - this.mapping = mapping; - this.attribution = attribution; - } - - @Override - public int hashCode() - { - return id; - } + private final int id; + private final String name; + private final Map parameters; + private final Map mapping; + private final String attribution; + + public StatisticsProviderConfiguration(int id, String name, Map parameters, Map mapping, String attribution) { + this.id = id; + this.name = name; + this.parameters = parameters; + this.mapping = mapping; + this.attribution = attribution; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public boolean equals(Object obj) { + return obj != null && obj.getClass() == this.getClass() && id == ((StatisticsProviderConfiguration) obj).id; + } + + public int getId() { + return id; + } - @Override - public boolean equals(Object obj) { - return obj != null && obj.getClass() == this.getClass() && id == ((StatisticsProviderConfiguration) obj).id; - } + public String getName() { + return name; + } - public int getId() - { - return id; - } - - public String getName() { - return name; - } + public String getAttribution() { + return attribution; + } - public String getAttribution() { - return attribution; - } + public Map getParameters() { + return parameters; + } - public Map getParameters() { - return parameters; - } - - public String[] getMappedProperties(List props) { - String[] res = new String[props.size()]; - for (int i = 0; i < props.size(); i++) { - res[i] = mapping.get(props.get(i)); - } - return res; - } + public String[] getMappedProperties(List props) { + String[] res = new String[props.size()]; + for (int i = 0; i < props.size(); i++) { + res[i] = mapping.get(props.get(i)); + } + return res; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderFactory.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderFactory.java index ddb50a1f19..f1e0f7d062 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderFactory.java @@ -4,14 +4,14 @@ * http://www.giscience.uni-hd.de * http://www.heigit.org * - * under one or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information regarding copyright - * ownership. The GIScience licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in compliance + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. The GIScience licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,67 +30,69 @@ import java.util.ServiceLoader; public class StatisticsProviderFactory { - - private static final Logger LOGGER = Logger.getLogger(StatisticsProviderFactory.class.getName()); - - private static final Map providers; + + private static final Logger LOGGER = Logger.getLogger(StatisticsProviderFactory.class.getName()); + + private static final Map providers; private static final Object lockObj; - static { - lockObj = new Object(); - providers = new HashMap<>(); - synchronized(lockObj) { - ServiceLoader loader = ServiceLoader.load(StatisticsProvider.class); - for (StatisticsProvider entry : loader) { - String name = entry.getName().toLowerCase(); - if (!providers.containsKey(name)) { - try { - StatisticsProvider provider = entry.getClass().getConstructor().newInstance(); - StatisticsProviderItem item = new StatisticsProviderItem(provider); - providers.put(name, item); - } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { - LOGGER.error(e); - } - } - } - } - } + static { + lockObj = new Object(); + providers = new HashMap<>(); + synchronized (lockObj) { + ServiceLoader loader = ServiceLoader.load(StatisticsProvider.class); + for (StatisticsProvider entry : loader) { + String name = entry.getName().toLowerCase(); + if (!providers.containsKey(name)) { + try { + StatisticsProvider provider = entry.getClass().getConstructor().newInstance(); + StatisticsProviderItem item = new StatisticsProviderItem(provider); + providers.put(name, item); + } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | + InvocationTargetException e) { + LOGGER.error(e); + } + } + } + } + } + + private StatisticsProviderFactory() { + } - private StatisticsProviderFactory() {} + public static StatisticsProvider getProvider(String name, Map parameters) throws Exception { + if (name == null) + throw new Exception("Data provider is not defined."); + StatisticsProvider provider; + synchronized (lockObj) { + String pname = name.toLowerCase(); + StatisticsProviderItem item = providers.get(pname); + if (item == null) { + Exception ex = new Exception("Unable to find a data provider with name '" + name + "'."); + LOGGER.error(ex); + throw new InternalServerException(IsochronesErrorCodes.UNKNOWN, ex.getMessage()); + } + provider = item.getProvider(); + if (!item.getIsInitialized()) { + try { + provider.init(parameters); + } catch (Exception ex) { + LOGGER.error(ex); + throw new InternalServerException(IsochronesErrorCodes.UNKNOWN, "Unable to initialize a data provider with name '" + name + "'."); + } + item.setIsInitialized(true); + } + } + return provider; + } - public static StatisticsProvider getProvider(String name, Map parameters) throws Exception { - if (name == null) - throw new Exception("Data provider is not defined."); - StatisticsProvider provider ; - synchronized(lockObj) { - String pname = name.toLowerCase(); - StatisticsProviderItem item = providers.get(pname); - if (item == null) { - Exception ex = new Exception("Unable to find a data provider with name '" + name + "'."); - LOGGER.error(ex); - throw new InternalServerException(IsochronesErrorCodes.UNKNOWN, ex.getMessage()); - } - provider = item.getProvider(); - if (!item.getIsInitialized()) { - try { - provider.init(parameters); - } catch(Exception ex) { - LOGGER.error(ex); - throw new InternalServerException(IsochronesErrorCodes.UNKNOWN, "Unable to initialize a data provider with name '" + name + "'."); - } - item.setIsInitialized(true); - } - } - return provider; - } - - public static void releaseProviders() throws Exception { - synchronized(lockObj) { - for(Map.Entry item: providers.entrySet()) { - if (item.getValue().getIsInitialized()) - item.getValue().getProvider().close(); - } - } - } + public static void releaseProviders() throws Exception { + synchronized (lockObj) { + for (Map.Entry item : providers.entrySet()) { + if (item.getValue().getIsInitialized()) + item.getValue().getProvider().close(); + } + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderItem.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderItem.java index ae894c44e6..70d8417c95 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderItem.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/StatisticsProviderItem.java @@ -1,39 +1,35 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.isochrones.statistics; -public class StatisticsProviderItem { - private final StatisticsProvider provider; - private boolean isInitialized = false; +public class StatisticsProviderItem { + private final StatisticsProvider provider; + private boolean isInitialized = false; - public StatisticsProviderItem(StatisticsProvider provider) - { - this.provider = provider; - } + public StatisticsProviderItem(StatisticsProvider provider) { + this.provider = provider; + } - public StatisticsProvider getProvider() - { - return provider; - } + public StatisticsProvider getProvider() { + return provider; + } - public boolean getIsInitialized() - { - return isInitialized; - } + public boolean getIsInitialized() { + return isInitialized; + } - public void setIsInitialized(boolean isInitialized) - { - this.isInitialized = isInitialized; - } + public void setIsInitialized(boolean isInitialized) { + this.isInitialized = isInitialized; + } } \ No newline at end of file diff --git a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/postgresql/PostgresSQLStatisticsProvider.java b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/postgresql/PostgresSQLStatisticsProvider.java index 9fd2ba1106..03012b5994 100644 --- a/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/postgresql/PostgresSQLStatisticsProvider.java +++ b/ors-engine/src/main/java/org/heigit/ors/isochrones/statistics/postgresql/PostgresSQLStatisticsProvider.java @@ -16,10 +16,10 @@ import com.graphhopper.util.Helper; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; +import org.apache.log4j.Logger; import org.heigit.ors.exceptions.InternalServerException; import org.heigit.ors.isochrones.Isochrone; import org.heigit.ors.isochrones.IsochronesErrorCodes; -import org.apache.log4j.Logger; import org.heigit.ors.isochrones.statistics.StatisticsProvider; import org.postgresql.ds.PGSimpleDataSource; @@ -44,6 +44,7 @@ public class PostgresSQLStatisticsProvider implements StatisticsProvider { private String geomColumn = null; private HikariDataSource dataSource; private String postgisVersion = null; + /** * This function initializes the connection to the server according to the settings in the ors-config.json. * The connection is established using a {@link HikariDataSource} object with the configuration data from the ors-config.json. diff --git a/ors-engine/src/main/java/org/heigit/ors/jts/GeometrySmoother.java b/ors-engine/src/main/java/org/heigit/ors/jts/GeometrySmoother.java index 6d4facf668..d0521ea28c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/jts/GeometrySmoother.java +++ b/ors-engine/src/main/java/org/heigit/ors/jts/GeometrySmoother.java @@ -1,7 +1,7 @@ /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org - * + * * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or @@ -13,22 +13,22 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * - * + * + * * This class is composed of code taken from JAI-tools version 1.1.0 * http://code.google.com/p/jai-tools/ - * + * * It combines the JAI-tools classes AbstractSmoother, LineSmoother, * PolygonSmoother and SmootherControl. All are covered by the following * copyright and license: - * + * * Copyright 2010-2011 Michael Bedward - * + * * This file is part of jai-tools. * * jai-tools is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the + * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * jai-tools is distributed in the hope that it will be useful, @@ -36,32 +36,27 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * - * You should have received a copy of the GNU Lesser General Public + * You should have received a copy of the GNU Lesser General Public * License along with jai-tools. If not, see . */ package org.heigit.ors.jts; +import org.locationtech.jts.geom.*; + import java.lang.ref.WeakReference; import java.util.*; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.GeometryFactory; -import org.locationtech.jts.geom.LineString; -import org.locationtech.jts.geom.LinearRing; -import org.locationtech.jts.geom.Polygon; - /** - * Provides package-private helper methods for the {@link JTS} + * Provides package-private helper methods for the {@link JTS} * utility class. - * - * @author Michael Bedward * - * @source $URL$ + * @author Michael Bedward * @version $Id$ + * @source $URL$ * @since 2.8 */ class GeometrySmoother { - + /** * Defines methods to control the smoothing process. * {@code LineSmoother} has a default implementation @@ -86,15 +81,14 @@ private interface SmootherControl { * number includes the segment end-points. * * @param length input segment length - * * @return number of vertices in the smoothed segment - * including the end-points + * including the end-points */ int getNumVertices(double length); } - + /** - * Default smoothing control. Specifies no minimum + * Default smoothing control. Specifies no minimum * vertex distance and a constant number of points * per smoothed segment. */ @@ -102,15 +96,20 @@ private interface SmootherControl { public double getMinLength() { return 0.0; } + public int getNumVertices(double length) { return 10; } }; - - /** The current SmootherControl instance. */ + + /** + * The current SmootherControl instance. + */ private SmootherControl control; - - /** The current {@code GeometryFactory} being used. */ + + /** + * The current {@code GeometryFactory} being used. + */ private final GeometryFactory geomFactory; /** @@ -120,7 +119,7 @@ private static final class InterpPoint { double[] t = new double[4]; double tsum; } - + /** * Cache of previously calculated interpolation parameters */ @@ -129,9 +128,8 @@ private static final class InterpPoint { /** * Creates a new smoother that will use the given {@code GeometryFactory}. - * + * * @param geomFactory factory to use for creating smoothed objects - * * @throws IllegalArgumentException if {@code geomFactory} is {@code null} */ GeometrySmoother(GeometryFactory geomFactory) { @@ -139,42 +137,40 @@ private static final class InterpPoint { throw new IllegalArgumentException("geomFactory must not be null"); } this.geomFactory = geomFactory; - + this.control = defaultControl; } /** - * Creates a new {@code LineString} which is a smoothed version of + * Creates a new {@code LineString} which is a smoothed version of * the input {@code LineString}. - * - * @param ls the input {@code LineString} - * + * + * @param ls the input {@code LineString} * @param alpha a value between 0 and 1 (inclusive) specifying the tightness - * of fit of the smoothed boundary (0 is loose) - * + * of fit of the smoothed boundary (0 is loose) * @return the smoothed {@code LineString} */ LineString smooth(LineString ls, double alpha) { Coordinate[] coords = ls.getCoordinates(); - + Coordinate[][] controlPoints = getLineControlPoints(coords, alpha); - + final int N = coords.length; List smoothCoords = new ArrayList<>(); double dist; for (int i = 0; i < N - 1; i++) { - dist = coords[i].distance(coords[i+1]); + dist = coords[i].distance(coords[i + 1]); if (dist < control.getMinLength()) { // segment too short - just copy input coordinate smoothCoords.add(new Coordinate(coords[i])); - + } else { int smoothN = control.getNumVertices(dist); Coordinate[] segment = cubicBezier( - coords[i], coords[i+1], - controlPoints[i][1], controlPoints[i+1][0], + coords[i], coords[i + 1], + controlPoints[i][1], controlPoints[i + 1][0], smoothN); - + int copyN = i < N - 1 ? segment.length - 1 : segment.length; smoothCoords.addAll(Arrays.asList(Arrays.copyOf(segment, copyN))); } @@ -183,71 +179,68 @@ LineString smooth(LineString ls, double alpha) { return geomFactory.createLineString(smoothCoords.toArray(new Coordinate[0])); } - + /** * Creates a new {@code Polygon} whose exterior shell is a smoothed * version of the input {@code Polygon}. *

* Note: this method presently ignores holes. - * - * @param p the input {@code Polygon} - * + * + * @param p the input {@code Polygon} * @param alpha a value between 0 and 1 (inclusive) specifying the tightness - * of fit of the smoothed boundary (0 is loose) - * + * of fit of the smoothed boundary (0 is loose) * @return the smoothed {@code Polygon} */ public Polygon smooth(Polygon p, double alpha) { Coordinate[] coords = p.getExteriorRing().getCoordinates(); final int N = coords.length - 1; // first coord == last coord - + Coordinate[][] controlPoints = getPolygonControlPoints(coords, N, alpha); - + List smoothCoords = new ArrayList<>(); double dist; for (int i = 0; i < N; i++) { int next = (i + 1) % N; - + dist = coords[i].distance(coords[next]); if (dist < control.getMinLength()) { // segment too short - just copy input coordinate smoothCoords.add(new Coordinate(coords[i])); - + } else { int smoothN = control.getNumVertices(dist); Coordinate[] segment = cubicBezier( coords[i], coords[next], controlPoints[i][1], controlPoints[next][0], smoothN); - + int copyN = i < N - 1 ? segment.length - 1 : segment.length; smoothCoords.addAll(Arrays.asList(Arrays.copyOf(segment, copyN))); } } - + LinearRing shell = geomFactory.createLinearRing(smoothCoords.toArray(new Coordinate[0])); return geomFactory.createPolygon(shell, null); } - + /** * Sets a new {@code Control} object to for smoothing. - * + * * @param control the control to use for smoothing; if {@code null} the - * default control will be set + * default control will be set */ void setControl(SmootherControl control) { this.control = control == null ? defaultControl : control; } - + /** * Calculates a pair of Bezier control points for each vertex in an * array of {@code Coordinates}. - * + * * @param coords input vertices - * @param alpha tightness of fit - * + * @param alpha tightness of fit * @return 2D array of {@code Coordinates} for positions of each pair of - * control points per input vertex + * control points per input vertex */ private Coordinate[][] getLineControlPoints(Coordinate[] coords, double alpha) { if (alpha < 0.0 || alpha > 1.0) { @@ -270,12 +263,12 @@ private Coordinate[][] getLineControlPoints(Coordinate[] coords, double alpha) { v[1] = new Coordinate( 2 * coords[0].x - coords[1].x, 2 * coords[0].y - coords[1].y); v[2] = coords[0]; - + // Dummy coordinate for end of line Coordinate vN = new Coordinate( - 2 * coords[N-1].x - coords[N-2].x, - 2 * coords[N-1].y - coords[N-2].y); - + 2 * coords[N - 1].x - coords[N - 2].x, + 2 * coords[N - 1].y - coords[N - 2].y); + mid[1].x = (v[1].x + v[2].x) / 2.0; mid[1].y = (v[1].y + v[2].y) / 2.0; vdist[1] = v[1].distance(v[2]); @@ -301,27 +294,26 @@ private Coordinate[][] getLineControlPoints(Coordinate[] coords, double alpha) { double ydelta = anchor.y - v[1].y; ctrl[i][0] = new Coordinate( - alpha*(v[1].x - mid[0].x + xdelta) + mid[0].x - xdelta, - alpha*(v[1].y - mid[0].y + ydelta) + mid[0].y - ydelta); + alpha * (v[1].x - mid[0].x + xdelta) + mid[0].x - xdelta, + alpha * (v[1].y - mid[0].y + ydelta) + mid[0].y - ydelta); ctrl[i][1] = new Coordinate( - alpha*(v[1].x - mid[1].x + xdelta) + mid[1].x - xdelta, - alpha*(v[1].y - mid[1].y + ydelta) + mid[1].y - ydelta); + alpha * (v[1].x - mid[1].x + xdelta) + mid[1].x - xdelta, + alpha * (v[1].y - mid[1].y + ydelta) + mid[1].y - ydelta); } return ctrl; } - + /** * Calculates a pair of Bezier control points for each vertex in an * array of {@code Coordinates}. - * + * * @param coords input vertices - * @param n number of coordinates in {@coords} to use - * @param alpha tightness of fit - * + * @param n number of coordinates in {@coords} to use + * @param alpha tightness of fit * @return 2D array of {@code Coordinates} for positions of each pair of - * control points per input vertex + * control points per input vertex */ private Coordinate[][] getPolygonControlPoints(Coordinate[] coords, int n, double alpha) { if (alpha < 0.0 || alpha > 1.0) { @@ -366,49 +358,48 @@ private Coordinate[][] getPolygonControlPoints(Coordinate[] coords, int n, doubl double ydelta = anchor.y - v[1].y; ctrl[i][0] = new Coordinate( - alpha*(v[1].x - mid[0].x + xdelta) + mid[0].x - xdelta, - alpha*(v[1].y - mid[0].y + ydelta) + mid[0].y - ydelta); + alpha * (v[1].x - mid[0].x + xdelta) + mid[0].x - xdelta, + alpha * (v[1].y - mid[0].y + ydelta) + mid[0].y - ydelta); ctrl[i][1] = new Coordinate( - alpha*(v[1].x - mid[1].x + xdelta) + mid[1].x - xdelta, - alpha*(v[1].y - mid[1].y + ydelta) + mid[1].y - ydelta); + alpha * (v[1].x - mid[1].x + xdelta) + mid[1].x - xdelta, + alpha * (v[1].y - mid[1].y + ydelta) + mid[1].y - ydelta); } return ctrl; } - + /** * Calculates vertices along a cubic Bazier curve given start point, end point * and two control points. - * + * * @param start start position - * @param end end position + * @param end end position * @param ctrl1 first control point * @param ctrl2 second control point - * @param nv number of vertices including the start and end points - * + * @param nv number of vertices including the start and end points * @return vertices along the Bezier curve */ private Coordinate[] cubicBezier(final Coordinate start, final Coordinate end, - final Coordinate ctrl1, final Coordinate ctrl2, final int nv) { - + final Coordinate ctrl1, final Coordinate ctrl2, final int nv) { + final Coordinate[] curve = new Coordinate[nv]; - + final Coordinate[] buf = new Coordinate[3]; for (int i = 0; i < buf.length; i++) { buf[i] = new Coordinate(); } - + curve[0] = new Coordinate(start); curve[nv - 1] = new Coordinate(end); InterpPoint[] ip = getInterpPoints(nv); - for (int i = 1; i < nv-1; i++) { + for (int i = 1; i < nv - 1; i++) { Coordinate c = new Coordinate(); - c.x = ip[i].t[0]*start.x + ip[i].t[1]*ctrl1.x + ip[i].t[2]*ctrl2.x + ip[i].t[3]*end.x; + c.x = ip[i].t[0] * start.x + ip[i].t[1] * ctrl1.x + ip[i].t[2] * ctrl2.x + ip[i].t[3] * end.x; c.x /= ip[i].tsum; - c.y = ip[i].t[0]*start.y + ip[i].t[1]*ctrl1.y + ip[i].t[2]*ctrl2.y + ip[i].t[3]*end.y; + c.y = ip[i].t[0] * start.y + ip[i].t[1] * ctrl1.y + ip[i].t[2] * ctrl2.y + ip[i].t[3] * end.y; c.y /= ip[i].tsum; curve[i] = c; @@ -416,39 +407,38 @@ private Coordinate[] cubicBezier(final Coordinate start, final Coordinate end, return curve; } - + /** * Gets the interpolation parameters for a Bezier curve approximated - * by the given number of vertices. - * + * by the given number of vertices. + * * @param npoints number of vertices - * * @return array of {@code InterpPoint} objects holding the parameter values */ private InterpPoint[] getInterpPoints(int npoints) { WeakReference ref = lookup.get(npoints); InterpPoint[] ip = null; if (ref != null) ip = ref.get(); - + if (ip == null) { ip = new InterpPoint[npoints]; - + for (int i = 0; i < npoints; i++) { double t = (double) i / (npoints - 1); double tc = 1.0 - t; ip[i] = new InterpPoint(); - ip[i].t[0] = tc*tc*tc; - ip[i].t[1] = 3.0*tc*tc*t; - ip[i].t[2] = 3.0*tc*t*t; - ip[i].t[3] = t*t*t; + ip[i].t[0] = tc * tc * tc; + ip[i].t[1] = 3.0 * tc * tc * t; + ip[i].t[2] = 3.0 * tc * t * t; + ip[i].t[3] = t * t * t; ip[i].tsum = ip[i].t[0] + ip[i].t[1] + ip[i].t[2] + ip[i].t[3]; } - + lookup.put(npoints, new WeakReference<>(ip)); } - + return ip; } - + } diff --git a/ors-engine/src/main/java/org/heigit/ors/jts/JTS.java b/ors-engine/src/main/java/org/heigit/ors/jts/JTS.java index beb70ce68d..3b0fe2aa4e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/jts/JTS.java +++ b/ors-engine/src/main/java/org/heigit/ors/jts/JTS.java @@ -16,28 +16,16 @@ */ package org.heigit.ors.jts; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.geotools.geometry.GeneralDirectPosition; -import org.geotools.referencing.GeodeticCalculator; import org.geotools.metadata.i18n.ErrorKeys; import org.geotools.metadata.i18n.Errors; +import org.geotools.referencing.GeodeticCalculator; import org.locationtech.jts.algorithm.Orientation; +import org.locationtech.jts.geom.*; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.Envelope; -import org.locationtech.jts.geom.Geometry; -import org.locationtech.jts.geom.GeometryFactory; -import org.locationtech.jts.geom.LineString; -import org.locationtech.jts.geom.LinearRing; -import org.locationtech.jts.geom.MultiPolygon; -import org.locationtech.jts.geom.Polygon; +import java.util.*; /** * JTS Geometry utility methods, bringing Geotools to JTS. @@ -51,15 +39,13 @@ *

  • common coordinate sequence implementations for specific uses
  • * * - * @since 2.2 - * - * - * @source $URL$ - * @version $Id$ * @author Jody Garnett * @author Martin Desruisseaux * @author Simone Giannecchini, GeoSolutions. * @author Michael Bedward + * @version $Id$ + * @source $URL$ + * @since 2.2 */ public final class JTS { /** @@ -79,7 +65,7 @@ public final class JTS { /** * Geodetic calculators already created for a given coordinate reference system. For use in * {@link #orthodromicDistance}. - * + *

    * Note: We would like to use {@link org.geotools.util.CanonicalSet}, but we can't because * {@link GeodeticCalculator} keep a reference to the CRS which is used as the key. */ @@ -94,12 +80,9 @@ private JTS() { /** * Makes sure that an argument is non-null. * - * @param name - * Argument name. - * @param object - * User argument. - * @throws IllegalArgumentException - * if {@code object} is null. + * @param name Argument name. + * @param object User argument. + * @throws IllegalArgumentException if {@code object} is null. */ private static void ensureNonNull(final String name, final Object object) throws IllegalArgumentException { if (object == null) { @@ -108,7 +91,6 @@ private static void ensureNonNull(final String name, final Object object) throws } - /** * Computes the orthodromic distance between two points. This method: *

    @@ -124,19 +106,15 @@ private static void ensureNonNull(final String name, final Object object) throws * to be computed, direct use of {@link GeodeticCalculator} provides better performance than * this convenience method. * - * @param p1 - * First point - * @param p2 - * Second point - * @param crs - * Reference system the two points are in. + * @param p1 First point + * @param p2 Second point + * @param crs Reference system the two points are in. * @return Orthodromic distance between the two points, in meters. - * @throws TransformException - * if the coordinates can't be transformed from the specified CRS to a - * {@linkplain org.opengis.referencing.crs.GeographicCRS geographic CRS}. + * @throws TransformException if the coordinates can't be transformed from the specified CRS to a + * {@linkplain org.opengis.referencing.crs.GeographicCRS geographic CRS}. */ public static synchronized double orthodromicDistance(final Coordinate p1, final Coordinate p2, - final CoordinateReferenceSystem crs) throws TransformException { + final CoordinateReferenceSystem crs) throws TransformException { ensureNonNull("p1", p1); ensureNonNull("p2", p2); ensureNonNull("crs", crs); @@ -172,10 +150,8 @@ public static synchronized double orthodromicDistance(final Coordinate p1, final * be copied. If the array length is greater than 3, then all extra dimensions will be set to * {@link Double#NaN NaN}. * - * @param point - * The source coordinate. - * @param ordinates - * The destination array. + * @param point The source coordinate. + * @param ordinates The destination array. */ public static void copy(final Coordinate point, final double[] ordinates) { ensureNonNull("point", point); @@ -200,9 +176,6 @@ public static void copy(final Coordinate point, final double[] ordinates) { } - - - /** * Creates a smoothed copy of the input Geometry. This is only useful for polygonal and lineal * geometries. Point objects will be returned unchanged. The smoothing algorithm inserts new @@ -217,14 +190,10 @@ public static void copy(final Coordinate point, final double[] ordinates) { * MultiLineString, MultiPolygon) or a GeometryCollection. The returned object will be of the * same type. * - * @param geom - * the input geometry - * @param fit - * tightness of fit from 0 (loose) to 1 (tight) - * + * @param geom the input geometry + * @param fit tightness of fit from 0 (loose) to 1 (tight) * @return a new Geometry object of the same class as {@code geom} - * @throws IllegalArgumentException - * if {@code geom} is {@code null} + * @throws IllegalArgumentException if {@code geom} is {@code null} */ public static Geometry smooth(final Geometry geom, double fit) { return smooth(geom, fit, new GeometryFactory()); @@ -244,16 +213,11 @@ public static Geometry smooth(final Geometry geom, double fit) { * MultiLineString, MultiPolygon) or a GeometryCollection. The returned object will be of the * same type. * - * @param geom - * the input geometry - * @param fit - * tightness of fit from 0 (loose) to 1 (tight) - * @param factory - * the GeometryFactory to use for creating smoothed objects - * + * @param geom the input geometry + * @param fit tightness of fit from 0 (loose) to 1 (tight) + * @param factory the GeometryFactory to use for creating smoothed objects * @return a new Geometry object of the same class as {@code geom} - * @throws IllegalArgumentException - * if either {@code geom} or {@code factory} is {@code null} + * @throws IllegalArgumentException if either {@code geom} or {@code factory} is {@code null} */ public static Geometry smooth(final Geometry geom, double fit, final GeometryFactory factory) { @@ -266,7 +230,7 @@ public static Geometry smooth(final Geometry geom, double fit, final GeometryFac } private static Geometry smooth(final Geometry geom, final double fit, - final GeometryFactory factory, GeometrySmoother smoother) { + final GeometryFactory factory, GeometrySmoother smoother) { return switch (geom.getGeometryType().toUpperCase()) { case "POINT", "MULTIPOINT" -> @@ -285,7 +249,7 @@ private static Geometry smooth(final Geometry geom, final double fit, } private static Geometry smoothLineString(GeometryFactory factory, GeometrySmoother smoother, - Geometry geom, double fit) { + Geometry geom, double fit) { if (geom instanceof LinearRing linearRing) { // Treat as a Polygon @@ -299,7 +263,7 @@ private static Geometry smoothLineString(GeometryFactory factory, GeometrySmooth } private static Geometry smoothMultiLineString(GeometryFactory factory, - GeometrySmoother smoother, Geometry geom, double fit) { + GeometrySmoother smoother, Geometry geom, double fit) { final int N = geom.getNumGeometries(); LineString[] smoothed = new LineString[N]; @@ -313,7 +277,7 @@ private static Geometry smoothMultiLineString(GeometryFactory factory, } private static Geometry smoothMultiPolygon(GeometryFactory factory, GeometrySmoother smoother, - Geometry geom, double fit) { + Geometry geom, double fit) { final int N = geom.getNumGeometries(); Polygon[] smoothed = new Polygon[N]; @@ -326,7 +290,7 @@ private static Geometry smoothMultiPolygon(GeometryFactory factory, GeometrySmoo } private static Geometry smoothGeometryCollection(GeometryFactory factory, - GeometrySmoother smoother, Geometry geom, double fit) { + GeometrySmoother smoother, Geometry geom, double fit) { final int N = geom.getNumGeometries(); Geometry[] smoothed = new Geometry[N]; @@ -471,7 +435,7 @@ public static Geometry removeCollinearVertices(final Geometry g) { * For the moment this implementation only accepts, {@link Polygon}, {@link LineString} and {@link MultiPolygon} It will throw an exception if the * geometry is not one of those types * - * @param geometry the instance of a {@link Geometry} to remove collinear vertices from. + * @param geometry the instance of a {@link Geometry} to remove collinear vertices from. * @param minPoints perform removal of collinear points if num of vertices exceeds minPoints. * @return a new instance of the provided {@link Geometry} without collinear vertices. */ @@ -502,19 +466,18 @@ public static Geometry removeCollinearVertices(final Geometry geometry, int minP + geometry.getClass()); } - public static Polygon toGeometry(final Envelope env) - { - return toGeometry(env, factory); + public static Polygon toGeometry(final Envelope env) { + return toGeometry(env, factory); } public static Polygon toGeometry(final Envelope env, GeometryFactory factory) { ensureNonNull("env", env); - return factory.createPolygon(factory.createLinearRing(new Coordinate[] { - new Coordinate(env.getMinX(), env.getMinY()), - new Coordinate(env.getMaxX(), env.getMinY()), - new Coordinate(env.getMaxX(), env.getMaxY()), - new Coordinate(env.getMinX(), env.getMaxY()), - new Coordinate(env.getMinX(), env.getMinY()) }), null); + return factory.createPolygon(factory.createLinearRing(new Coordinate[]{ + new Coordinate(env.getMinX(), env.getMinY()), + new Coordinate(env.getMaxX(), env.getMinY()), + new Coordinate(env.getMaxX(), env.getMaxY()), + new Coordinate(env.getMinX(), env.getMaxY()), + new Coordinate(env.getMinX(), env.getMinY())}), null); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/localization/Language.java b/ors-engine/src/main/java/org/heigit/ors/localization/Language.java index e721308267..b8f36b9642 100644 --- a/ors-engine/src/main/java/org/heigit/ors/localization/Language.java +++ b/ors-engine/src/main/java/org/heigit/ors/localization/Language.java @@ -1,56 +1,56 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.localization; import java.util.Locale; public class Language { - private final String langTag; - private final String enLangName; - private final String nativeName; - private final Locale locale; - - public Language(String langTag) { - this.langTag = langTag; - this.locale = Locale.forLanguageTag(langTag); - this.enLangName = locale.getDisplayName(); - this.nativeName = locale.getDisplayName(locale); - } - - public String getLangTag() { - return langTag; - } - - public String getEnLangName() { - return enLangName; - } - - public String getNativeName() { - return nativeName; - } - - public Locale getLocale() { - return locale; - } - - @Override - public int hashCode() { - return langTag.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj != null && getClass() == obj.getClass() && langTag.equals(((Language)obj).getLangTag()); - } + private final String langTag; + private final String enLangName; + private final String nativeName; + private final Locale locale; + + public Language(String langTag) { + this.langTag = langTag; + this.locale = Locale.forLanguageTag(langTag); + this.enLangName = locale.getDisplayName(); + this.nativeName = locale.getDisplayName(locale); + } + + public String getLangTag() { + return langTag; + } + + public String getEnLangName() { + return enLangName; + } + + public String getNativeName() { + return nativeName; + } + + public Locale getLocale() { + return locale; + } + + @Override + public int hashCode() { + return langTag.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return obj != null && getClass() == obj.getClass() && langTag.equals(((Language) obj).getLangTag()); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/localization/LanguageResources.java b/ors-engine/src/main/java/org/heigit/ors/localization/LanguageResources.java index eec47c4fb2..c380341bf7 100644 --- a/ors-engine/src/main/java/org/heigit/ors/localization/LanguageResources.java +++ b/ors-engine/src/main/java/org/heigit/ors/localization/LanguageResources.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.localization; @@ -17,41 +17,41 @@ import java.util.Map; public class LanguageResources { - private final Map localStrings; - private final Language lang; - - public LanguageResources(String langTag) { - this.lang = new Language(langTag); - localStrings = new HashMap<>(); - } - - public void addLocalString(String resourceName, String resourceText) { - int hashCode = resourceName.hashCode(); - if (!localStrings.containsKey(hashCode)) { - LocalString localString = new LocalString(lang, resourceText); - localStrings.put(hashCode, localString); - } - } - - public Language getLangCode() { - return lang; - } - - public String getTranslation(String name) throws Exception { - return getTranslation(name, false); - } - - public String getTranslation(String name, boolean throwException) throws Exception { - if (name == null) - return null; - LocalString ls = localStrings.get(name.hashCode()); - if (ls != null) { - return ls.getString(); - } else { - if (throwException) - throw new Exception("Unable to find translation for '" + name + "' in language '" + lang.getLangTag() + "'."); - else - return null; - } - } + private final Map localStrings; + private final Language lang; + + public LanguageResources(String langTag) { + this.lang = new Language(langTag); + localStrings = new HashMap<>(); + } + + public void addLocalString(String resourceName, String resourceText) { + int hashCode = resourceName.hashCode(); + if (!localStrings.containsKey(hashCode)) { + LocalString localString = new LocalString(lang, resourceText); + localStrings.put(hashCode, localString); + } + } + + public Language getLangCode() { + return lang; + } + + public String getTranslation(String name) throws Exception { + return getTranslation(name, false); + } + + public String getTranslation(String name, boolean throwException) throws Exception { + if (name == null) + return null; + LocalString ls = localStrings.get(name.hashCode()); + if (ls != null) { + return ls.getString(); + } else { + if (throwException) + throw new Exception("Unable to find translation for '" + name + "' in language '" + lang.getLangTag() + "'."); + else + return null; + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/localization/LocalString.java b/ors-engine/src/main/java/org/heigit/ors/localization/LocalString.java index 01e8eb71dc..b0335469f8 100644 --- a/ors-engine/src/main/java/org/heigit/ors/localization/LocalString.java +++ b/ors-engine/src/main/java/org/heigit/ors/localization/LocalString.java @@ -1,61 +1,60 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.localization; public class LocalString { - private final Language language; - private final String string; + private final Language language; + private final String string; - public LocalString(Language language, String string) - { - this.language = language; - this.string = string; - } + public LocalString(Language language, String string) { + this.language = language; + this.string = string; + } - public Language getLanguage() { - return language; - } + public Language getLanguage() { + return language; + } - public String getString() { - return string; - } + public String getString() { + return string; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - LocalString that = (LocalString) o; + LocalString that = (LocalString) o; - return language.equals(that.language) && string.equals(that.string); + return language.equals(that.language) && string.equals(that.string); - } + } - @Override - public int hashCode() { - int result = language.hashCode(); - result = 31 * result + string.hashCode(); - return result; - } + @Override + public int hashCode() { + int result = language.hashCode(); + result = 31 * result + string.hashCode(); + return result; + } - @Override - public String toString() { - return """ + @Override + public String toString() { + return """ LocalString{\ language=\ """ + language + - ", string='" + string + '\'' + - '}'; - } + ", string='" + string + '\'' + + '}'; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/localization/LocalizationManager.java b/ors-engine/src/main/java/org/heigit/ors/localization/LocalizationManager.java index 8cf31b769e..4484025320 100644 --- a/ors-engine/src/main/java/org/heigit/ors/localization/LocalizationManager.java +++ b/ors-engine/src/main/java/org/heigit/ors/localization/LocalizationManager.java @@ -20,7 +20,6 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.Map; diff --git a/ors-engine/src/main/java/org/heigit/ors/mapmatching/AbstractMapMatcher.java b/ors-engine/src/main/java/org/heigit/ors/mapmatching/AbstractMapMatcher.java index ccfd5b1690..5734784818 100644 --- a/ors-engine/src/main/java/org/heigit/ors/mapmatching/AbstractMapMatcher.java +++ b/ors-engine/src/main/java/org/heigit/ors/mapmatching/AbstractMapMatcher.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.mapmatching; @@ -17,27 +17,23 @@ import com.graphhopper.routing.util.EdgeFilter; public abstract class AbstractMapMatcher implements MapMatcher { - protected double searchRadius = 50; - protected EdgeFilter edgeFilter; - protected GraphHopper graphHopper; - - public void setSearchRadius(double radius) - { - searchRadius = radius; - } - - public void setEdgeFilter(EdgeFilter edgeFilter) - { - this.edgeFilter = edgeFilter; - } - - public void setGraphHopper(GraphHopper gh) - { - graphHopper = gh; - } - - public RouteSegmentInfo match(double lat0, double lon0, double lat1, double lon1) - { - return null; - } + protected double searchRadius = 50; + protected EdgeFilter edgeFilter; + protected GraphHopper graphHopper; + + public void setSearchRadius(double radius) { + searchRadius = radius; + } + + public void setEdgeFilter(EdgeFilter edgeFilter) { + this.edgeFilter = edgeFilter; + } + + public void setGraphHopper(GraphHopper gh) { + graphHopper = gh; + } + + public RouteSegmentInfo match(double lat0, double lon0, double lat1, double lon1) { + return null; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/mapmatching/GhMapMatcher.java b/ors-engine/src/main/java/org/heigit/ors/mapmatching/GhMapMatcher.java index d5239c3bbc..509bd8551e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/mapmatching/GhMapMatcher.java +++ b/ors-engine/src/main/java/org/heigit/ors/mapmatching/GhMapMatcher.java @@ -20,12 +20,14 @@ */ public class GhMapMatcher extends AbstractMapMatcher { PMap hints; + public GhMapMatcher(GraphHopper graphHopper, String profile) { setGraphHopper(graphHopper); hints = new PMap() - .putObject("profile", profile) - .putObject(Parameters.Landmark.DISABLE, true); + .putObject("profile", profile) + .putObject(Parameters.Landmark.DISABLE, true); } + @Override public RouteSegmentInfo[] match(Coordinate[] locations, boolean bothDirections) { MapMatching mapMatching = new MapMatching(graphHopper, hints); @@ -39,8 +41,8 @@ private static RouteSegmentInfo[] getRouteSegmentInfoFromMatchResult(MatchResult double distance = mr.getMatchLength(); long time = mr.getMatchMillis(); Geometry geometry = null; // TODO: get geometry from match result - // it is unclear, whether the geometry is - // used at all, so we leave it for now. + // it is unclear, whether the geometry is + // used at all, so we leave it for now. RouteSegmentInfo[] rsi = new RouteSegmentInfo[1]; rsi[0] = new RouteSegmentInfo(edgeStates, distance, time, geometry); return rsi; diff --git a/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatcher.java b/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatcher.java index 55e8491b48..5b7ce8aaf2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatcher.java +++ b/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatcher.java @@ -19,14 +19,14 @@ public interface MapMatcher { - - void setSearchRadius(double radius); - void setEdgeFilter(EdgeFilter edgeFilter); + void setSearchRadius(double radius); - void setGraphHopper(GraphHopper gh); + void setEdgeFilter(EdgeFilter edgeFilter); - RouteSegmentInfo[] match(Coordinate[] locations, boolean bothDirections); + void setGraphHopper(GraphHopper gh); - void clear(); + RouteSegmentInfo[] match(Coordinate[] locations, boolean bothDirections); + + void clear(); } diff --git a/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingErrorCodes.java b/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingErrorCodes.java index a906225c9b..52421e464c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingErrorCodes.java +++ b/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingErrorCodes.java @@ -1,24 +1,26 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.mapmatching; public class MapMatchingErrorCodes { - public static final int INVALID_JSON_FORMAT = 800; - public static final int MISSING_PARAMETER = 801; - public static final int INVALID_PARAMETER_FORMAT = 802; - public static final int INVALID_PARAMETER_VALUE = 803; - public static final int PARAMETER_VALUE_EXCEEDS_MAXIMUM = 804; - public static final int UNKNOWN = 899; - private MapMatchingErrorCodes() {} + public static final int INVALID_JSON_FORMAT = 800; + public static final int MISSING_PARAMETER = 801; + public static final int INVALID_PARAMETER_FORMAT = 802; + public static final int INVALID_PARAMETER_VALUE = 803; + public static final int PARAMETER_VALUE_EXCEEDS_MAXIMUM = 804; + public static final int UNKNOWN = 899; + + private MapMatchingErrorCodes() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingRequest.java b/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingRequest.java index e00dd26852..9694c338e9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingRequest.java +++ b/ors-engine/src/main/java/org/heigit/ors/mapmatching/MapMatchingRequest.java @@ -1,38 +1,37 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.mapmatching; import org.heigit.ors.routing.RoutingRequest; public class MapMatchingRequest extends RoutingRequest { - private double accuracy = 50; + private double accuracy = 50; - public MapMatchingRequest() - { - getSearchParameters().setFlexibleMode(true); - } + public MapMatchingRequest() { + getSearchParameters().setFlexibleMode(true); + } - public double getAccuracy() { - return accuracy; - } + public double getAccuracy() { + return accuracy; + } - public void setAccuracy(double accuracy) { - this.accuracy = accuracy; - } + public void setAccuracy(double accuracy) { + this.accuracy = accuracy; + } - @Override - public boolean isValid() { - return !(this.getId() == null && this.getCoordinates() == null); - } + @Override + public boolean isValid() { + return !(this.getId() == null && this.getCoordinates() == null); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/mapmatching/RouteSegmentInfo.java b/ors-engine/src/main/java/org/heigit/ors/mapmatching/RouteSegmentInfo.java index 92e113bcbf..e358fc8ee9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/mapmatching/RouteSegmentInfo.java +++ b/ors-engine/src/main/java/org/heigit/ors/mapmatching/RouteSegmentInfo.java @@ -1,179 +1,177 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.mapmatching; import com.graphhopper.routing.querygraph.EdgeIteratorStateHelper; import com.graphhopper.util.*; +import org.heigit.ors.util.FrechetDistance; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.LineString; -import org.heigit.ors.util.FrechetDistance; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; public class RouteSegmentInfo { - private final List edges; - private final Geometry geometry; - private final long time; - private final double distance; - - public RouteSegmentInfo(List edges, double distance, long time, Geometry geom) { - this.edges = edges; - this.time = time; - this.distance = distance; - this.geometry = geom; - } - - public boolean isEmpty() { - return this.edges == null || this.edges.isEmpty(); - } - - public double getDistance() { - return this.distance; - } - - public long getTime() { - return this.time; - } - - public String getEdgeName(int index) - { - return edges.get(index).getName(); - } - - /** - * @return Returns all Edges. - */ - public List getEdgesStates() { - return edges; - } - - public List getEdges() { - List res = new ArrayList<>(edges.size()); - - for(EdgeIteratorState edge : edges) - res.add(EdgeIteratorStateHelper.getOriginalEdge(edge)); - - return res; - } - - public Geometry getGeometry() { - return this.geometry; - } - - public double getLength() - { - return this.geometry.getLength(); - } - - public double getLength(DistanceCalc dc) { - double res = 0; - - if (this.getGeometry() != null) { - LineString ls = (LineString) this.getGeometry(); - int nPoints = ls.getNumPoints(); - - if (nPoints > 1) { - Coordinate c = ls.getCoordinateN(0); - double x0 = c.x; - double y0 = c.y; - for (int i = 1; i < ls.getNumPoints(); i++) { - c = ls.getCoordinateN(i); - - res += dc.calcDist(y0, x0, c.y, c.x); - x0 = c.x; - y0 = c.y; - } - } - } - - return res; - } - - public String getNearbyStreetName(PointList points, boolean ignoreAdjacency) { - if (edges.isEmpty()) - return null; - - String result = null; - Point2D[] p = getPoints(points); - double minValue = Double.MAX_VALUE; - - for(EdgeIteratorState edge : edges) { - String edgeName = edge.getName(); - if (Helper.isEmpty(edgeName)) - continue; - - PointList pl = edge.fetchWayGeometry(FetchMode.ALL); - if (pl.size() <= 1) - continue; - - if (ignoreAdjacency && arePolylinesAdjacent(points, pl)) - return null; - - Point2D[] q = getPoints(pl); - - FrechetDistance fd = new FrechetDistance(p, q); - - try { - double value = fd.computeFrechetDistance();// * pl.calcDistance(dc)/1000.0 - if (value < minValue && value < 1.5E-6) { - minValue = value; - result = edgeName; - } - } catch(Exception ex) { - // do nothing - } - } - - return result; - } - - private Point2D[] getPoints(PointList points) { - List res = new ArrayList<>(points.size()); - double lon0 = 0; - double lat0 = 0; - double lon1; - double lat1; - for (int i = 0; i < points.size(); i++) { - lon1 = points.getLon(i); - lat1 = points.getLat(i); - if (i > 0 && (lon0 == lon1 || lat0 == lat1)) - continue; - - Point2D p = new Point2D.Double(lon1, lat1); - res.add(p); - lon0 = lon1; - lat0 = lat1; - } - return res.toArray(new Point2D[0]); - } - - private boolean arePolylinesAdjacent(PointList pl1, PointList pl2) { - for (int i = 0; i < pl1.size(); i++) { - double lon0 = pl1.getLon(i); - double lat0 = pl1.getLat(i); - - for (int j = 0; j < pl2.size(); j++) { - double lon1 = pl2.getLon(j); - double lat1 = pl2.getLat(j); - - if (lon0 == lon1 && lat0 == lat1) - return true; - } - } - return false; - } + private final List edges; + private final Geometry geometry; + private final long time; + private final double distance; + + public RouteSegmentInfo(List edges, double distance, long time, Geometry geom) { + this.edges = edges; + this.time = time; + this.distance = distance; + this.geometry = geom; + } + + public boolean isEmpty() { + return this.edges == null || this.edges.isEmpty(); + } + + public double getDistance() { + return this.distance; + } + + public long getTime() { + return this.time; + } + + public String getEdgeName(int index) { + return edges.get(index).getName(); + } + + /** + * @return Returns all Edges. + */ + public List getEdgesStates() { + return edges; + } + + public List getEdges() { + List res = new ArrayList<>(edges.size()); + + for (EdgeIteratorState edge : edges) + res.add(EdgeIteratorStateHelper.getOriginalEdge(edge)); + + return res; + } + + public Geometry getGeometry() { + return this.geometry; + } + + public double getLength() { + return this.geometry.getLength(); + } + + public double getLength(DistanceCalc dc) { + double res = 0; + + if (this.getGeometry() != null) { + LineString ls = (LineString) this.getGeometry(); + int nPoints = ls.getNumPoints(); + + if (nPoints > 1) { + Coordinate c = ls.getCoordinateN(0); + double x0 = c.x; + double y0 = c.y; + for (int i = 1; i < ls.getNumPoints(); i++) { + c = ls.getCoordinateN(i); + + res += dc.calcDist(y0, x0, c.y, c.x); + x0 = c.x; + y0 = c.y; + } + } + } + + return res; + } + + public String getNearbyStreetName(PointList points, boolean ignoreAdjacency) { + if (edges.isEmpty()) + return null; + + String result = null; + Point2D[] p = getPoints(points); + double minValue = Double.MAX_VALUE; + + for (EdgeIteratorState edge : edges) { + String edgeName = edge.getName(); + if (Helper.isEmpty(edgeName)) + continue; + + PointList pl = edge.fetchWayGeometry(FetchMode.ALL); + if (pl.size() <= 1) + continue; + + if (ignoreAdjacency && arePolylinesAdjacent(points, pl)) + return null; + + Point2D[] q = getPoints(pl); + + FrechetDistance fd = new FrechetDistance(p, q); + + try { + double value = fd.computeFrechetDistance();// * pl.calcDistance(dc)/1000.0 + if (value < minValue && value < 1.5E-6) { + minValue = value; + result = edgeName; + } + } catch (Exception ex) { + // do nothing + } + } + + return result; + } + + private Point2D[] getPoints(PointList points) { + List res = new ArrayList<>(points.size()); + double lon0 = 0; + double lat0 = 0; + double lon1; + double lat1; + for (int i = 0; i < points.size(); i++) { + lon1 = points.getLon(i); + lat1 = points.getLat(i); + if (i > 0 && (lon0 == lon1 || lat0 == lat1)) + continue; + + Point2D p = new Point2D.Double(lon1, lat1); + res.add(p); + lon0 = lon1; + lat0 = lat1; + } + return res.toArray(new Point2D[0]); + } + + private boolean arePolylinesAdjacent(PointList pl1, PointList pl2) { + for (int i = 0; i < pl1.size(); i++) { + double lon0 = pl1.getLon(i); + double lat0 = pl1.getLat(i); + + for (int j = 0; j < pl2.size(); j++) { + double lon1 = pl2.getLon(j); + double lat1 = pl2.getLat(j); + + if (lon0 == lon1 && lat0 == lat1) + return true; + } + } + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixErrorCodes.java b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixErrorCodes.java index 962681a683..f843c4bcda 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixErrorCodes.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixErrorCodes.java @@ -33,5 +33,7 @@ public class MatrixErrorCodes { public static final int UNKNOWN_PARAMETER = 6011; public static final int MAX_VISITED_NODES_EXCEEDED = 6020; public static final int UNKNOWN = 6099; - private MatrixErrorCodes() {} + + private MatrixErrorCodes() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixLocations.java b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixLocations.java index 388bc9040e..42a083d2ce 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixLocations.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixLocations.java @@ -1,59 +1,53 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.matrix; public class MatrixLocations { - private final int[] nodeIds; - private final ResolvedLocation[] locations; - private boolean hasValidNodes = false; - - public MatrixLocations(int size) { - nodeIds = new int[size]; - locations = new ResolvedLocation[size]; - } - - public ResolvedLocation[] getLocations() - { - return locations; - } - - public int size() - { - return nodeIds.length; - } - - public int[] getNodeIds() - { - return nodeIds; - } - - public int getNodeId(int index) - { - return nodeIds[index]; - } - - public void setData(int index, int nodeId, ResolvedLocation location) - { - nodeIds[index] = nodeId; - locations[index] = location; - - if (nodeId >= 0 && !hasValidNodes) - hasValidNodes = true; - } - - public boolean hasValidNodes() - { - return hasValidNodes; - } + private final int[] nodeIds; + private final ResolvedLocation[] locations; + private boolean hasValidNodes = false; + + public MatrixLocations(int size) { + nodeIds = new int[size]; + locations = new ResolvedLocation[size]; + } + + public ResolvedLocation[] getLocations() { + return locations; + } + + public int size() { + return nodeIds.length; + } + + public int[] getNodeIds() { + return nodeIds; + } + + public int getNodeId(int index) { + return nodeIds[index]; + } + + public void setData(int index, int nodeId, ResolvedLocation location) { + nodeIds[index] = nodeId; + locations[index] = location; + + if (nodeId >= 0 && !hasValidNodes) + hasValidNodes = true; + } + + public boolean hasValidNodes() { + return hasValidNodes; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixMetricsType.java b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixMetricsType.java index 6302a38410..ad61d1adf6 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixMetricsType.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixMetricsType.java @@ -21,65 +21,66 @@ import java.util.Set; public class MatrixMetricsType { - public static final int UNKNOWN = 0; - public static final int DURATION = 1; - public static final int DISTANCE = 2; - public static final int WEIGHT = 4; - public static final String KEY_DURATION = "duration"; - public static final String KEY_DISTANCE = "distance"; - public static final String KEY_WEIGHT = "weight"; - public static final String KEY_UNKNOWN = "unknown"; + public static final int UNKNOWN = 0; + public static final int DURATION = 1; + public static final int DISTANCE = 2; + public static final int WEIGHT = 4; + public static final String KEY_DURATION = "duration"; + public static final String KEY_DISTANCE = "distance"; + public static final String KEY_WEIGHT = "weight"; + public static final String KEY_UNKNOWN = "unknown"; - private MatrixMetricsType() {} + private MatrixMetricsType() { + } public static boolean isSet(int metrics, int value) { return (metrics & value) == value; } - public static int getFromString(String value) { - if (Helper.isEmpty(value)) - return 0; + public static int getFromString(String value) { + if (Helper.isEmpty(value)) + return 0; - String[] values = value.toLowerCase().split("\\|"); - int res = UNKNOWN; + String[] values = value.toLowerCase().split("\\|"); + int res = UNKNOWN; - for(String str : values) { - switch(str) { - case KEY_DURATION: - res |= DURATION; - break; - case KEY_DISTANCE: - res |= DISTANCE; - break; - case KEY_WEIGHT: - res |= WEIGHT; - break; - default: - return UNKNOWN; - } - } + for (String str : values) { + switch (str) { + case KEY_DURATION: + res |= DURATION; + break; + case KEY_DISTANCE: + res |= DISTANCE; + break; + case KEY_WEIGHT: + res |= WEIGHT; + break; + default: + return UNKNOWN; + } + } - return res; - } + return res; + } - public static String getMetricNameFromInt(int metric) { - String res = switch (metric) { - case MatrixMetricsType.DURATION -> KEY_DURATION; - case MatrixMetricsType.DISTANCE -> KEY_DISTANCE; - case MatrixMetricsType.WEIGHT -> KEY_WEIGHT; - default -> KEY_UNKNOWN; - }; - return res; - } + public static String getMetricNameFromInt(int metric) { + String res = switch (metric) { + case MatrixMetricsType.DURATION -> KEY_DURATION; + case MatrixMetricsType.DISTANCE -> KEY_DISTANCE; + case MatrixMetricsType.WEIGHT -> KEY_WEIGHT; + default -> KEY_UNKNOWN; + }; + return res; + } - public static Set getMetricsNamesFromInt(int metric) { - return switch (metric) { - case MatrixMetricsType.DURATION -> new HashSet<>(List.of(KEY_DURATION)); - case MatrixMetricsType.DISTANCE -> new HashSet<>(List.of(KEY_DISTANCE)); - case MatrixMetricsType.WEIGHT -> new HashSet<>(List.of(KEY_WEIGHT)); - case MatrixMetricsType.DURATION | MatrixMetricsType.DISTANCE -> - new HashSet<>(Arrays.asList(KEY_DURATION, KEY_DISTANCE)); - default -> new HashSet<>(List.of(KEY_UNKNOWN)); - }; - } + public static Set getMetricsNamesFromInt(int metric) { + return switch (metric) { + case MatrixMetricsType.DURATION -> new HashSet<>(List.of(KEY_DURATION)); + case MatrixMetricsType.DISTANCE -> new HashSet<>(List.of(KEY_DISTANCE)); + case MatrixMetricsType.WEIGHT -> new HashSet<>(List.of(KEY_WEIGHT)); + case MatrixMetricsType.DURATION | MatrixMetricsType.DISTANCE -> + new HashSet<>(Arrays.asList(KEY_DURATION, KEY_DISTANCE)); + default -> new HashSet<>(List.of(KEY_UNKNOWN)); + }; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixResult.java b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixResult.java index c39b117bbc..ada055b62f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixResult.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixResult.java @@ -14,52 +14,50 @@ package org.heigit.ors.matrix; public class MatrixResult { - private final float[][] tables; - private ResolvedLocation[] destinations; - private ResolvedLocation[] sources; - private String graphDate; - - public MatrixResult(ResolvedLocation[] sources, ResolvedLocation[] destinations) { - tables = new float[6][]; - this.sources = sources; - this.destinations = destinations; - } - - public void setTable(int metric, float[] values) - { - tables[metric] = values; - } - - public float[] getTable(int metric) - { - return tables[metric]; - } - - public float[][] getTables() { - return tables; - } - - public ResolvedLocation[] getDestinations() - { - return destinations; - } - - public void setDestinations(ResolvedLocation[] locations) - { - destinations = locations; - } - - public ResolvedLocation[] getSources() - { - return sources; - } - - public void setSources(ResolvedLocation[] locations) - { - sources = locations; - } - - public void setGraphDate(String graphDate) {this.graphDate = graphDate; } - - public String getGraphDate() { return graphDate; } + private final float[][] tables; + private ResolvedLocation[] destinations; + private ResolvedLocation[] sources; + private String graphDate; + + public MatrixResult(ResolvedLocation[] sources, ResolvedLocation[] destinations) { + tables = new float[6][]; + this.sources = sources; + this.destinations = destinations; + } + + public void setTable(int metric, float[] values) { + tables[metric] = values; + } + + public float[] getTable(int metric) { + return tables[metric]; + } + + public float[][] getTables() { + return tables; + } + + public ResolvedLocation[] getDestinations() { + return destinations; + } + + public void setDestinations(ResolvedLocation[] locations) { + destinations = locations; + } + + public ResolvedLocation[] getSources() { + return sources; + } + + public void setSources(ResolvedLocation[] locations) { + sources = locations; + } + + public void setGraphDate(String graphDate) { + this.graphDate = graphDate; + } + + public String getGraphDate() { + return graphDate; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixSearchContextBuilder.java b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixSearchContextBuilder.java index 8aae00ac9f..d2fb8996f2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixSearchContextBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/MatrixSearchContextBuilder.java @@ -26,163 +26,163 @@ import com.graphhopper.storage.index.Snap; import com.graphhopper.util.shapes.BBox; import com.graphhopper.util.shapes.GHPoint3D; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.exceptions.PointNotFoundException; +import org.locationtech.jts.geom.Coordinate; import java.util.*; public class MatrixSearchContextBuilder { - private final boolean resolveNames; - private final LocationIndex locIndex; - private final EdgeFilter edgeFilter; - private Map locationCache; - private GraphHopperStorage graphHopperStorage; - private Weighting weighting; - - public MatrixSearchContextBuilder(GraphHopperStorage graphHopperStorage, LocationIndex index, EdgeFilter edgeFilter, boolean resolveNames) { - locIndex = index; - this.edgeFilter = edgeFilter; - this.resolveNames = resolveNames; - this.graphHopperStorage = graphHopperStorage; - } - - public MatrixSearchContext create(Graph graph, RoutingCHGraph chGraph, Weighting weighting, String profileName, Coordinate[] sources, Coordinate[] destinations, double maxSearchRadius) throws Exception { - if (locationCache == null) - locationCache = new HashMap<>(); - else - locationCache.clear(); - - checkBounds(graph.getBounds(), sources, destinations); - this.weighting = weighting; - - List snaps = new ArrayList<>(sources.length + destinations.length); - - resolveLocations(profileName, sources, snaps, maxSearchRadius); - resolveLocations(profileName, destinations, snaps, maxSearchRadius); - - QueryGraph queryGraph = QueryGraph.create(graph, snaps); - RoutingCHGraph routingCHGraph = null; - if (chGraph != null) { - routingCHGraph = new QueryRoutingCHGraph(chGraph, queryGraph); - } - - MatrixLocations mlSources = createLocations(sources); - MatrixLocations mlDestinations = createLocations(destinations); - - return new MatrixSearchContext(queryGraph, routingCHGraph, mlSources, mlDestinations); - } - - private void checkBounds(BBox bounds, Coordinate[] sources, Coordinate[] destinations) throws PointNotFoundException { - String[] messages = new String[2]; - messages[0] = constructPointOutOfBoundsMessage("Source", bounds, sources); - messages[1] = constructPointOutOfBoundsMessage("Destination", bounds, destinations); - - String exceptionMessage = messages[0]; - if (!exceptionMessage.isEmpty() && !messages[1].isEmpty()) - exceptionMessage += ". "; - exceptionMessage += messages[1]; - - if (!exceptionMessage.isEmpty()) - throw new PointNotFoundException(exceptionMessage, MatrixErrorCodes.POINT_NOT_FOUND); - } - - private String constructPointOutOfBoundsMessage(String pointsType, BBox bounds, Coordinate[] coords) { - int[] pointIds = pointIdsOutOfBounds(bounds, coords); - String message = ""; - if (pointIds.length > 0) { - String idString = Arrays.toString(pointIds); - StringBuilder coordsString = new StringBuilder(); - for (int id : pointIds) { - if (coordsString.length() > 0) { - coordsString.append("; "); - } - coordsString.append(coords[id].y).append(",").append(coords[id].x); - } - - message = pointsType + " point(s) " + idString + " out of bounds: " + coordsString; - } - return message; - } - - private int[] pointIdsOutOfBounds(BBox bounds, Coordinate[] coords) { - List ids = new ArrayList<>(); - for (int i = 0; i < coords.length; i++) { - Coordinate c = coords[i]; - if (!bounds.contains(c.y, c.x)) { - ids.add(i); - } - } - int[] idsArray = new int[ids.size()]; - for (int i = 0; i < ids.size(); i++) { - idsArray[i] = ids.get(i); - } - return idsArray; - } - - private void resolveLocations(String profileName, Coordinate[] coords, List queryResults, double maxSearchRadius) { - for (Coordinate p : coords) { - LocationEntry ld = locationCache.get(p); - if (ld == null) { - Snap qr = locIndex.findClosest(p.y, p.x, getSnapFilter(profileName)); - - ld = new LocationEntry(); - ld.snap = qr; - - if (qr.isValid() && qr.getQueryDistance() < maxSearchRadius) { - GHPoint3D pt = qr.getSnappedPoint(); - ld.nodeId = qr.getClosestNode(); - ld.location = new ResolvedLocation(new Coordinate(pt.getLon(), pt.getLat()), resolveNames ? qr.getClosestEdge().getName() : null, qr.getQueryDistance()); - - queryResults.add(qr); - } else { - ld.nodeId = -1; - } - locationCache.put(p, ld); - } - } - } - - protected EdgeFilter getSnapFilter(String profileName) { - EdgeFilter defaultSnapFilter = new DefaultSnapFilter(weighting, this.graphHopperStorage.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileName))); - //TODO when Matrix supports additional parameters such as avoidables in the future, the corresponding filters need to be added here for snapping + private final boolean resolveNames; + private final LocationIndex locIndex; + private final EdgeFilter edgeFilter; + private Map locationCache; + private final GraphHopperStorage graphHopperStorage; + private Weighting weighting; + + public MatrixSearchContextBuilder(GraphHopperStorage graphHopperStorage, LocationIndex index, EdgeFilter edgeFilter, boolean resolveNames) { + locIndex = index; + this.edgeFilter = edgeFilter; + this.resolveNames = resolveNames; + this.graphHopperStorage = graphHopperStorage; + } + + public MatrixSearchContext create(Graph graph, RoutingCHGraph chGraph, Weighting weighting, String profileName, Coordinate[] sources, Coordinate[] destinations, double maxSearchRadius) throws Exception { + if (locationCache == null) + locationCache = new HashMap<>(); + else + locationCache.clear(); + + checkBounds(graph.getBounds(), sources, destinations); + this.weighting = weighting; + + List snaps = new ArrayList<>(sources.length + destinations.length); + + resolveLocations(profileName, sources, snaps, maxSearchRadius); + resolveLocations(profileName, destinations, snaps, maxSearchRadius); + + QueryGraph queryGraph = QueryGraph.create(graph, snaps); + RoutingCHGraph routingCHGraph = null; + if (chGraph != null) { + routingCHGraph = new QueryRoutingCHGraph(chGraph, queryGraph); + } + + MatrixLocations mlSources = createLocations(sources); + MatrixLocations mlDestinations = createLocations(destinations); + + return new MatrixSearchContext(queryGraph, routingCHGraph, mlSources, mlDestinations); + } + + private void checkBounds(BBox bounds, Coordinate[] sources, Coordinate[] destinations) throws PointNotFoundException { + String[] messages = new String[2]; + messages[0] = constructPointOutOfBoundsMessage("Source", bounds, sources); + messages[1] = constructPointOutOfBoundsMessage("Destination", bounds, destinations); + + String exceptionMessage = messages[0]; + if (!exceptionMessage.isEmpty() && !messages[1].isEmpty()) + exceptionMessage += ". "; + exceptionMessage += messages[1]; + + if (!exceptionMessage.isEmpty()) + throw new PointNotFoundException(exceptionMessage, MatrixErrorCodes.POINT_NOT_FOUND); + } + + private String constructPointOutOfBoundsMessage(String pointsType, BBox bounds, Coordinate[] coords) { + int[] pointIds = pointIdsOutOfBounds(bounds, coords); + String message = ""; + if (pointIds.length > 0) { + String idString = Arrays.toString(pointIds); + StringBuilder coordsString = new StringBuilder(); + for (int id : pointIds) { + if (coordsString.length() > 0) { + coordsString.append("; "); + } + coordsString.append(coords[id].y).append(",").append(coords[id].x); + } + + message = pointsType + " point(s) " + idString + " out of bounds: " + coordsString; + } + return message; + } + + private int[] pointIdsOutOfBounds(BBox bounds, Coordinate[] coords) { + List ids = new ArrayList<>(); + for (int i = 0; i < coords.length; i++) { + Coordinate c = coords[i]; + if (!bounds.contains(c.y, c.x)) { + ids.add(i); + } + } + int[] idsArray = new int[ids.size()]; + for (int i = 0; i < ids.size(); i++) { + idsArray[i] = ids.get(i); + } + return idsArray; + } + + private void resolveLocations(String profileName, Coordinate[] coords, List queryResults, double maxSearchRadius) { + for (Coordinate p : coords) { + LocationEntry ld = locationCache.get(p); + if (ld == null) { + Snap qr = locIndex.findClosest(p.y, p.x, getSnapFilter(profileName)); + + ld = new LocationEntry(); + ld.snap = qr; + + if (qr.isValid() && qr.getQueryDistance() < maxSearchRadius) { + GHPoint3D pt = qr.getSnappedPoint(); + ld.nodeId = qr.getClosestNode(); + ld.location = new ResolvedLocation(new Coordinate(pt.getLon(), pt.getLat()), resolveNames ? qr.getClosestEdge().getName() : null, qr.getQueryDistance()); + + queryResults.add(qr); + } else { + ld.nodeId = -1; + } + locationCache.put(p, ld); + } + } + } + + protected EdgeFilter getSnapFilter(String profileName) { + EdgeFilter defaultSnapFilter = new DefaultSnapFilter(weighting, this.graphHopperStorage.getEncodingManager().getBooleanEncodedValue(Subnetwork.key(profileName))); + //TODO when Matrix supports additional parameters such as avoidables in the future, the corresponding filters need to be added here for snapping // if (edgeFilterFactory != null) // return edgeFilterFactory.createEdgeFilter(request.getAdditionalHints(), weighting.getFlagEncoder(), ghStorage, defaultSnapFilter); - return defaultSnapFilter; - } - - - private MatrixLocations createLocations(Coordinate[] coords) throws Exception { - MatrixLocations mlRes = new MatrixLocations(coords.length); - for (int i = 0; i < coords.length; i++) { - Coordinate p = coords[i]; - LocationEntry ld = locationCache.get(p); - if (ld != null) - mlRes.setData(i, ld.nodeId == -1 ? -1 : ld.snap.getClosestNode(), ld.location); - else - throw new Exception("Oops!"); - } - return mlRes; - } - - static class LocationEntry { - private int nodeId; - private ResolvedLocation location; - private Snap snap; - - public int getNodeId() { - return nodeId; - } - - public void setNodeId(int nodeId) { - this.nodeId = nodeId; - } - - public ResolvedLocation getLocation() { - return location; - } - - public void setLocation(ResolvedLocation location) { - this.location = location; - } - } + return defaultSnapFilter; + } + + + private MatrixLocations createLocations(Coordinate[] coords) throws Exception { + MatrixLocations mlRes = new MatrixLocations(coords.length); + for (int i = 0; i < coords.length; i++) { + Coordinate p = coords[i]; + LocationEntry ld = locationCache.get(p); + if (ld != null) + mlRes.setData(i, ld.nodeId == -1 ? -1 : ld.snap.getClosestNode(), ld.location); + else + throw new Exception("Oops!"); + } + return mlRes; + } + + static class LocationEntry { + private int nodeId; + private ResolvedLocation location; + private Snap snap; + + public int getNodeId() { + return nodeId; + } + + public void setNodeId(int nodeId) { + this.nodeId = nodeId; + } + + public ResolvedLocation getLocation() { + return location; + } + + public void setLocation(ResolvedLocation location) { + this.location = location; + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/MultiTreeMetricsExtractor.java b/ors-engine/src/main/java/org/heigit/ors/matrix/MultiTreeMetricsExtractor.java index 65a6f8d502..fe5fb1ce07 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/MultiTreeMetricsExtractor.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/MultiTreeMetricsExtractor.java @@ -14,8 +14,6 @@ package org.heigit.ors.matrix; import com.graphhopper.coll.GHLongObjectHashMap; -import com.graphhopper.routing.querygraph.QueryGraph; -import com.graphhopper.routing.querygraph.QueryRoutingCHGraph; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.routing.weighting.FastestWeighting; import com.graphhopper.routing.weighting.Weighting; @@ -37,7 +35,7 @@ public class MultiTreeMetricsExtractor { private final DistanceUnit distUnits; private final GHLongObjectHashMap edgeMetrics; private final long maxEdgeId; - private RoutingCHGraph chGraph; + private final RoutingCHGraph chGraph; private double edgeDistance; private double edgeWeight; private double edgeTime; diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/PathMetricsExtractor.java b/ors-engine/src/main/java/org/heigit/ors/matrix/PathMetricsExtractor.java index c2b34dfb51..2e77077ed6 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/PathMetricsExtractor.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/PathMetricsExtractor.java @@ -24,97 +24,98 @@ import org.heigit.ors.util.DistanceUnitUtil; public class PathMetricsExtractor { - private final int metrics; - private final Graph graph; - private final Weighting weighting; - private final DistanceUnit distUnits; - private final GHLongObjectHashMap edgeMetrics = new GHLongObjectHashMap<>(); - private static class MetricsItem { - protected double distance; - protected double time; - protected double weight; - } - - public PathMetricsExtractor(int metrics, Graph graph, Weighting weighting, DistanceUnit units) { - this.metrics = metrics; - this.graph = graph; - this.weighting = weighting; - this.distUnits = units; - } - - public void setEmptyValues(int sourceIndex, MatrixLocations dstData, float[] times, float[] distances, float[] weights) { - int offset = sourceIndex * dstData.size(); - for (int i = 0; i < dstData.getNodeIds().length; i++) { - if (times != null) - times[offset+i] = -1; - if (distances != null) - distances[offset+i] = -1; - if (weights != null) - weights[offset+i] = -1; - } - } - - public void calcValues(int sourceIndex, SPTEntry[] targets, MatrixLocations dstData, float[] times, float[] distances, float[] weights) throws IllegalStateException, StatusCodeException { - if (targets == null) - throw new IllegalStateException("Target destinations not set"); - - int index = sourceIndex * dstData.size(); - double pathTime; - double pathDistance; - double pathWeight; - boolean calcTime = MatrixMetricsType.isSet(metrics, MatrixMetricsType.DURATION); - boolean calcDistance = MatrixMetricsType.isSet(metrics, MatrixMetricsType.DISTANCE); - boolean calcWeight = MatrixMetricsType.isSet(metrics, MatrixMetricsType.WEIGHT); - - for (int i = 0; i < targets.length; ++i) { - SPTEntry goalEdge = targets[i]; - - if (goalEdge != null) { - pathTime = 0.0; - pathDistance = 0.0; - pathWeight = 0.0; - - while (EdgeIterator.Edge.isValid(goalEdge.edge)) { - EdgeIteratorState iter = graph.getEdgeIteratorState(goalEdge.edge, goalEdge.adjNode); - long edgeKey = iter.getEdgeKey(); - MetricsItem edgeMetricsItem = edgeMetrics.get(edgeKey); - - if (edgeMetricsItem == null) { - edgeMetricsItem = new MetricsItem(); - if (calcDistance) - edgeMetricsItem.distance = (distUnits == DistanceUnit.METERS) ? iter.getDistance() : DistanceUnitUtil.convert(iter.getDistance(), DistanceUnit.METERS, distUnits); - if (calcTime) - edgeMetricsItem.time = weighting.calcEdgeMillis(iter, false, EdgeIterator.NO_EDGE) / 1000.0; - if (calcWeight) - edgeMetricsItem.weight = weighting.calcEdgeWeight(iter, false, EdgeIterator.NO_EDGE); - edgeMetrics.put(edgeKey, edgeMetricsItem); - } - - pathDistance += edgeMetricsItem.distance; - pathTime += edgeMetricsItem.time; - pathWeight += edgeMetricsItem.weight; - - goalEdge = goalEdge.parent; - - if (goalEdge == null) - break; - } - } else { - pathTime = -1; - pathDistance= -1; - pathWeight = -1; - } - - if (calcTime) - times[index] = (float)pathTime; - - if (calcDistance) - distances[index] = (float)pathDistance; - - if (calcWeight) - weights[index] = (float)pathWeight; - - index++; - } - } + private final int metrics; + private final Graph graph; + private final Weighting weighting; + private final DistanceUnit distUnits; + private final GHLongObjectHashMap edgeMetrics = new GHLongObjectHashMap<>(); + + private static class MetricsItem { + protected double distance; + protected double time; + protected double weight; + } + + public PathMetricsExtractor(int metrics, Graph graph, Weighting weighting, DistanceUnit units) { + this.metrics = metrics; + this.graph = graph; + this.weighting = weighting; + this.distUnits = units; + } + + public void setEmptyValues(int sourceIndex, MatrixLocations dstData, float[] times, float[] distances, float[] weights) { + int offset = sourceIndex * dstData.size(); + for (int i = 0; i < dstData.getNodeIds().length; i++) { + if (times != null) + times[offset + i] = -1; + if (distances != null) + distances[offset + i] = -1; + if (weights != null) + weights[offset + i] = -1; + } + } + + public void calcValues(int sourceIndex, SPTEntry[] targets, MatrixLocations dstData, float[] times, float[] distances, float[] weights) throws IllegalStateException, StatusCodeException { + if (targets == null) + throw new IllegalStateException("Target destinations not set"); + + int index = sourceIndex * dstData.size(); + double pathTime; + double pathDistance; + double pathWeight; + boolean calcTime = MatrixMetricsType.isSet(metrics, MatrixMetricsType.DURATION); + boolean calcDistance = MatrixMetricsType.isSet(metrics, MatrixMetricsType.DISTANCE); + boolean calcWeight = MatrixMetricsType.isSet(metrics, MatrixMetricsType.WEIGHT); + + for (int i = 0; i < targets.length; ++i) { + SPTEntry goalEdge = targets[i]; + + if (goalEdge != null) { + pathTime = 0.0; + pathDistance = 0.0; + pathWeight = 0.0; + + while (EdgeIterator.Edge.isValid(goalEdge.edge)) { + EdgeIteratorState iter = graph.getEdgeIteratorState(goalEdge.edge, goalEdge.adjNode); + long edgeKey = iter.getEdgeKey(); + MetricsItem edgeMetricsItem = edgeMetrics.get(edgeKey); + + if (edgeMetricsItem == null) { + edgeMetricsItem = new MetricsItem(); + if (calcDistance) + edgeMetricsItem.distance = (distUnits == DistanceUnit.METERS) ? iter.getDistance() : DistanceUnitUtil.convert(iter.getDistance(), DistanceUnit.METERS, distUnits); + if (calcTime) + edgeMetricsItem.time = weighting.calcEdgeMillis(iter, false, EdgeIterator.NO_EDGE) / 1000.0; + if (calcWeight) + edgeMetricsItem.weight = weighting.calcEdgeWeight(iter, false, EdgeIterator.NO_EDGE); + edgeMetrics.put(edgeKey, edgeMetricsItem); + } + + pathDistance += edgeMetricsItem.distance; + pathTime += edgeMetricsItem.time; + pathWeight += edgeMetricsItem.weight; + + goalEdge = goalEdge.parent; + + if (goalEdge == null) + break; + } + } else { + pathTime = -1; + pathDistance = -1; + pathWeight = -1; + } + + if (calcTime) + times[index] = (float) pathTime; + + if (calcDistance) + distances[index] = (float) pathDistance; + + if (calcWeight) + weights[index] = (float) pathWeight; + + index++; + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/ResolvedLocation.java b/ors-engine/src/main/java/org/heigit/ors/matrix/ResolvedLocation.java index 4fc48f0326..1358fa4b10 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/ResolvedLocation.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/ResolvedLocation.java @@ -1,31 +1,30 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.matrix; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.common.NamedLocation; +import org.locationtech.jts.geom.Coordinate; public class ResolvedLocation extends NamedLocation { - private final double snappedDistance; - - public ResolvedLocation(Coordinate coord, String name, double snappedDistance) { - super(coord, name); - this.snappedDistance = snappedDistance; - } - - public double getSnappedDistance() - { - return snappedDistance; - } + private final double snappedDistance; + + public ResolvedLocation(Coordinate coord, String name, double snappedDistance) { + super(coord, name); + this.snappedDistance = snappedDistance; + } + + public double getSnappedDistance() { + return snappedDistance; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/TargetGraphBuilder.java b/ors-engine/src/main/java/org/heigit/ors/matrix/TargetGraphBuilder.java index cae61d201d..ca242e8aa4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/TargetGraphBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/TargetGraphBuilder.java @@ -36,7 +36,7 @@ public TargetGraphResults prepareTargetGraph(int[] targets, RoutingCHGraph chGra this.chGraph = chGraph; //Get node count from base graph, as chGraph should be a query graph with additional virtual nodes that are counted in chGraph.getNodes() //TODO Refactoring : implement isVirtualNode in QueryRoutingCHGraph from underlying query graph for better style - if(chGraph instanceof QueryRoutingCHGraph) + if (chGraph instanceof QueryRoutingCHGraph) this.nodeCount = chGraph.getBaseGraph().getBaseGraph().getNodes(); else this.nodeCount = chGraph.getNodes(); diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/AbstractMatrixAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/AbstractMatrixAlgorithm.java index c5dc05278b..270ca2e3b0 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/AbstractMatrixAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/AbstractMatrixAlgorithm.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.matrix.algorithms; diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/dijkstra/DijkstraManyToMany.java b/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/dijkstra/DijkstraManyToMany.java index c270626f7a..237c6ef323 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/dijkstra/DijkstraManyToMany.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/dijkstra/DijkstraManyToMany.java @@ -54,15 +54,15 @@ public class DijkstraManyToMany extends AbstractManyToManyRoutingAlgorithm { IntObjectMap> bestWeightMapCore; IntObjectMap targetMap; IntHashSet targetSet; - private RoutingCHGraph chGraph; + private final RoutingCHGraph chGraph; private IntHashSet coreExitPoints; private RoutingCHEdgeExplorer targetGraphExplorer; private MultiSourceStoppingCriterion stoppingCriterion; private int visitedNodes; private int treeEntrySize; private boolean hasTurnWeighting = false; - private int coreNodeLevel; - private int nodeCount; + private final int coreNodeLevel; + private final int nodeCount; private boolean swap = false; public DijkstraManyToMany(RoutingCHGraph chGraph, Weighting weighting, TraversalMode tMode) { diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/rphast/RPHASTMatrixAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/rphast/RPHASTMatrixAlgorithm.java index bd3473b0df..a3d8c16d2f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/rphast/RPHASTMatrixAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/algorithms/rphast/RPHASTMatrixAlgorithm.java @@ -66,7 +66,7 @@ public MatrixResult compute(MatrixLocations srcData, MatrixLocations dstData, in int[] srcIds = getValidNodeIds(srcData.getNodeIds()); int[] destIds = getValidNodeIds(dstData.getNodeIds()); - if(graphHopper != null) + if (graphHopper != null) mtxResult.setGraphDate(graphHopper.getGraphHopperStorage().getProperties().get("datareader.import.date")); algorithm.prepare(srcIds, destIds); diff --git a/ors-engine/src/main/java/org/heigit/ors/matrix/util/GraphUtils.java b/ors-engine/src/main/java/org/heigit/ors/matrix/util/GraphUtils.java index a266bcdc59..22bcb22bef 100644 --- a/ors-engine/src/main/java/org/heigit/ors/matrix/util/GraphUtils.java +++ b/ors-engine/src/main/java/org/heigit/ors/matrix/util/GraphUtils.java @@ -10,7 +10,7 @@ public static boolean isCoreNode(RoutingCHGraph chGraph, int nodeId, int nodeCou return chGraph.getLevel(nodeId) >= coreNodeLevel; } - private static boolean isVirtualNode(int node, int nodeCount){ + private static boolean isVirtualNode(int node, int nodeCount) { return node >= nodeCount; } } diff --git a/ors-engine/src/main/java/org/heigit/ors/plugins/Plugin.java b/ors-engine/src/main/java/org/heigit/ors/plugins/Plugin.java index e65632bdc2..44d1d1f021 100644 --- a/ors-engine/src/main/java/org/heigit/ors/plugins/Plugin.java +++ b/ors-engine/src/main/java/org/heigit/ors/plugins/Plugin.java @@ -1,22 +1,22 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.plugins; import java.util.Map; public interface Plugin { - String getName(); - - void setParameters(Map parameters); + String getName(); + + void setParameters(Map parameters); } diff --git a/ors-engine/src/main/java/org/heigit/ors/plugins/PluginManager.java b/ors-engine/src/main/java/org/heigit/ors/plugins/PluginManager.java index c7cb1b5371..a6294eca7a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/plugins/PluginManager.java +++ b/ors-engine/src/main/java/org/heigit/ors/plugins/PluginManager.java @@ -1,92 +1,85 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.plugins; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.ServiceConfigurationError; -import java.util.ServiceLoader; - import org.apache.log4j.Logger; +import java.lang.reflect.InvocationTargetException; +import java.util.*; + public class PluginManager { - private static final Logger LOGGER = Logger.getLogger(PluginManager.class.getName()); + private static final Logger LOGGER = Logger.getLogger(PluginManager.class.getName()); - private final ServiceLoader loader; - private final Object lockObj; - private static final Map pluginMgrCache = new HashMap<>(); + private final ServiceLoader loader; + private final Object lockObj; + private static final Map pluginMgrCache = new HashMap<>(); - @SuppressWarnings("unchecked") - public static synchronized PluginManager getPluginManager(Class cls) throws Exception { - PluginManager pmgr = null; - pmgr = (PluginManager) pluginMgrCache.get(cls.getName()); - if (pmgr == null) - { - pmgr = new PluginManager<>(cls); - pluginMgrCache.put(cls.getName(), pmgr); - } - return pmgr; - } + @SuppressWarnings("unchecked") + public static synchronized PluginManager getPluginManager(Class cls) throws Exception { + PluginManager pmgr = null; + pmgr = (PluginManager) pluginMgrCache.get(cls.getName()); + if (pmgr == null) { + pmgr = new PluginManager<>(cls); + pluginMgrCache.put(cls.getName(), pmgr); + } + return pmgr; + } - @SuppressWarnings("unchecked") - public PluginManager(Class cls) throws Exception { - if (cls.equals(getClass())) - throw new Exception("Wrong class parameter"); - loader = (ServiceLoader)ServiceLoader.load(cls); - lockObj = new Object(); - } + @SuppressWarnings("unchecked") + public PluginManager(Class cls) throws Exception { + if (cls.equals(getClass())) + throw new Exception("Wrong class parameter"); + loader = (ServiceLoader) ServiceLoader.load(cls); + lockObj = new Object(); + } - public List createInstances(Map> parameters) { - List result = new ArrayList<>(parameters.size()); - if (!parameters.isEmpty()) { - for(Map.Entry> storageEntry : parameters.entrySet()) { - T instance = createInstance(storageEntry.getKey(), storageEntry.getValue()); + public List createInstances(Map> parameters) { + List result = new ArrayList<>(parameters.size()); + if (!parameters.isEmpty()) { + for (Map.Entry> storageEntry : parameters.entrySet()) { + T instance = createInstance(storageEntry.getKey(), storageEntry.getValue()); - if (instance != null) { - result.add(instance); - } - else - LOGGER.warn("'%s' was not found.".formatted(storageEntry.getKey())); - } - } - return result; - } + if (instance != null) { + result.add(instance); + } else + LOGGER.warn("'%s' was not found.".formatted(storageEntry.getKey())); + } + } + return result; + } - @SuppressWarnings("unchecked") - public T createInstance(String name, Map params) { - T instance = null; - try { - // ServiceLoader is not threadsafe - synchronized(lockObj) { - Iterator entries = loader.iterator(); - while (entries.hasNext()) { - T entry = entries.next(); - if (entry.getName().equalsIgnoreCase(name)) { - instance = ((Class)entry.getClass()).getDeclaredConstructor().newInstance(); - instance.setParameters(params); - break; - } - } - } - } catch (ServiceConfigurationError | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException se) { - instance = null; - LOGGER.error(se); - } - return instance; - } + @SuppressWarnings("unchecked") + public T createInstance(String name, Map params) { + T instance = null; + try { + // ServiceLoader is not threadsafe + synchronized (lockObj) { + Iterator entries = loader.iterator(); + while (entries.hasNext()) { + T entry = entries.next(); + if (entry.getName().equalsIgnoreCase(name)) { + instance = ((Class) entry.getClass()).getDeclaredConstructor().newInstance(); + instance.setParameters(params); + break; + } + } + } + } catch (ServiceConfigurationError | InstantiationException | IllegalAccessException | NoSuchMethodException | + InvocationTargetException se) { + instance = null; + LOGGER.error(se); + } + return instance; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/AvoidFeatureFlags.java b/ors-engine/src/main/java/org/heigit/ors/routing/AvoidFeatureFlags.java index f23e80ec24..9b962b3a1d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/AvoidFeatureFlags.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/AvoidFeatureFlags.java @@ -14,43 +14,44 @@ package org.heigit.ors.routing; public class AvoidFeatureFlags { - public static final int HIGHWAYS = 1; - public static final int TOLLWAYS = 2; - public static final int STEPS = 4; - public static final int FERRIES = 8; - public static final int FORDS = 16; - - private static final int DRIVING_FEATURES = HIGHWAYS | TOLLWAYS | FERRIES | FORDS; - private static final int CYCLING_FEATURES = STEPS | FERRIES | FORDS; - private static final int WALKING_FEATURES = STEPS | FERRIES | FORDS; - private static final int WHEELCHAIR_FEATURES = WALKING_FEATURES; - - private AvoidFeatureFlags() {} - - public static int getFromString(String value) { - return switch (value.toLowerCase()) { - case "highways" -> HIGHWAYS; - case "tollways" -> TOLLWAYS; - case "ferries" -> FERRIES; - case "steps" -> STEPS; - case "fords" -> FORDS; - default -> 0; - }; - } - - public static int getProfileFlags(int profileCategory) { - return switch (profileCategory) { - case RoutingProfileCategory.DRIVING -> DRIVING_FEATURES; - case RoutingProfileCategory.CYCLING -> CYCLING_FEATURES; - case RoutingProfileCategory.WALKING -> WALKING_FEATURES; - case RoutingProfileCategory.WHEELCHAIR -> WHEELCHAIR_FEATURES; - default -> RoutingProfileCategory.UNKNOWN; - }; - } - - public static boolean isValid(int profileType, int value) { - int profileCategory = RoutingProfileCategory.getFromRouteProfile(profileType); - int nonProfileFlags = ~ getProfileFlags(profileCategory); - return (nonProfileFlags & value) == 0; - } + public static final int HIGHWAYS = 1; + public static final int TOLLWAYS = 2; + public static final int STEPS = 4; + public static final int FERRIES = 8; + public static final int FORDS = 16; + + private static final int DRIVING_FEATURES = HIGHWAYS | TOLLWAYS | FERRIES | FORDS; + private static final int CYCLING_FEATURES = STEPS | FERRIES | FORDS; + private static final int WALKING_FEATURES = STEPS | FERRIES | FORDS; + private static final int WHEELCHAIR_FEATURES = WALKING_FEATURES; + + private AvoidFeatureFlags() { + } + + public static int getFromString(String value) { + return switch (value.toLowerCase()) { + case "highways" -> HIGHWAYS; + case "tollways" -> TOLLWAYS; + case "ferries" -> FERRIES; + case "steps" -> STEPS; + case "fords" -> FORDS; + default -> 0; + }; + } + + public static int getProfileFlags(int profileCategory) { + return switch (profileCategory) { + case RoutingProfileCategory.DRIVING -> DRIVING_FEATURES; + case RoutingProfileCategory.CYCLING -> CYCLING_FEATURES; + case RoutingProfileCategory.WALKING -> WALKING_FEATURES; + case RoutingProfileCategory.WHEELCHAIR -> WHEELCHAIR_FEATURES; + default -> RoutingProfileCategory.UNKNOWN; + }; + } + + public static boolean isValid(int profileType, int value) { + int profileCategory = RoutingProfileCategory.getFromRouteProfile(profileType); + int nonProfileFlags = ~getProfileFlags(profileCategory); + return (nonProfileFlags & value) == 0; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/ExtraSummaryItem.java b/ors-engine/src/main/java/org/heigit/ors/routing/ExtraSummaryItem.java index 90146e9c49..e9bcf19a6a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/ExtraSummaryItem.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/ExtraSummaryItem.java @@ -1,42 +1,38 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; public class ExtraSummaryItem { - private final double value; - private final double distance; - private final double amount; - - public ExtraSummaryItem(double value, double distance, double amount) - { - this.value = value; - this.distance = distance; - this.amount = amount; - } - - public double getValue() - { - return value; - } - - public double getDistance() - { - return distance; - } - - public double getAmount() - { - return amount; - } + private final double value; + private final double distance; + private final double amount; + + public ExtraSummaryItem(double value, double distance, double amount) { + this.value = value; + this.distance = distance; + this.amount = amount; + } + + public double getValue() { + return value; + } + + public double getDistance() { + return distance; + } + + public double getAmount() { + return amount; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeighting.java index 8bd0c3fef4..6890327ee9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeighting.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; @@ -20,40 +20,37 @@ import org.heigit.ors.util.StringUtility; public class ProfileWeighting { - private final String name; - private PMap params; - - public ProfileWeighting(String name) throws InternalServerException { - if (Helper.isEmpty(name)) - throw new InternalServerException(RoutingErrorCodes.EMPTY_ELEMENT, "'name' can't be null or empty"); - this.name = name; - } - - public String getName() - { - return name; - } - - public void addParameter(String name, Object value) { - getParameters().putObject(name, value); - } - - public PMap getParameters() - { - if (params == null) - params = new PMap(); - return params; - } - - public static String encodeName(String name) - { - return "weighting_#" + name + "#"; - } - - public static String decodeName(String value) { - if (value.startsWith("weighting_#")) - return StringUtility.substring(value, '#'); - else - return null; - } + private final String name; + private PMap params; + + public ProfileWeighting(String name) throws InternalServerException { + if (Helper.isEmpty(name)) + throw new InternalServerException(RoutingErrorCodes.EMPTY_ELEMENT, "'name' can't be null or empty"); + this.name = name; + } + + public String getName() { + return name; + } + + public void addParameter(String name, Object value) { + getParameters().putObject(name, value); + } + + public PMap getParameters() { + if (params == null) + params = new PMap(); + return params; + } + + public static String encodeName(String name) { + return "weighting_#" + name + "#"; + } + + public static String decodeName(String value) { + if (value.startsWith("weighting_#")) + return StringUtility.substring(value, '#'); + else + return null; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeightingCollection.java b/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeightingCollection.java index b888a46675..c42849e00e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeightingCollection.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/ProfileWeightingCollection.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; @@ -18,26 +18,23 @@ import java.util.List; public class ProfileWeightingCollection { - protected List weightings; - - public ProfileWeightingCollection() - { - weightings = new ArrayList<>(); - } - - public void add(ProfileWeighting weighting) { - if (weightings == null) - weightings = new ArrayList<>(); - weightings.add(weighting); - } - - public Iterator getIterator() - { - return weightings.iterator(); - } - - public int size() - { - return weightings.size(); - } + protected List weightings; + + public ProfileWeightingCollection() { + weightings = new ArrayList<>(); + } + + public void add(ProfileWeighting weighting) { + if (weightings == null) + weightings = new ArrayList<>(); + weightings.add(weighting); + } + + public Iterator getIterator() { + return weightings.iterator(); + } + + public int size() { + return weightings.size(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfo.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfo.java index 6a5c6946d2..fe7deae704 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfo.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfo.java @@ -1,24 +1,18 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.graphhopper.storage.GraphExtension; import org.heigit.ors.common.DistanceUnit; import org.heigit.ors.exceptions.StatusCodeException; @@ -26,117 +20,112 @@ import org.heigit.ors.util.DistanceUnitUtil; import org.heigit.ors.util.FormatUtility; +import java.util.*; + public class RouteExtraInfo { private final String name; private final List segments; private double factor = 1.0; private boolean usedForWarnings = false; private WarningGraphExtension warningGraphExtension; - - public RouteExtraInfo(String name) - { - this(name, null); + + public RouteExtraInfo(String name) { + this(name, null); + } + + /** + * Constructor that can mark the RouteExtraInfo as being able to generate warnings or not + * + * @param name name of the extra info + * @param extension The GraphExtension that is used to generate the extra info. A check is made against this to + * see if it is of type {@Link org.heigit.ors.routing.graphhopper.extensions.storages.WarningGraphExtension}. + */ + public RouteExtraInfo(String name, GraphExtension extension) { + this.name = name; + segments = new ArrayList<>(); + if (extension instanceof WarningGraphExtension graphExtension) { + warningGraphExtension = graphExtension; + usedForWarnings = true; + } } - /** - * Constructor that can mark the RouteExtraInfo as being able to generate warnings or not - * - * @param name name of the extra info - * @param extension The GraphExtension that is used to generate the extra info. A check is made against this to - * see if it is of type {@Link org.heigit.ors.routing.graphhopper.extensions.storages.WarningGraphExtension}. - * - */ - public RouteExtraInfo(String name, GraphExtension extension) { - this.name = name; - segments = new ArrayList<>(); - if(extension instanceof WarningGraphExtension graphExtension) { - warningGraphExtension = graphExtension; - usedForWarnings = true; - } - } - - public String getName() - { - return name; + public String getName() { + return name; } - - public boolean isEmpty() - { - return segments.isEmpty(); + + public boolean isEmpty() { + return segments.isEmpty(); } - - public void add(RouteSegmentItem item) - { - segments.add(item); - } - - public List getSegments() - { - return segments; - } - - public List getSummary(DistanceUnit units, double routeDistance, boolean sort) throws StatusCodeException { - List summary = new ArrayList<>(); - - if (!segments.isEmpty()) { - Comparator comp = (ExtraSummaryItem a, ExtraSummaryItem b) -> Double.compare(b.getAmount(), a.getAmount()); - - double totalDist = 0.0; - - Map stats = new HashMap<>(); - - for (RouteSegmentItem seg : segments) { - Double scaledValue = seg.getValue()/ factor; - Double value = stats.get(scaledValue); - - if (value == null) - stats.put(scaledValue, seg.getDistance()); - else { - value += seg.getDistance(); - stats.put(scaledValue, value); - } - - totalDist += seg.getDistance(); - } - - if (totalDist != 0.0) { - int unitDecimals = FormatUtility.getUnitDecimals(units); - // Some extras such as steepness might provide inconsistent distance values caused by multiple rounding. - // Therefore, we try to scale distance so that their sum equals to the whole distance of a route - double distScale = totalDist/routeDistance; - - for (Map.Entry entry : stats.entrySet()) - { - double scaledValue = entry.getValue()/distScale; - ExtraSummaryItem esi = new ExtraSummaryItem(entry.getKey(), - FormatUtility.roundToDecimals(DistanceUnitUtil.convert(scaledValue, DistanceUnit.METERS, units), unitDecimals), - FormatUtility.roundToDecimals(scaledValue * 100.0 / routeDistance, 2) - ); - - summary.add(esi); - } - - if (sort) - summary.sort(comp); - } - } - - return summary; - } - - public double getFactor() { - return factor; - } - - public void setFactor(double factor) { - this.factor = factor; - } - - public boolean isUsedForWarnings() { - return usedForWarnings; + + public void add(RouteSegmentItem item) { + segments.add(item); + } + + public List getSegments() { + return segments; + } + + public List getSummary(DistanceUnit units, double routeDistance, boolean sort) throws StatusCodeException { + List summary = new ArrayList<>(); + + if (!segments.isEmpty()) { + Comparator comp = (ExtraSummaryItem a, ExtraSummaryItem b) -> Double.compare(b.getAmount(), a.getAmount()); + + double totalDist = 0.0; + + Map stats = new HashMap<>(); + + for (RouteSegmentItem seg : segments) { + Double scaledValue = seg.getValue() / factor; + Double value = stats.get(scaledValue); + + if (value == null) + stats.put(scaledValue, seg.getDistance()); + else { + value += seg.getDistance(); + stats.put(scaledValue, value); + } + + totalDist += seg.getDistance(); + } + + if (totalDist != 0.0) { + int unitDecimals = FormatUtility.getUnitDecimals(units); + // Some extras such as steepness might provide inconsistent distance values caused by multiple rounding. + // Therefore, we try to scale distance so that their sum equals to the whole distance of a route + double distScale = totalDist / routeDistance; + + for (Map.Entry entry : stats.entrySet()) { + double scaledValue = entry.getValue() / distScale; + ExtraSummaryItem esi = new ExtraSummaryItem(entry.getKey(), + FormatUtility.roundToDecimals(DistanceUnitUtil.convert(scaledValue, DistanceUnit.METERS, units), unitDecimals), + FormatUtility.roundToDecimals(scaledValue * 100.0 / routeDistance, 2) + ); + + summary.add(esi); + } + + if (sort) + summary.sort(comp); + } + } + + return summary; + } + + public double getFactor() { + return factor; + } + + public void setFactor(double factor) { + this.factor = factor; + } + + public boolean isUsedForWarnings() { + return usedForWarnings; } public WarningGraphExtension getWarningGraphExtension() { - return warningGraphExtension; - } + return warningGraphExtension; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfoFlag.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfoFlag.java index 28f62ad56b..c4669333d2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfoFlag.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteExtraInfoFlag.java @@ -32,7 +32,8 @@ public class RouteExtraInfoFlag { public static final int SHADOW = 8192; public static final int CSV = 16384; - private RouteExtraInfoFlag() {} + private RouteExtraInfoFlag() { + } public static boolean isSet(int extraInfo, int value) { return (extraInfo & value) == value; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteInstructionsFormat.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteInstructionsFormat.java index f239aad45e..dbf5069670 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteInstructionsFormat.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteInstructionsFormat.java @@ -1,30 +1,29 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; public enum RouteInstructionsFormat { - UNKNOWN, - TEXT, - HTML; + UNKNOWN, + TEXT, + HTML; - public static RouteInstructionsFormat fromString(String text) - { - if ("TEXT".equalsIgnoreCase(text)) - return RouteInstructionsFormat.TEXT; - else if ("HTML".equalsIgnoreCase(text)) - return RouteInstructionsFormat.HTML; + public static RouteInstructionsFormat fromString(String text) { + if ("TEXT".equalsIgnoreCase(text)) + return RouteInstructionsFormat.TEXT; + else if ("HTML".equalsIgnoreCase(text)) + return RouteInstructionsFormat.HTML; - return RouteInstructionsFormat.UNKNOWN; - } + return RouteInstructionsFormat.UNKNOWN; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteLeg.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteLeg.java index a5581ebcad..9113306369 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteLeg.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteLeg.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; @@ -30,156 +30,156 @@ import static org.heigit.ors.routing.RouteResult.KEY_TIMEZONE_DEPARTURE; public class RouteLeg { - private final String type; - private final String departureLocation; - private final String tripHeadsign; - private final String routeLongName; - private final String routeShortName; - private final String routeDesc; - private final int routeType; - private final double distance; - private final double duration; - private final ZonedDateTime departureTime; - private final ZonedDateTime arrivalTime; - private final String feedId; - private final String tripId; - private final String routeId; - private final boolean isInSameVehicleAsPrevious; - private final Coordinate[] geometry; - private final List instructions; - private final List stops; - private final boolean includeElevation; - - public RouteLeg(Trip.Leg leg, List instructions, GHResponse response, RoutingRequest request) throws StatusCodeException { - DistanceUnit units = request.getUnits(); - distance = FormatUtility.roundToDecimalsForUnits(DistanceUnitUtil.convert(leg.getDistance(), DistanceUnit.METERS, units), units); - type = leg.type; - departureLocation = leg.departureLocation; - String timezoneDeparture = response.getHints().getString(KEY_TIMEZONE_DEPARTURE, "UTC"); - String timezoneArrival = response.getHints().getString(KEY_TIMEZONE_ARRIVAL, "UTC"); - departureTime = ZonedDateTime.ofInstant(leg.getDepartureTime().toInstant(), ZoneId.of(timezoneDeparture)); - arrivalTime = ZonedDateTime.ofInstant(leg.getArrivalTime().toInstant(), ZoneId.of(timezoneArrival)); - geometry = request.getIncludeGeometry() ? new Coordinate[leg.geometry.getCoordinates().length] : null; - if (geometry != null) { - for (int i = 0; i < leg.geometry.getCoordinates().length; i++) { - // this is an ugly hack since GH uses org.locationtech.jts.geom classes, and we expect com.vividsolutions.jts.geom classes. - // we seriously need to consolidate at some point. - geometry[i] = new Coordinate(leg.geometry.getCoordinates()[i].x, leg.geometry.getCoordinates()[i].y, leg.geometry.getCoordinates()[i].z); - } - } - this.instructions = instructions; - this.includeElevation = request.getIncludeElevation(); - if (leg instanceof Trip.PtLeg ptLeg) { - duration = FormatUtility.roundToDecimals(ptLeg.travelTime / 1000.0, 1); - tripHeadsign = ptLeg.trip_headsign; - routeLongName = ptLeg.route_long_name; - routeShortName = ptLeg.route_short_name; - routeDesc = ptLeg.route_desc; - routeType = ptLeg.route_type; - feedId = ptLeg.feed_id; - tripId = ptLeg.trip_id; - routeId = ptLeg.route_id; - isInSameVehicleAsPrevious = ptLeg.isInSameVehicleAsPrevious; - stops = new ArrayList<>(); - for (Trip.Stop stop : ptLeg.stops) { - stops.add(new RoutePtStop(stop)); - } - } else { // leg has to be an instance of Trip.WalkLeg - duration = FormatUtility.roundToDecimals(getDurationSum(instructions), 1); - tripHeadsign = null; - routeLongName = null; - routeShortName = null; - routeDesc = null; - routeType = -1; - feedId = null; - tripId = null; - routeId = null; - isInSameVehicleAsPrevious = false; - stops = null; - } - } - - private double getDurationSum(List instructions) { - double d = 0; - for (RouteStep step : instructions) { - d += step.getDuration(); - } - return d; - } - - public String getType() { - return type; - } - - public String getDepartureLocation() { - return departureLocation; - } - - public String getTripHeadsign() { - return tripHeadsign; - } - - public String getRouteLongName() { - return routeLongName; - } - - public String getRouteShortName() { - return routeShortName; - } - - public String getRouteDesc() { - return routeDesc; - } - - public int getRouteType() { - return routeType; - } - - public double getDistance() { - return distance; - } - - public double getDuration() { - return duration; - } - - public ZonedDateTime getDepartureTime() { - return departureTime; - } - - public ZonedDateTime getArrivalTime() { - return arrivalTime; - } - - public String getFeedId() { - return feedId; - } - - public String getTripId() { - return tripId; - } - - public String getRouteId() { - return routeId; - } - - public boolean isInSameVehicleAsPrevious() { - return isInSameVehicleAsPrevious; - } - - public Coordinate[] getGeometry() { - return geometry; - } - - public List getInstructions() { - return instructions; - } - - public List getStops() { - return stops; - } - - public boolean getIncludeElevation() { - return includeElevation; - } + private final String type; + private final String departureLocation; + private final String tripHeadsign; + private final String routeLongName; + private final String routeShortName; + private final String routeDesc; + private final int routeType; + private final double distance; + private final double duration; + private final ZonedDateTime departureTime; + private final ZonedDateTime arrivalTime; + private final String feedId; + private final String tripId; + private final String routeId; + private final boolean isInSameVehicleAsPrevious; + private final Coordinate[] geometry; + private final List instructions; + private final List stops; + private final boolean includeElevation; + + public RouteLeg(Trip.Leg leg, List instructions, GHResponse response, RoutingRequest request) throws StatusCodeException { + DistanceUnit units = request.getUnits(); + distance = FormatUtility.roundToDecimalsForUnits(DistanceUnitUtil.convert(leg.getDistance(), DistanceUnit.METERS, units), units); + type = leg.type; + departureLocation = leg.departureLocation; + String timezoneDeparture = response.getHints().getString(KEY_TIMEZONE_DEPARTURE, "UTC"); + String timezoneArrival = response.getHints().getString(KEY_TIMEZONE_ARRIVAL, "UTC"); + departureTime = ZonedDateTime.ofInstant(leg.getDepartureTime().toInstant(), ZoneId.of(timezoneDeparture)); + arrivalTime = ZonedDateTime.ofInstant(leg.getArrivalTime().toInstant(), ZoneId.of(timezoneArrival)); + geometry = request.getIncludeGeometry() ? new Coordinate[leg.geometry.getCoordinates().length] : null; + if (geometry != null) { + for (int i = 0; i < leg.geometry.getCoordinates().length; i++) { + // this is an ugly hack since GH uses org.locationtech.jts.geom classes, and we expect com.vividsolutions.jts.geom classes. + // we seriously need to consolidate at some point. + geometry[i] = new Coordinate(leg.geometry.getCoordinates()[i].x, leg.geometry.getCoordinates()[i].y, leg.geometry.getCoordinates()[i].z); + } + } + this.instructions = instructions; + this.includeElevation = request.getIncludeElevation(); + if (leg instanceof Trip.PtLeg ptLeg) { + duration = FormatUtility.roundToDecimals(ptLeg.travelTime / 1000.0, 1); + tripHeadsign = ptLeg.trip_headsign; + routeLongName = ptLeg.route_long_name; + routeShortName = ptLeg.route_short_name; + routeDesc = ptLeg.route_desc; + routeType = ptLeg.route_type; + feedId = ptLeg.feed_id; + tripId = ptLeg.trip_id; + routeId = ptLeg.route_id; + isInSameVehicleAsPrevious = ptLeg.isInSameVehicleAsPrevious; + stops = new ArrayList<>(); + for (Trip.Stop stop : ptLeg.stops) { + stops.add(new RoutePtStop(stop)); + } + } else { // leg has to be an instance of Trip.WalkLeg + duration = FormatUtility.roundToDecimals(getDurationSum(instructions), 1); + tripHeadsign = null; + routeLongName = null; + routeShortName = null; + routeDesc = null; + routeType = -1; + feedId = null; + tripId = null; + routeId = null; + isInSameVehicleAsPrevious = false; + stops = null; + } + } + + private double getDurationSum(List instructions) { + double d = 0; + for (RouteStep step : instructions) { + d += step.getDuration(); + } + return d; + } + + public String getType() { + return type; + } + + public String getDepartureLocation() { + return departureLocation; + } + + public String getTripHeadsign() { + return tripHeadsign; + } + + public String getRouteLongName() { + return routeLongName; + } + + public String getRouteShortName() { + return routeShortName; + } + + public String getRouteDesc() { + return routeDesc; + } + + public int getRouteType() { + return routeType; + } + + public double getDistance() { + return distance; + } + + public double getDuration() { + return duration; + } + + public ZonedDateTime getDepartureTime() { + return departureTime; + } + + public ZonedDateTime getArrivalTime() { + return arrivalTime; + } + + public String getFeedId() { + return feedId; + } + + public String getTripId() { + return tripId; + } + + public String getRouteId() { + return routeId; + } + + public boolean isInSameVehicleAsPrevious() { + return isInSameVehicleAsPrevious; + } + + public Coordinate[] getGeometry() { + return geometry; + } + + public List getInstructions() { + return instructions; + } + + public List getStops() { + return stops; + } + + public boolean getIncludeElevation() { + return includeElevation; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutePtStop.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutePtStop.java index d288a98d7f..afcd1e2705 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutePtStop.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutePtStop.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; @@ -21,74 +21,75 @@ import java.util.List; public class RoutePtStop { - private final String stopId; - private final String stopName; - private final Coordinate location; - - private final Date arrivalTime; - private final Date plannedArrivalTime; - private final Date predictedArrivalTime; - private final boolean arrivalCancelled; - - private final Date departureTime; - private final Date plannedDepartureTime; - private final Date predictedDepartureTime; - private final boolean departureCancelled; - public RoutePtStop(Trip.Stop stop) { - stopId = stop.stop_id; - stopName = stop.stop_name; - location = new Coordinate(stop.geometry.getX(), stop.geometry.getY()); - arrivalTime = stop.arrivalTime; - plannedArrivalTime = stop.plannedArrivalTime; - predictedArrivalTime = stop.predictedArrivalTime; - arrivalCancelled = stop.arrivalCancelled; - departureTime = stop.departureTime; - plannedDepartureTime = stop.plannedDepartureTime; - predictedDepartureTime = stop.predictedDepartureTime; - departureCancelled = stop.departureCancelled; - } - - public String getStopId() { - return stopId; - } - - public String getStopName() { - return stopName; - } - - public List getLocationAsCoordinateList() { - return Double.isNaN(location.z) ? Arrays.asList(location.x, location.y) : Arrays.asList(location.x, location.y, location.z); - } - - public Date getArrivalTime() { - return arrivalTime; - } - - public Date getPlannedArrivalTime() { - return plannedArrivalTime; - } - - public Date getPredictedArrivalTime() { - return predictedArrivalTime; - } - - public boolean isArrivalCancelled() { - return arrivalCancelled; - } - - public Date getDepartureTime() { - return departureTime; - } - - public Date getPlannedDepartureTime() { - return plannedDepartureTime; - } - - public Date getPredictedDepartureTime() { - return predictedDepartureTime; - } - - public boolean isDepartureCancelled() { - return departureCancelled; - } + private final String stopId; + private final String stopName; + private final Coordinate location; + + private final Date arrivalTime; + private final Date plannedArrivalTime; + private final Date predictedArrivalTime; + private final boolean arrivalCancelled; + + private final Date departureTime; + private final Date plannedDepartureTime; + private final Date predictedDepartureTime; + private final boolean departureCancelled; + + public RoutePtStop(Trip.Stop stop) { + stopId = stop.stop_id; + stopName = stop.stop_name; + location = new Coordinate(stop.geometry.getX(), stop.geometry.getY()); + arrivalTime = stop.arrivalTime; + plannedArrivalTime = stop.plannedArrivalTime; + predictedArrivalTime = stop.predictedArrivalTime; + arrivalCancelled = stop.arrivalCancelled; + departureTime = stop.departureTime; + plannedDepartureTime = stop.plannedDepartureTime; + predictedDepartureTime = stop.predictedDepartureTime; + departureCancelled = stop.departureCancelled; + } + + public String getStopId() { + return stopId; + } + + public String getStopName() { + return stopName; + } + + public List getLocationAsCoordinateList() { + return Double.isNaN(location.z) ? Arrays.asList(location.x, location.y) : Arrays.asList(location.x, location.y, location.z); + } + + public Date getArrivalTime() { + return arrivalTime; + } + + public Date getPlannedArrivalTime() { + return plannedArrivalTime; + } + + public Date getPredictedArrivalTime() { + return predictedArrivalTime; + } + + public boolean isArrivalCancelled() { + return arrivalCancelled; + } + + public Date getDepartureTime() { + return departureTime; + } + + public Date getPlannedDepartureTime() { + return plannedDepartureTime; + } + + public Date getPredictedDepartureTime() { + return predictedDepartureTime; + } + + public boolean isDepartureCancelled() { + return departureCancelled; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteResult.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteResult.java index 488684f89c..7a090cea7c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteResult.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteResult.java @@ -1,24 +1,24 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; import com.graphhopper.ResponsePath; import com.graphhopper.util.PointList; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.common.DistanceUnit; import org.heigit.ors.util.FormatUtility; import org.heigit.ors.util.GeomUtility; +import org.locationtech.jts.geom.Coordinate; import java.time.ZonedDateTime; import java.util.ArrayList; @@ -26,216 +26,205 @@ public class RouteResult { - private Coordinate[] geometry; - private List segments; - private List legs; - private List extraInfo; - private PointList pointlist; - private String graphDate = ""; - private final List wayPointsIndices; - private final List routeWarnings; - private final RouteSummary summary; - - private ZonedDateTime departure; - private ZonedDateTime arrival; - public static final String KEY_TIMEZONE_DEPARTURE = "timezone.departure"; - public static final String KEY_TIMEZONE_ARRIVAL = "timezone.arrival"; - public static final String DEFAULT_TIMEZONE = "Europe/Berlin"; - - public RouteResult(int routeExtras) { - segments = new ArrayList<>(); - summary = new RouteSummary(); - if (routeExtras != 0) - extraInfo = new ArrayList<>(); - routeWarnings = new ArrayList<>(); - wayPointsIndices = new ArrayList<>(); - legs = new ArrayList<>(); - } - - public void addSegment(RouteSegment seg) - { - segments.add(seg); - } - - public List getSegments() - { - return segments; - } - - public void resetSegments() { - segments = new ArrayList<>(); - } - - public RouteSummary getSummary() - { - return summary; - } - - public Coordinate[] getGeometry() { - return geometry; - } - - public void addPointsToGeometry(PointList points, boolean skipFirstPoint, boolean includeElevation) - { - int index = skipFirstPoint ? 1 : 0; - - if (geometry == null) - { - int newSize = points.size() - index; - geometry = new Coordinate[newSize]; - - if (includeElevation && points.is3D()) - { - for (int i = index; i < newSize; ++i) - geometry[i] = new Coordinate(points.getLon(i), points.getLat(i), points.getEle(i)); - } - else - { - for (int i= index; i < newSize; ++i) - geometry[i] = new Coordinate(points.getLon(i), points.getLat(i)); - } - } - else - { - int oldSize = geometry.length; - int pointsSize = points.size() - index; - int newSize = oldSize + pointsSize; - Coordinate[] coords = new Coordinate[newSize]; - System.arraycopy(geometry, 0, coords, 0, oldSize); - for (int i = 0; i < pointsSize; ++i) { - int j = i + index; - if (includeElevation && points.is3D()) - coords[oldSize + i] = new Coordinate(points.getLon(j), points.getLat(j), points.getEle(j)); - else - coords[oldSize + i] = new Coordinate(points.getLon(j), points.getLat(j)); - } - - geometry = coords; - } - } - - - public List getExtraInfo() - { - return extraInfo; - } - - private void addExtraInfo(RouteExtraInfo info) - { - if(extraInfo == null) - extraInfo = new ArrayList<>(); - extraInfo.add(info); - } - - public void addWarning(RouteWarning warning) { - routeWarnings.add(warning); - } - - public List getWarnings() { - return routeWarnings; - } - - public void addPointlist(PointList pointlistToAdd) { - if (pointlist == null) { - pointlist = new PointList(pointlistToAdd.size(), pointlistToAdd.is3D()); - } - pointlist.add(pointlistToAdd); - } - - public List getWayPointsIndices() { - return wayPointsIndices; - } - - public void addWayPointIndex(int index) { - wayPointsIndices.add(index); - } - - void addExtras(RoutingRequest request, List extras) { - if (extras == null) - return; - // add the extras if they generate a "warning" or they were requested - for (RouteExtraInfo extra : extras) { - if (extra.isUsedForWarnings() && extra.getWarningGraphExtension().generatesWarning(extra)) { - addWarning(extra.getWarningGraphExtension().getWarning()); - addExtraInfo(extra); - } else if (RouteExtraInfoFlag.isSet(request.getExtraInfo(), RouteExtraInfoFlag.getFromString(extra.getName()))) { - addExtraInfo(extra); - } - } - } - - /** - * set route summary values according to segments in this route and request parameters - * @param request for parameter lookup (units, include elevation) - */ - void calculateRouteSummary(RoutingRequest request) { - calculateRouteSummary(request, null); - } - - void calculateRouteSummary(RoutingRequest request, ResponsePath path) { - double distance = 0.0; - double duration = 0.0; - for (RouteSegment seg : getSegments()) { - distance += seg.getDistance(); - duration += seg.getDuration(); - } - summary.setDuration(duration); - summary.setDistance(FormatUtility.roundToDecimalsForUnits(distance, request.getUnits())); - double averageSpeed = 0; - if (duration > 0) - averageSpeed = distance / (request.getUnits() == DistanceUnit.METERS ? 1000 : 1) / (duration / 3600); - summary.setAverageSpeed(FormatUtility.roundToDecimals(averageSpeed, 1)); - summary.setBBox(GeomUtility.calculateBoundingBox(pointlist)); - if (request.getIncludeElevation()) { - double ascent = 0.0; - double descent = 0.0; - for (RouteSegment seg : getSegments()) { - ascent += seg.getAscent(); - descent += seg.getDescent(); - } - summary.setAscent(FormatUtility.roundToDecimals(ascent, 1)); - summary.setDescent(FormatUtility.roundToDecimals(descent, 1)); - } - if (path != null) { - summary.setTransfers(path.getNumChanges()); - if (path.getFare() != null) - summary.setFare(path.getFare().intValue()); - } - } - - public String getGraphDate() { - return graphDate; - } - - public void setGraphDate(String graphDate) { - this.graphDate = graphDate; - } - - public boolean hasDepartureAndArrival() { - return (departure!=null && arrival!=null); - } - - public ZonedDateTime getDeparture() { - return departure; - } - - public void setDeparture(ZonedDateTime departure) { - this.departure = departure; - } - - public ZonedDateTime getArrival() { - return arrival; - } - - public void setArrival(ZonedDateTime arrival) { - this.arrival = arrival; - } - - public void addLeg(RouteLeg leg) { - legs.add(leg); - } - - public List getLegs() { - return legs; - } + private Coordinate[] geometry; + private List segments; + private final List legs; + private List extraInfo; + private PointList pointlist; + private String graphDate = ""; + private final List wayPointsIndices; + private final List routeWarnings; + private final RouteSummary summary; + + private ZonedDateTime departure; + private ZonedDateTime arrival; + public static final String KEY_TIMEZONE_DEPARTURE = "timezone.departure"; + public static final String KEY_TIMEZONE_ARRIVAL = "timezone.arrival"; + public static final String DEFAULT_TIMEZONE = "Europe/Berlin"; + + public RouteResult(int routeExtras) { + segments = new ArrayList<>(); + summary = new RouteSummary(); + if (routeExtras != 0) + extraInfo = new ArrayList<>(); + routeWarnings = new ArrayList<>(); + wayPointsIndices = new ArrayList<>(); + legs = new ArrayList<>(); + } + + public void addSegment(RouteSegment seg) { + segments.add(seg); + } + + public List getSegments() { + return segments; + } + + public void resetSegments() { + segments = new ArrayList<>(); + } + + public RouteSummary getSummary() { + return summary; + } + + public Coordinate[] getGeometry() { + return geometry; + } + + public void addPointsToGeometry(PointList points, boolean skipFirstPoint, boolean includeElevation) { + int index = skipFirstPoint ? 1 : 0; + + if (geometry == null) { + int newSize = points.size() - index; + geometry = new Coordinate[newSize]; + + if (includeElevation && points.is3D()) { + for (int i = index; i < newSize; ++i) + geometry[i] = new Coordinate(points.getLon(i), points.getLat(i), points.getEle(i)); + } else { + for (int i = index; i < newSize; ++i) + geometry[i] = new Coordinate(points.getLon(i), points.getLat(i)); + } + } else { + int oldSize = geometry.length; + int pointsSize = points.size() - index; + int newSize = oldSize + pointsSize; + Coordinate[] coords = new Coordinate[newSize]; + System.arraycopy(geometry, 0, coords, 0, oldSize); + for (int i = 0; i < pointsSize; ++i) { + int j = i + index; + if (includeElevation && points.is3D()) + coords[oldSize + i] = new Coordinate(points.getLon(j), points.getLat(j), points.getEle(j)); + else + coords[oldSize + i] = new Coordinate(points.getLon(j), points.getLat(j)); + } + + geometry = coords; + } + } + + + public List getExtraInfo() { + return extraInfo; + } + + private void addExtraInfo(RouteExtraInfo info) { + if (extraInfo == null) + extraInfo = new ArrayList<>(); + extraInfo.add(info); + } + + public void addWarning(RouteWarning warning) { + routeWarnings.add(warning); + } + + public List getWarnings() { + return routeWarnings; + } + + public void addPointlist(PointList pointlistToAdd) { + if (pointlist == null) { + pointlist = new PointList(pointlistToAdd.size(), pointlistToAdd.is3D()); + } + pointlist.add(pointlistToAdd); + } + + public List getWayPointsIndices() { + return wayPointsIndices; + } + + public void addWayPointIndex(int index) { + wayPointsIndices.add(index); + } + + void addExtras(RoutingRequest request, List extras) { + if (extras == null) + return; + // add the extras if they generate a "warning" or they were requested + for (RouteExtraInfo extra : extras) { + if (extra.isUsedForWarnings() && extra.getWarningGraphExtension().generatesWarning(extra)) { + addWarning(extra.getWarningGraphExtension().getWarning()); + addExtraInfo(extra); + } else if (RouteExtraInfoFlag.isSet(request.getExtraInfo(), RouteExtraInfoFlag.getFromString(extra.getName()))) { + addExtraInfo(extra); + } + } + } + + /** + * set route summary values according to segments in this route and request parameters + * + * @param request for parameter lookup (units, include elevation) + */ + void calculateRouteSummary(RoutingRequest request) { + calculateRouteSummary(request, null); + } + + void calculateRouteSummary(RoutingRequest request, ResponsePath path) { + double distance = 0.0; + double duration = 0.0; + for (RouteSegment seg : getSegments()) { + distance += seg.getDistance(); + duration += seg.getDuration(); + } + summary.setDuration(duration); + summary.setDistance(FormatUtility.roundToDecimalsForUnits(distance, request.getUnits())); + double averageSpeed = 0; + if (duration > 0) + averageSpeed = distance / (request.getUnits() == DistanceUnit.METERS ? 1000 : 1) / (duration / 3600); + summary.setAverageSpeed(FormatUtility.roundToDecimals(averageSpeed, 1)); + summary.setBBox(GeomUtility.calculateBoundingBox(pointlist)); + if (request.getIncludeElevation()) { + double ascent = 0.0; + double descent = 0.0; + for (RouteSegment seg : getSegments()) { + ascent += seg.getAscent(); + descent += seg.getDescent(); + } + summary.setAscent(FormatUtility.roundToDecimals(ascent, 1)); + summary.setDescent(FormatUtility.roundToDecimals(descent, 1)); + } + if (path != null) { + summary.setTransfers(path.getNumChanges()); + if (path.getFare() != null) + summary.setFare(path.getFare().intValue()); + } + } + + public String getGraphDate() { + return graphDate; + } + + public void setGraphDate(String graphDate) { + this.graphDate = graphDate; + } + + public boolean hasDepartureAndArrival() { + return (departure != null && arrival != null); + } + + public ZonedDateTime getDeparture() { + return departure; + } + + public void setDeparture(ZonedDateTime departure) { + this.departure = departure; + } + + public ZonedDateTime getArrival() { + return arrival; + } + + public void setArrival(ZonedDateTime arrival) { + this.arrival = arrival; + } + + public void addLeg(RouteLeg leg) { + legs.add(leg); + } + + public List getLegs() { + return legs; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteResultBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteResultBuilder.java index 41465ee7f6..d75ae2e616 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteResultBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteResultBuilder.java @@ -37,17 +37,16 @@ import static org.heigit.ors.routing.RouteResult.*; // visibilities needed until RouteResultBuilderTest is properly migrated -public class RouteResultBuilder -{ - private final AngleCalc angleCalc; - private final DistanceCalc distCalc; - private static final CardinalDirection[] directions = {CardinalDirection.NORTH, CardinalDirection.NORTH_EAST, CardinalDirection.EAST, CardinalDirection.SOUTH_EAST, CardinalDirection.SOUTH, CardinalDirection.SOUTH_WEST, CardinalDirection.WEST, CardinalDirection.NORTH_WEST}; +public class RouteResultBuilder { + private final AngleCalc angleCalc; + private final DistanceCalc distCalc; + private static final CardinalDirection[] directions = {CardinalDirection.NORTH, CardinalDirection.NORTH_EAST, CardinalDirection.EAST, CardinalDirection.SOUTH_EAST, CardinalDirection.SOUTH, CardinalDirection.SOUTH_WEST, CardinalDirection.WEST, CardinalDirection.NORTH_WEST}; private int startWayPointIndex = 0; - public RouteResultBuilder() { - angleCalc = new AngleCalc(); - distCalc = new DistanceCalcEarth(); - } + public RouteResultBuilder() { + angleCalc = new AngleCalc(); + distCalc = new DistanceCalcEarth(); + } RouteResult[] createRouteResults(List responses, RoutingRequest request, List[] extras) throws Exception { if (responses.isEmpty()) @@ -58,7 +57,7 @@ RouteResult[] createRouteResults(List responses, RoutingRequest requ return createRouteResultSetFromMultiplePaths(responses.get(0), request, extras); } - private RouteResult createInitialRouteResult (RoutingRequest request, List extras) { + private RouteResult createInitialRouteResult(RoutingRequest request, List extras) { RouteResult result = new RouteResult(request.getExtraInfo()); result.addExtras(request, extras); @@ -102,7 +101,7 @@ public RouteResult createMergedRouteResultFromBestPaths(List respons if (request.getSearchParameters().isTimeDependent()) { String timezoneDeparture = responses.get(0).getHints().getString(KEY_TIMEZONE_DEPARTURE, DEFAULT_TIMEZONE); - String timezoneArrival = responses.get(responses.size()-1).getHints().getString(KEY_TIMEZONE_ARRIVAL, DEFAULT_TIMEZONE); + String timezoneArrival = responses.get(responses.size() - 1).getHints().getString(KEY_TIMEZONE_ARRIVAL, DEFAULT_TIMEZONE); setDepartureArrivalTimes(timezoneDeparture, timezoneArrival, request, result); } @@ -209,12 +208,12 @@ private RouteSegment createRouteSegment(ResponsePath path, RoutingRequest reques private void addLegsToRouteResult(RouteResult result, RoutingRequest request, List legs, GHResponse response) throws Exception { for (Trip.Leg leg : legs) { startWayPointIndex = 0; - List instructions = leg instanceof Trip.WalkLeg wl ? convertRouteSteps(wl.instructions, PointList.from((LineString)leg.geometry), request, null) : null; + List instructions = leg instanceof Trip.WalkLeg wl ? convertRouteSteps(wl.instructions, PointList.from((LineString) leg.geometry), request, null) : null; result.addLeg(new RouteLeg(leg, instructions, response, request)); } } - private List convertRouteSteps(InstructionList instructions, PointList points, RoutingRequest request, PointList nextRouteFirstStepPoints) throws Exception{ + private List convertRouteSteps(InstructionList instructions, PointList points, RoutingRequest request, PointList nextRouteFirstStepPoints) throws Exception { List result = new ArrayList<>(); int nInstructions = instructions.size(); InstructionTranslator instrTranslator = InstructionTranslatorsCache.getInstance().getTranslator(request.getLanguage()); @@ -324,45 +323,44 @@ private ArrivalDirection getArrivalDirection(PointList points, Coordinate destin if (points.size() < 2) return ArrivalDirection.UNKNOWN; - int lastIndex = points.size() - 1; - double lon0 = points.getLon(lastIndex - 1); - double lat0 = points.getLat(lastIndex - 1); - double lon1 = points.getLon(lastIndex); - double lat1 = points.getLat(lastIndex); - - double dist = distCalc.calcDist(lat1, lon1, destination.y, destination.x); - - if (dist < 1) - return ArrivalDirection.STRAIGHT_AHEAD; - else - { - double sign = Math.signum((lon1 - lon0) * (destination.y - lat0) - (lat1 - lat0) * (destination.x - lon0)); - if (sign == 0) - return ArrivalDirection.STRAIGHT_AHEAD; - else if (sign == 1) - return ArrivalDirection.LEFT; - else - return ArrivalDirection.RIGHT; - } - } - - private int getEndWayPointIndex(int startIndex, InstructionType instrType, Instruction instr) { - if (instrType == InstructionType.FINISH + int lastIndex = points.size() - 1; + double lon0 = points.getLon(lastIndex - 1); + double lat0 = points.getLat(lastIndex - 1); + double lon1 = points.getLon(lastIndex); + double lat1 = points.getLat(lastIndex); + + double dist = distCalc.calcDist(lat1, lon1, destination.y, destination.x); + + if (dist < 1) + return ArrivalDirection.STRAIGHT_AHEAD; + else { + double sign = Math.signum((lon1 - lon0) * (destination.y - lat0) - (lat1 - lat0) * (destination.x - lon0)); + if (sign == 0) + return ArrivalDirection.STRAIGHT_AHEAD; + else if (sign == 1) + return ArrivalDirection.LEFT; + else + return ArrivalDirection.RIGHT; + } + } + + private int getEndWayPointIndex(int startIndex, InstructionType instrType, Instruction instr) { + if (instrType == InstructionType.FINISH // "empty" departure instruction means start and end coordinates are the same, index should not increase || (instrType == InstructionType.DEPART && instr.getDistance() == 0.0 && instr.getPoints().size() == 1) - ) - return startIndex; - else - return startIndex + instr.getPoints().size(); - } - - private RouteStepManeuver calcManeuver(InstructionType instrType, PointList prevSegPoints, PointList segPoints, PointList nextSegPoints) { - RouteStepManeuver maneuver = new RouteStepManeuver(); + ) + return startIndex; + else + return startIndex + instr.getPoints().size(); + } + + private RouteStepManeuver calcManeuver(InstructionType instrType, PointList prevSegPoints, PointList segPoints, PointList nextSegPoints) { + RouteStepManeuver maneuver = new RouteStepManeuver(); maneuver.setBearingBefore(0); maneuver.setBearingAfter(0); - if (nextSegPoints == null) { + if (nextSegPoints == null) { return maneuver; - } + } if (instrType == InstructionType.DEPART) { double lon0 = segPoints.getLon(0); double lat0 = segPoints.getLat(0); @@ -370,13 +368,13 @@ private RouteStepManeuver calcManeuver(InstructionType instrType, PointList prev double lon1; double lat1; if (segPoints.size() == 1) { - lon1 = nextSegPoints.getLon(0); - lat1 = nextSegPoints.getLat(0); + lon1 = nextSegPoints.getLon(0); + lat1 = nextSegPoints.getLat(0); } else { - lon1 = segPoints.getLon(1); - lat1 = segPoints.getLat(1); + lon1 = segPoints.getLon(1); + lat1 = segPoints.getLat(1); } - maneuver.setBearingAfter((int)Math.round(angleCalc.calcAzimuth(lat0, lon0, lat1, lon1))); + maneuver.setBearingAfter((int) Math.round(angleCalc.calcAzimuth(lat0, lon0, lat1, lon1))); } else if (prevSegPoints.size() > 0) { int locIndex = prevSegPoints.size() - 1; double lon0 = prevSegPoints.getLon(locIndex); @@ -384,7 +382,7 @@ private RouteStepManeuver calcManeuver(InstructionType instrType, PointList prev double lon1 = segPoints.getLon(0); double lat1 = segPoints.getLat(0); maneuver.setLocation(new Coordinate(lon1, lat1)); - maneuver.setBearingBefore((int)Math.round(angleCalc.calcAzimuth(lat0, lon0, lat1, lon1))); + maneuver.setBearingBefore((int) Math.round(angleCalc.calcAzimuth(lat0, lon0, lat1, lon1))); if (instrType != InstructionType.FINISH) { double lon2; double lat2; @@ -395,26 +393,26 @@ private RouteStepManeuver calcManeuver(InstructionType instrType, PointList prev lon2 = segPoints.getLon(1); lat2 = segPoints.getLat(1); } - maneuver.setBearingAfter((int)Math.round(angleCalc.calcAzimuth(lat1, lon1, lat2, lon2))); + maneuver.setBearingAfter((int) Math.round(angleCalc.calcAzimuth(lat1, lon1, lat2, lon2))); } } return maneuver; - } + } - private boolean isTurnInstruction(InstructionType instrType) { - return instrType == InstructionType.TURN_LEFT || instrType == InstructionType.TURN_SLIGHT_LEFT - || instrType == InstructionType.TURN_SHARP_LEFT || instrType == InstructionType.TURN_RIGHT - || instrType == InstructionType.TURN_SLIGHT_RIGHT || instrType == InstructionType.TURN_SHARP_RIGHT; - } + private boolean isTurnInstruction(InstructionType instrType) { + return instrType == InstructionType.TURN_LEFT || instrType == InstructionType.TURN_SLIGHT_LEFT + || instrType == InstructionType.TURN_SHARP_LEFT || instrType == InstructionType.TURN_RIGHT + || instrType == InstructionType.TURN_SLIGHT_RIGHT || instrType == InstructionType.TURN_SHARP_RIGHT; + } - private boolean isKeepInstruction(InstructionType instrType){ - return instrType == InstructionType.KEEP_LEFT || instrType == InstructionType.KEEP_RIGHT; + private boolean isKeepInstruction(InstructionType instrType) { + return instrType == InstructionType.KEEP_LEFT || instrType == InstructionType.KEEP_RIGHT; } - private InstructionType getInstructionType(boolean isDepart, Instruction instr) { - if (isDepart) { - return InstructionType.DEPART; - } + private InstructionType getInstructionType(boolean isDepart, Instruction instr) { + if (isDepart) { + return InstructionType.DEPART; + } return switch (instr.getSign()) { case Instruction.TURN_LEFT -> InstructionType.TURN_LEFT; @@ -434,17 +432,17 @@ private InstructionType getInstructionType(boolean isDepart, Instruction instr) case Instruction.CONTINUE_ON_STREET -> InstructionType.CONTINUE; default -> InstructionType.CONTINUE; }; - } + } - private CardinalDirection calcDirection(double lat1, double lon1, double lat2, double lon2 ) { - double orientation = - angleCalc.calcOrientation(lat1, lon1, lat2, lon2); - orientation = Helper.round4(orientation + Math.PI / 2); - if (orientation < 0) - orientation += 2 * Math.PI; + private CardinalDirection calcDirection(double lat1, double lon1, double lat2, double lon2) { + double orientation = -angleCalc.calcOrientation(lat1, lon1, lat2, lon2); + orientation = Helper.round4(orientation + Math.PI / 2); + if (orientation < 0) + orientation += 2 * Math.PI; - double degree = Math.toDegrees(orientation); - return directions[(int)Math.floor(((degree+ 22.5) % 360) / 45)]; - } + double degree = Math.toDegrees(orientation); + return directions[(int) Math.floor(((degree + 22.5) % 360) / 45)]; + } private void handleResponseWarnings(RouteResult result, GHResponse response) { String skippedExtras = response.getHints().getString("skipped_extra_info", ""); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchContext.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchContext.java index dc5d12574e..888ff4622a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchContext.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchContext.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; @@ -18,42 +18,40 @@ import com.graphhopper.util.PMap; public class RouteSearchContext { - private final GraphHopper graphhopper; - private final FlagEncoder encoder; - private final String profileName; - private final String profileNameCH; - private PMap properties; - - public RouteSearchContext(GraphHopper gh, FlagEncoder encoder, String profileName, String profileNameCH) { - graphhopper = gh; - this.encoder = encoder; - this.profileName = profileName; - this.profileNameCH = profileNameCH; - } - - public FlagEncoder getEncoder() { - return encoder; - } - - public GraphHopper getGraphHopper() { - return graphhopper; - } - - public PMap getProperties() - { - return properties; - } - - public void setProperties(PMap value) - { - properties = value; - } - - public String profileName() { - return profileName; - } - - public String profileNameCH() { - return profileNameCH; - } + private final GraphHopper graphhopper; + private final FlagEncoder encoder; + private final String profileName; + private final String profileNameCH; + private PMap properties; + + public RouteSearchContext(GraphHopper gh, FlagEncoder encoder, String profileName, String profileNameCH) { + graphhopper = gh; + this.encoder = encoder; + this.profileName = profileName; + this.profileNameCH = profileNameCH; + } + + public FlagEncoder getEncoder() { + return encoder; + } + + public GraphHopper getGraphHopper() { + return graphhopper; + } + + public PMap getProperties() { + return properties; + } + + public void setProperties(PMap value) { + properties = value; + } + + public String profileName() { + return profileName; + } + + public String profileNameCH() { + return profileNameCH; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchParameters.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchParameters.java index 416d9e1299..35f982241d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchParameters.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSearchParameters.java @@ -13,34 +13,14 @@ */ package org.heigit.ors.routing; -import com.graphhopper.util.Helper; -import org.locationtech.jts.geom.Geometry; -import org.locationtech.jts.geom.MultiPolygon; -import org.locationtech.jts.geom.Polygon; -import org.heigit.ors.common.StatusCode; -import org.heigit.ors.config.AppConfig; -import org.heigit.ors.exceptions.InternalServerException; -import org.heigit.ors.exceptions.ParameterValueException; -import org.heigit.ors.exceptions.StatusCodeException; -import org.heigit.ors.exceptions.UnknownParameterValueException; -import org.heigit.ors.geojson.GeometryJSON; import org.heigit.ors.routing.graphhopper.extensions.HeavyVehicleAttributes; -import org.heigit.ors.routing.graphhopper.extensions.VehicleLoadCharacteristicsFlags; -import org.heigit.ors.routing.graphhopper.extensions.WheelchairTypesEncoder; -import org.heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersReader; import org.heigit.ors.routing.parameters.ProfileParameters; import org.heigit.ors.routing.parameters.VehicleParameters; -import org.heigit.ors.routing.parameters.WheelchairParameters; import org.heigit.ors.routing.pathprocessors.BordersExtractor; -import org.heigit.ors.util.GeomUtility; -import org.heigit.ors.util.StringUtility; -import org.json.JSONArray; -import org.json.JSONObject; +import org.locationtech.jts.geom.Polygon; -import java.text.ParseException; import java.time.Duration; import java.time.LocalDateTime; -import java.util.Iterator; /** * This class is used to store the search/calculation Parameters to calculate the desired Route/Isochrones etc… @@ -324,14 +304,14 @@ public boolean hasNonDefaultVehicleType() { public boolean requiresDynamicPreprocessedWeights() { return hasAvoidAreas() - || hasAvoidFeatures() - || hasAvoidBorders() - || hasAvoidCountries() - || getConsiderTurnRestrictions() - || hasNonDefaultVehicleType() - || isProfileTypeDriving() && hasParameters(VehicleParameters.class) - || hasMaximumSpeed() - || hasFlexibleMode(); + || hasAvoidFeatures() + || hasAvoidBorders() + || hasAvoidCountries() + || getConsiderTurnRestrictions() + || hasNonDefaultVehicleType() + || isProfileTypeDriving() && hasParameters(VehicleParameters.class) + || hasMaximumSpeed() + || hasFlexibleMode(); } /** @@ -339,10 +319,10 @@ public boolean requiresDynamicPreprocessedWeights() { */ public boolean requiresFullyDynamicWeights() { return hasAvoidAreas() - || hasBearings() - || hasContinueStraight() - || (getProfileParameters() != null && getProfileParameters().hasWeightings()) - || getAlternativeRoutesCount() > 0; + || hasBearings() + || hasContinueStraight() + || (getProfileParameters() != null && getProfileParameters().hasWeightings()) + || getAlternativeRoutesCount() > 0; } // time-dependent stuff @@ -355,7 +335,7 @@ public void setDeparture(LocalDateTime departure) { } public boolean hasDeparture() { - return departure!=null; + return departure != null; } public LocalDateTime getArrival() { @@ -366,7 +346,9 @@ public void setArrival(LocalDateTime arrival) { this.arrival = arrival; } - public boolean hasArrival() { return arrival!=null; } + public boolean hasArrival() { + return arrival != null; + } public boolean isTimeDependent() { return (hasDeparture() || hasArrival()); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegment.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegment.java index 36eecb75cb..7f8fa732e0 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegment.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegment.java @@ -1,19 +1,18 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; -import com.graphhopper.ResponsePath; import com.graphhopper.ResponsePath; import org.heigit.ors.common.DistanceUnit; import org.heigit.ors.util.DistanceUnitUtil; @@ -23,70 +22,62 @@ import java.util.List; public class RouteSegment { - private final double distance; - private final double duration; - private final double ascent; - private final double descent; - private double detourFactor = 0.0; - private final List steps; - - public RouteSegment(ResponsePath path, DistanceUnit units) throws Exception { - distance = FormatUtility.roundToDecimalsForUnits(DistanceUnitUtil.convert(path.getDistance(), DistanceUnit.METERS, units), units); - duration = FormatUtility.roundToDecimals(path.getTime()/1000.0, 1); - ascent = path.getAscend(); - descent = path.getDescend(); - steps = new ArrayList<>(); - } - - public double getDistance() - { - return distance; - } - - public double getDuration() - { - return duration; - } - - public double getAscent() - { - return ascent; - } - - public double getDescent() - { - return descent; - } - - public double getAscentRounded() - { - return FormatUtility.roundToDecimals(ascent, 1); - } - - public double getDescentRounded() - { - return FormatUtility.roundToDecimals(descent, 1); - } - - public void addStep(RouteStep step) - { - steps.add(step); - } - - public void addSteps(List stepsToAdd) - { - steps.addAll(stepsToAdd); - } - - public List getSteps() { - return steps; - } - - public double getDetourFactor() { - return detourFactor; - } - - public void setDetourFactor(double detourFactor) { - this.detourFactor = detourFactor; - } + private final double distance; + private final double duration; + private final double ascent; + private final double descent; + private double detourFactor = 0.0; + private final List steps; + + public RouteSegment(ResponsePath path, DistanceUnit units) throws Exception { + distance = FormatUtility.roundToDecimalsForUnits(DistanceUnitUtil.convert(path.getDistance(), DistanceUnit.METERS, units), units); + duration = FormatUtility.roundToDecimals(path.getTime() / 1000.0, 1); + ascent = path.getAscend(); + descent = path.getDescend(); + steps = new ArrayList<>(); + } + + public double getDistance() { + return distance; + } + + public double getDuration() { + return duration; + } + + public double getAscent() { + return ascent; + } + + public double getDescent() { + return descent; + } + + public double getAscentRounded() { + return FormatUtility.roundToDecimals(ascent, 1); + } + + public double getDescentRounded() { + return FormatUtility.roundToDecimals(descent, 1); + } + + public void addStep(RouteStep step) { + steps.add(step); + } + + public void addSteps(List stepsToAdd) { + steps.addAll(stepsToAdd); + } + + public List getSteps() { + return steps; + } + + public double getDetourFactor() { + return detourFactor; + } + + public void setDetourFactor(double detourFactor) { + this.detourFactor = detourFactor; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegmentItem.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegmentItem.java index aa95e58a17..73e4949bef 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegmentItem.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSegmentItem.java @@ -1,62 +1,60 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; public class RouteSegmentItem { - private int from; - private int to; - private long value; - private double distance; - - public RouteSegmentItem(int from, int to, long value, double distance) { - this.from = from; - this.to = to; - this.value = value; - this.distance = distance; - } - - public int getFrom() { - return from; - } - - public void setFrom(int from) { - this.from = from; - } - - public int getTo() { - return to; - } - - public void setTo(int to) { - this.to = to; - } - - public long getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } - - public double getDistance() - { - return distance; - } - - public void setDistance(double value) - { - distance = value; - } + private int from; + private int to; + private long value; + private double distance; + + public RouteSegmentItem(int from, int to, long value, double distance) { + this.from = from; + this.to = to; + this.value = value; + this.distance = distance; + } + + public int getFrom() { + return from; + } + + public void setFrom(int from) { + this.from = from; + } + + public int getTo() { + return to; + } + + public void setTo(int to) { + this.to = to; + } + + public long getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public double getDistance() { + return distance; + } + + public void setDistance(double value) { + distance = value; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteStep.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteStep.java index 483dccb767..8ebc02523f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteStep.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteStep.java @@ -1,116 +1,116 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; public class RouteStep { - private double distance = 0.0; - private double duration = 0.0; - private String message; - private int messageType = -1; - private String instruction = ""; - private String name = null; - private int exitNumber = -1; - private int type; - private int[] wayPoints; + private double distance = 0.0; + private double duration = 0.0; + private String message; + private int messageType = -1; + private String instruction = ""; + private String name = null; + private int exitNumber = -1; + private int type; + private int[] wayPoints; private RouteStepManeuver maneuver; private int[] roundaboutExitBearings; - - public double getDuration() { - return duration; - } - - public void setDuration(double duration) { - this.duration = duration; - } - - public double getDistance() { - return distance; - } - - public void setDistance(double distance) { - this.distance = distance; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public int getExitNumber() { - return exitNumber; - } - - public void setExitNumber(int exitNumber) { - this.exitNumber = exitNumber; - } - - public String getInstruction() { - return instruction; - } - - public void setInstruction(String text) { - instruction = text; - } - - public int[] getWayPoints() { - return wayPoints; - } - - public void setWayPoints(int[] wayPoints) { - this.wayPoints = wayPoints; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getMessageType() { - return messageType; - } - - public void setMessageType(int messageType) { - this.messageType = messageType; - } - - public RouteStepManeuver getManeuver() { - return maneuver; - } - - public void setManeuver(RouteStepManeuver maneuver) { - this.maneuver = maneuver; - } - - public int[] getRoundaboutExitBearings() { - return roundaboutExitBearings; - } - - public void setRoundaboutExitBearings(int[] roundaboutExitBearings) { - this.roundaboutExitBearings = roundaboutExitBearings; - } + + public double getDuration() { + return duration; + } + + public void setDuration(double duration) { + this.duration = duration; + } + + public double getDistance() { + return distance; + } + + public void setDistance(double distance) { + this.distance = distance; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getExitNumber() { + return exitNumber; + } + + public void setExitNumber(int exitNumber) { + this.exitNumber = exitNumber; + } + + public String getInstruction() { + return instruction; + } + + public void setInstruction(String text) { + instruction = text; + } + + public int[] getWayPoints() { + return wayPoints; + } + + public void setWayPoints(int[] wayPoints) { + this.wayPoints = wayPoints; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getMessageType() { + return messageType; + } + + public void setMessageType(int messageType) { + this.messageType = messageType; + } + + public RouteStepManeuver getManeuver() { + return maneuver; + } + + public void setManeuver(RouteStepManeuver maneuver) { + this.maneuver = maneuver; + } + + public int[] getRoundaboutExitBearings() { + return roundaboutExitBearings; + } + + public void setRoundaboutExitBearings(int[] roundaboutExitBearings) { + this.roundaboutExitBearings = roundaboutExitBearings; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteStepManeuver.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteStepManeuver.java index e9e31dfccd..8db17145fe 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteStepManeuver.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteStepManeuver.java @@ -1,50 +1,50 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; import org.locationtech.jts.geom.Coordinate; public class RouteStepManeuver { - private Coordinate location; - private int bearingBefore = 0; - private int bearingAfter = 0; - - public Coordinate getLocation() { - return location; - } - - public void setLocation(Coordinate location) { - this.location = location; - } - - public int getBearingBefore() { - return bearingBefore; - } - - public void setBearingBefore(int value) { - bearingBefore = value; - } - - public int getBearingAfter() { - return bearingAfter; - } - - public void setBearingAfter(int value) { - bearingAfter = value; - } + private Coordinate location; + private int bearingBefore = 0; + private int bearingAfter = 0; + + public Coordinate getLocation() { + return location; + } + + public void setLocation(Coordinate location) { + this.location = location; + } + + public int getBearingBefore() { + return bearingBefore; + } + + public void setBearingBefore(int value) { + bearingBefore = value; + } + + public int getBearingAfter() { + return bearingAfter; + } + + public void setBearingAfter(int value) { + bearingAfter = value; + } public boolean isContinue() { - return Math.abs(bearingAfter - bearingBefore) < 6; - } + return Math.abs(bearingAfter - bearingBefore) < 6; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSummary.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSummary.java index 69a7e960d6..5f28e504d1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteSummary.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteSummary.java @@ -1,92 +1,92 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; import com.graphhopper.util.shapes.BBox; public class RouteSummary { - private double distance; - private double duration; - private double ascent; - private double descent; - private double avgSpeed; - private BBox bbox; - - private int transfers; - private int fare; - - public double getDistance() { - return distance; - } - - public void setDistance(double distance) { - this.distance = distance; - } - - public double getDuration() { - return duration; - } - - public void setDuration(double duration) { - this.duration = duration; - } - - public int getTransfers() { - return transfers; - } - - public void setTransfers(int transfers) { - this.transfers = transfers; - } - public int getFare() { - return fare; - } - - public void setFare(int fare) { - this.fare = fare; - } - public BBox getBBox() - { - return bbox; - } - - public void setBBox(BBox bbox) - { - this.bbox = bbox; - } - - public double getAscent() { - return ascent; - } - - public void setAscent(double ascent) { - this.ascent = ascent; - } - - public double getDescent() { - return descent; - } - - public void setDescent(double descent) { - this.descent = descent; - } - - public double getAverageSpeed() { - return avgSpeed; - } - - public void setAverageSpeed(double avgSpeed) { - this.avgSpeed = avgSpeed; - } + private double distance; + private double duration; + private double ascent; + private double descent; + private double avgSpeed; + private BBox bbox; + + private int transfers; + private int fare; + + public double getDistance() { + return distance; + } + + public void setDistance(double distance) { + this.distance = distance; + } + + public double getDuration() { + return duration; + } + + public void setDuration(double duration) { + this.duration = duration; + } + + public int getTransfers() { + return transfers; + } + + public void setTransfers(int transfers) { + this.transfers = transfers; + } + + public int getFare() { + return fare; + } + + public void setFare(int fare) { + this.fare = fare; + } + + public BBox getBBox() { + return bbox; + } + + public void setBBox(BBox bbox) { + this.bbox = bbox; + } + + public double getAscent() { + return ascent; + } + + public void setAscent(double ascent) { + this.ascent = ascent; + } + + public double getDescent() { + return descent; + } + + public void setDescent(double descent) { + this.descent = descent; + } + + public double getAverageSpeed() { + return avgSpeed; + } + + public void setAverageSpeed(double avgSpeed) { + this.avgSpeed = avgSpeed; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RouteWarning.java b/ors-engine/src/main/java/org/heigit/ors/routing/RouteWarning.java index 54d113250f..70580f0e8e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RouteWarning.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RouteWarning.java @@ -29,7 +29,8 @@ public class RouteWarning { /** * Generate the warning object and initialise the contents based on the warning code passed - * @param warning The warning code for the warning that should be generated + * + * @param warning The warning code for the warning that should be generated */ public RouteWarning(int warning, String additionalInfo) { warningCode = warning; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingErrorCodes.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingErrorCodes.java index 9bda3659b3..346b4b8389 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingErrorCodes.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingErrorCodes.java @@ -42,5 +42,7 @@ public class RoutingErrorCodes { public static final int PT_MAX_VISITED_NODES_EXCEEDED = 2017; public static final int UNKNOWN = 2099; - private RoutingErrorCodes() {} + + private RoutingErrorCodes() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfile.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfile.java index 0c29e334f6..1bead758b4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfile.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfile.java @@ -31,11 +31,13 @@ import com.graphhopper.util.shapes.BBox; import com.graphhopper.util.shapes.GHPoint; import com.typesafe.config.Config; -import org.heigit.ors.config.EngineConfig; -import org.heigit.ors.exceptions.*; -import org.locationtech.jts.geom.Coordinate; import org.apache.log4j.Logger; import org.heigit.ors.common.Pair; +import org.heigit.ors.config.EngineConfig; +import org.heigit.ors.exceptions.IncompatibleParameterException; +import org.heigit.ors.exceptions.InternalServerException; +import org.heigit.ors.exceptions.MaxVisitedNodesExceededException; +import org.heigit.ors.exceptions.PointNotFoundException; import org.heigit.ors.export.ExportRequest; import org.heigit.ors.export.ExportResult; import org.heigit.ors.export.ExportWarning; @@ -61,17 +63,14 @@ import org.heigit.ors.util.DebugUtility; import org.heigit.ors.util.StringUtility; import org.heigit.ors.util.TimeUtility; +import org.locationtech.jts.geom.Coordinate; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.LocalDateTime; -import java.time.ZoneId; +import java.time.*; import java.util.*; /** @@ -115,7 +114,7 @@ public class RoutingProfile { private static int profileIdentifier = 0; private final Integer[] mRoutePrefs; private final RouteProfileConfiguration config; - private ORSGraphHopper mGraphHopper; + private final ORSGraphHopper mGraphHopper; private Integer mUseCounter; private String astarApproximation; private Double astarEpsilon; @@ -359,7 +358,7 @@ private static ORSGraphHopperConfig createGHSettings(String sourceFile, RoutePro if (prepareCore) { if (coreOpts.hasPath(KEY_THREADS)) { - String [] threads = coreOpts.getString(KEY_THREADS).split(","); + String[] threads = coreOpts.getString(KEY_THREADS).split(","); int threadsCH = Integer.parseInt(threads[0]); int threadsLM = threads.length > 1 ? Integer.parseInt(threads[1]) : threadsCH; ghConfig.putObject("prepare.core.threads", threadsCH); @@ -419,8 +418,8 @@ private static ORSGraphHopperConfig createGHSettings(String sourceFile, RoutePro ghConfig.putObject("gtfs.file", config.getGtfsFile()); String flagEncoder = vehicle; - if(!Helper.isEmpty(config.getEncoderOptions())) - flagEncoder += "|" + config.getEncoderOptions(); + if (!Helper.isEmpty(config.getEncoderOptions())) + flagEncoder += "|" + config.getEncoderOptions(); ghConfig.putObject("graph.flag_encoders", flagEncoder.toLowerCase()); ghConfig.putObject("index.high_resolution", config.getLocationIndexResolution()); @@ -711,7 +710,7 @@ private MatrixResult computeDijkstraMatrix(MatrixRequest req, GraphHopper gh, Fl return algorithm.compute(mtxSearchCntx.getSources(), mtxSearchCntx.getDestinations(), req.getMetrics()); } - public ExportResult computeExport(ExportRequest req) throws Exception { + public ExportResult computeExport(ExportRequest req) throws Exception { ExportResult res = new ExportResult(); GraphHopper gh = getGraphhopper(); @@ -1020,8 +1019,7 @@ else if (bearings[1] == null) if (searchParams.hasDeparture()) { key = RouteRequestParameterNames.PARAM_DEPARTURE; time = searchParams.getDeparture(); - } - else { + } else { key = RouteRequestParameterNames.PARAM_ARRIVAL; time = searchParams.getArrival(); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileCategory.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileCategory.java index 67f4937744..9fd5160729 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileCategory.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileCategory.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; @@ -17,44 +17,45 @@ import org.heigit.ors.routing.graphhopper.extensions.flagencoders.FlagEncoderNames; public class RoutingProfileCategory { - public static final int UNKNOWN = 0; - public static final int DRIVING = 1; - public static final int CYCLING = 2; - public static final int WALKING = 4; - public static final int WHEELCHAIR = 8; - - public static int getFromRouteProfile(int profileType) { - if (RoutingProfileType.isDriving(profileType)) - return RoutingProfileCategory.DRIVING; - - if (RoutingProfileType.isCycling(profileType)) - return RoutingProfileCategory.CYCLING; - - if (RoutingProfileType.isWalking(profileType)) - return RoutingProfileCategory.WALKING; - - if (RoutingProfileType.WHEELCHAIR == profileType) - return RoutingProfileCategory.WHEELCHAIR; - - return RoutingProfileCategory.UNKNOWN; - } - - public static int getFromEncoder(EncodingManager encodingManager) { - if (encodingManager.hasEncoder(FlagEncoderNames.CAR_ORS) || encodingManager.hasEncoder(FlagEncoderNames.HEAVYVEHICLE)) - return RoutingProfileCategory.DRIVING; - - if (encodingManager.hasEncoder(FlagEncoderNames.BIKE_ORS) || encodingManager.hasEncoder(FlagEncoderNames.MTB_ORS) || encodingManager.hasEncoder(FlagEncoderNames.ROADBIKE_ORS) - || encodingManager.hasEncoder(FlagEncoderNames.BIKE_ELECTRO)) - return RoutingProfileCategory.CYCLING; - - if (encodingManager.hasEncoder(FlagEncoderNames.PEDESTRIAN_ORS) || encodingManager.hasEncoder(FlagEncoderNames.HIKING_ORS)) - return RoutingProfileCategory.WALKING; - - if (encodingManager.hasEncoder(FlagEncoderNames.WHEELCHAIR)) - return RoutingProfileCategory.WHEELCHAIR; - - return RoutingProfileCategory.UNKNOWN; - } - - private RoutingProfileCategory() {} + public static final int UNKNOWN = 0; + public static final int DRIVING = 1; + public static final int CYCLING = 2; + public static final int WALKING = 4; + public static final int WHEELCHAIR = 8; + + public static int getFromRouteProfile(int profileType) { + if (RoutingProfileType.isDriving(profileType)) + return RoutingProfileCategory.DRIVING; + + if (RoutingProfileType.isCycling(profileType)) + return RoutingProfileCategory.CYCLING; + + if (RoutingProfileType.isWalking(profileType)) + return RoutingProfileCategory.WALKING; + + if (RoutingProfileType.WHEELCHAIR == profileType) + return RoutingProfileCategory.WHEELCHAIR; + + return RoutingProfileCategory.UNKNOWN; + } + + public static int getFromEncoder(EncodingManager encodingManager) { + if (encodingManager.hasEncoder(FlagEncoderNames.CAR_ORS) || encodingManager.hasEncoder(FlagEncoderNames.HEAVYVEHICLE)) + return RoutingProfileCategory.DRIVING; + + if (encodingManager.hasEncoder(FlagEncoderNames.BIKE_ORS) || encodingManager.hasEncoder(FlagEncoderNames.MTB_ORS) || encodingManager.hasEncoder(FlagEncoderNames.ROADBIKE_ORS) + || encodingManager.hasEncoder(FlagEncoderNames.BIKE_ELECTRO)) + return RoutingProfileCategory.CYCLING; + + if (encodingManager.hasEncoder(FlagEncoderNames.PEDESTRIAN_ORS) || encodingManager.hasEncoder(FlagEncoderNames.HIKING_ORS)) + return RoutingProfileCategory.WALKING; + + if (encodingManager.hasEncoder(FlagEncoderNames.WHEELCHAIR)) + return RoutingProfileCategory.WHEELCHAIR; + + return RoutingProfileCategory.UNKNOWN; + } + + private RoutingProfileCategory() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoadContext.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoadContext.java index bec8913a31..5fd314d777 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoadContext.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoadContext.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; @@ -20,22 +20,22 @@ * An example of such a shared resource is {@link ElevationProvider}. */ public class RoutingProfileLoadContext { - // add here any other shared resources - private ElevationProvider elevationProvider = null; - - public ElevationProvider getElevationProvider(){ - return elevationProvider; - } + // add here any other shared resources + private ElevationProvider elevationProvider = null; - public void setElevationProvider(ElevationProvider ep) { - if (elevationProvider == null) { - elevationProvider = ep; - } - } + public ElevationProvider getElevationProvider() { + return elevationProvider; + } - public void releaseElevationProviderCacheAfterAllVehicleProfilesHaveBeenProcessed() { - if (elevationProvider != null){ - elevationProvider.release(); - } - } + public void setElevationProvider(ElevationProvider ep) { + if (elevationProvider == null) { + elevationProvider = ep; + } + } + + public void releaseElevationProviderCacheAfterAllVehicleProfilesHaveBeenProcessed() { + if (elevationProvider != null) { + elevationProvider.release(); + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoader.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoader.java index 591000b0e9..db8a17372d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoader.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileLoader.java @@ -14,30 +14,30 @@ package org.heigit.ors.routing; -import java.util.concurrent.Callable; - import org.heigit.ors.config.EngineConfig; import org.heigit.ors.routing.configuration.RouteProfileConfiguration; +import java.util.concurrent.Callable; + /** * Callable creating a {@link RoutingProfile} from an OSM-file, * a {@link RouteProfileConfiguration} and a {@link RoutingProfileLoadContext}. */ public class RoutingProfileLoader implements Callable { - private final EngineConfig engineConfig; - private final RouteProfileConfiguration rpc; - private final RoutingProfileLoadContext loadCntx; - - public RoutingProfileLoader(EngineConfig engineConfig, RouteProfileConfiguration rpc, RoutingProfileLoadContext loadCntx) { - this.engineConfig = engineConfig; - this.rpc = rpc; - this.loadCntx = loadCntx; - - } - - @Override - public RoutingProfile call() throws Exception { - Thread.currentThread().setName("ORS-pl-" + rpc.getName()); - return new RoutingProfile(engineConfig, rpc, loadCntx); - } + private final EngineConfig engineConfig; + private final RouteProfileConfiguration rpc; + private final RoutingProfileLoadContext loadCntx; + + public RoutingProfileLoader(EngineConfig engineConfig, RouteProfileConfiguration rpc, RoutingProfileLoadContext loadCntx) { + this.engineConfig = engineConfig; + this.rpc = rpc; + this.loadCntx = loadCntx; + + } + + @Override + public RoutingProfile call() throws Exception { + Thread.currentThread().setName("ORS-pl-" + rpc.getName()); + return new RoutingProfile(engineConfig, rpc, loadCntx); + } } \ No newline at end of file diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManager.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManager.java index 5646e16db5..598a83268a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManager.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManager.java @@ -88,7 +88,7 @@ public void initialize(EngineConfig config) { } int initializationThreads = config.getInitializationThreads(); LOGGER.info("====> Initializing profiles from '%s' (%d threads) ...".formatted( - config.getSourceFile(), initializationThreads)); + config.getSourceFile(), initializationThreads)); routingProfiles = new RoutingProfilesCollection(); int nRouteInstances = routeProfileConfigurations.length; @@ -180,7 +180,7 @@ public RouteResult[] computeRoundTripRoute(RoutingRequest req) throws Exception if (config.getMaximumDistanceRoundTripRoutes() != 0 && config.getMaximumDistanceRoundTripRoutes() < searchParams.getRoundTripLength()) { throw new ServerLimitExceededException( RoutingErrorCodes.REQUEST_EXCEEDS_SERVER_LIMIT, - "The requested route length must not be greater than %s meters.".formatted(config.getMaximumDistanceRoundTripRoutes()) + "The requested route length must not be greater than %s meters.".formatted(config.getMaximumDistanceRoundTripRoutes()) ); } @@ -201,8 +201,8 @@ public RouteResult[] computeRoundTripRoute(RoutingRequest req) throws Exception if (gr.getErrors().get(0) instanceof com.graphhopper.util.exceptions.ConnectionNotFoundException) { throw new RouteNotFoundException( RoutingErrorCodes.ROUTE_NOT_FOUND, - "Unable to find a route for point (%s).".formatted( - FormatUtility.formatCoordinate(c0)) + "Unable to find a route for point (%s).".formatted( + FormatUtility.formatCoordinate(c0)) ); } else if (gr.getErrors().get(0) instanceof com.graphhopper.util.exceptions.PointNotFoundException) { StringBuilder message = new StringBuilder(); @@ -220,9 +220,9 @@ public RouteResult[] computeRoundTripRoute(RoutingRequest req) throws Exception // has happened, so return that a route could not be found throw new RouteNotFoundException( RoutingErrorCodes.ROUTE_NOT_FOUND, - "Unable to find a route for point (%s).".formatted( - FormatUtility.formatCoordinate(c0) - )); + "Unable to find a route for point (%s).".formatted( + FormatUtility.formatCoordinate(c0) + )); } } @@ -329,35 +329,35 @@ public RouteResult[] computeLinearRoute(RoutingRequest req) throws Exception { } throw new RouteNotFoundException( code, - "Unable to find a route between points %d (%s) and %d (%s). %s".formatted( - i, - FormatUtility.formatCoordinate(c0), - i + 1, - FormatUtility.formatCoordinate(c1), - details.values().stream().map(Object::toString).collect(Collectors.joining(" ")) - ) + "Unable to find a route between points %d (%s) and %d (%s). %s".formatted( + i, + FormatUtility.formatCoordinate(c0), + i + 1, + FormatUtility.formatCoordinate(c1), + details.values().stream().map(Object::toString).collect(Collectors.joining(" ")) + ) ); } throw new RouteNotFoundException( RoutingErrorCodes.ROUTE_NOT_FOUND, - "Unable to find a route between points %d (%s) and %d (%s).".formatted( - i, - FormatUtility.formatCoordinate(c0), - i + 1, - FormatUtility.formatCoordinate(c1) - ) + "Unable to find a route between points %d (%s) and %d (%s).".formatted( + i, + FormatUtility.formatCoordinate(c0), + i + 1, + FormatUtility.formatCoordinate(c1) + ) ); } else if (gr.getErrors().get(0) instanceof com.graphhopper.util.exceptions.MaximumNodesExceededException) { Map details = ((MaximumNodesExceededException) gr.getErrors().get(0)).getDetails(); throw new RouteNotFoundException( RoutingErrorCodes.PT_MAX_VISITED_NODES_EXCEEDED, - "Unable to find a route between points %d (%s) and %d (%s). Maximum number of nodes exceeded: %s".formatted( - i, - FormatUtility.formatCoordinate(c0), - i + 1, - FormatUtility.formatCoordinate(c1), - details.get(MaximumNodesExceededException.NODES_KEY).toString() - ) + "Unable to find a route between points %d (%s) and %d (%s). Maximum number of nodes exceeded: %s".formatted( + i, + FormatUtility.formatCoordinate(c0), + i + 1, + FormatUtility.formatCoordinate(c1), + details.get(MaximumNodesExceededException.NODES_KEY).toString() + ) ); } else if (gr.getErrors().get(0) instanceof com.graphhopper.util.exceptions.PointNotFoundException) { StringBuilder message = new StringBuilder(); @@ -375,14 +375,14 @@ public RouteResult[] computeLinearRoute(RoutingRequest req) throws Exception { if (pointRadius == -1) { pointRadius = routingProfiles.getRouteProfile(profileType).getConfiguration().getMaximumSnappingRadius(); message.append("Could not find routable point within the maximum possible radius of %.1f meters of specified coordinate %d: %s.".formatted( - pointRadius, - pointReference, - FormatUtility.formatCoordinate(pointCoordinate))); + pointRadius, + pointReference, + FormatUtility.formatCoordinate(pointCoordinate))); } else { message.append("Could not find routable point within a radius of %.1f meters of specified coordinate %d: %s.".formatted( - pointRadius, - pointReference, - FormatUtility.formatCoordinate(pointCoordinate))); + pointRadius, + pointReference, + FormatUtility.formatCoordinate(pointCoordinate))); } } else { @@ -398,11 +398,11 @@ public RouteResult[] computeLinearRoute(RoutingRequest req) throws Exception { // has happened, so return that a route could not be found throw new RouteNotFoundException( RoutingErrorCodes.ROUTE_NOT_FOUND, - "Unable to find a route between points %d (%s) and %d (%s).".formatted( - i, - FormatUtility.formatCoordinate(c0), - i + 1, - FormatUtility.formatCoordinate(c1)) + "Unable to find a route between points %d (%s) and %d (%s).".formatted( + i, + FormatUtility.formatCoordinate(c0), + i + 1, + FormatUtility.formatCoordinate(c1)) ); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManagerStatus.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManagerStatus.java index 93962faf62..644751f7c2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManagerStatus.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileManagerStatus.java @@ -1,28 +1,29 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; public class RoutingProfileManagerStatus { - private static boolean ready = false; + private static boolean ready = false; - private RoutingProfileManagerStatus() {} + private RoutingProfileManagerStatus() { + } - public static boolean isReady() { - return ready; - } - - public static void setReady(boolean ready) { - RoutingProfileManagerStatus.ready = ready; - } + public static boolean isReady() { + return ready; + } + + public static void setReady(boolean ready) { + RoutingProfileManagerStatus.ready = ready; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileType.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileType.java index ff4bec5cf1..5b6cac2288 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileType.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfileType.java @@ -56,32 +56,33 @@ public class RoutingProfileType { public static final int GH_FOOT = 46; public static final int GH_HIKE = 47; - private RoutingProfileType() {} + private RoutingProfileType() { + } public static boolean isDriving(int routePref) { return routePref == DRIVING_CAR - || routePref == DRIVING_HGV - || routePref == DRIVING_ELECTRIC_CAR - || routePref == DRIVING_EMERGENCY - || routePref == DRIVING_MOTORCYCLE - || routePref == DRIVING_CAROFFROAD - || routePref == DRIVING_TRAFFIC - || routePref == GH_CAR - || routePref == GH_CAR4WD; + || routePref == DRIVING_HGV + || routePref == DRIVING_ELECTRIC_CAR + || routePref == DRIVING_EMERGENCY + || routePref == DRIVING_MOTORCYCLE + || routePref == DRIVING_CAROFFROAD + || routePref == DRIVING_TRAFFIC + || routePref == GH_CAR + || routePref == GH_CAR4WD; } public static boolean isHeavyVehicle(int routePref) { return routePref == DRIVING_HGV - || routePref == DRIVING_CAROFFROAD - || routePref == DRIVING_EMERGENCY; + || routePref == DRIVING_CAROFFROAD + || routePref == DRIVING_EMERGENCY; } public static boolean isWalking(int routePref) { return routePref == FOOT_WALKING - || routePref == FOOT_HIKING - || routePref == FOOT_JOGGING - || routePref == GH_FOOT - || routePref == GH_HIKE; + || routePref == FOOT_HIKING + || routePref == FOOT_JOGGING + || routePref == GH_FOOT + || routePref == GH_HIKE; } public static boolean isPedestrian(int routePref) { @@ -94,13 +95,13 @@ public static boolean isWheelchair(int routePref) { public static boolean isCycling(int routePref) { return routePref == CYCLING_REGULAR - || routePref == CYCLING_MOUNTAIN - || routePref == CYCLING_ROAD - || routePref == CYCLING_ELECTRIC - || routePref == GH_BIKE - || routePref == GH_BIKE2 - || routePref == GH_BIKE_MTB - || routePref == GH_BIKE_ROAD; + || routePref == CYCLING_MOUNTAIN + || routePref == CYCLING_ROAD + || routePref == CYCLING_ELECTRIC + || routePref == GH_BIKE + || routePref == GH_BIKE2 + || routePref == GH_BIKE_MTB + || routePref == GH_BIKE_ROAD; } public static boolean supportMessages(int profileType) { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfilesCollection.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfilesCollection.java index f90229e83d..edd314b6cb 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfilesCollection.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingProfilesCollection.java @@ -1,161 +1,159 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; +import org.apache.log4j.Logger; +import org.heigit.ors.util.RuntimeUtility; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.apache.log4j.Logger; - -import org.heigit.ors.util.RuntimeUtility; - public class RoutingProfilesCollection { - private final HashMap routeProfiles; - private final ArrayList uniqueProfiles; - - public RoutingProfilesCollection() { - routeProfiles = new HashMap<>(); - uniqueProfiles = new ArrayList<>(); - } - - public void destroy() { - for (RoutingProfile rp : uniqueProfiles) { - rp.close(); - } - routeProfiles.clear(); - } - - public List getUniqueProfiles() { - return uniqueProfiles; - } - - public int size() - { - return uniqueProfiles.size(); - } - - public void clear() { - routeProfiles.clear(); - uniqueProfiles.clear(); - } - - public boolean add(RoutingProfile rp ) { - boolean result = true; - synchronized (uniqueProfiles) { - uniqueProfiles.add(rp); - Integer[] routePrefs = rp.getPreferences(); - if (routePrefs != null) { - for (int j = 0; j < routePrefs.length; j++) { - if (!add(routePrefs[j], rp, false)) - result = false; - } - } - } - return result; - } - - public boolean add(int routePref, RoutingProfile rp, boolean isUnique) { - boolean res = false; - - synchronized (routeProfiles) { - int key = getRoutePreferenceKey(routePref, rp.isCHEnabled()); - - if (!routeProfiles.containsKey(key)) { - routeProfiles.put(key, rp); - if (isUnique) - uniqueProfiles.add(rp); - - res = true; - } - - if (rp.isCHEnabled()) { - // add the same profile but with dynamic weights - key = getRoutePreferenceKey(routePref, false); - - if (!routeProfiles.containsKey(key)) { - routeProfiles.put(key, rp); - if (isUnique) - uniqueProfiles.add(rp); - - res = true; - } - } - } - - return res; - } - - public List getCarProfiles() { - ArrayList result = new ArrayList<>(); - for (RoutingProfile rp : routeProfiles.values()) { - if (rp.hasCarPreferences()) - result.add(rp); - } - return result; - } - - public RoutingProfile getRouteProfile(int routePref, boolean chEnabled) { - int routePrefKey = getRoutePreferenceKey(routePref, chEnabled); - //Fall back to non-CH version if CH routing profile does not exist - if (!routeProfiles.containsKey(routePrefKey)){ - routePrefKey = getRoutePreferenceKey(routePref, false); - if (!routeProfiles.containsKey(routePrefKey)) - return null; - } - return routeProfiles.get(routePrefKey); - } - - /** - * Check if the CH graph of the specified profile has been built. - * - * @param routePref The chosen routing profile - */ - - public boolean isCHProfileAvailable(int routePref) { - int routePrefKey = getRoutePreferenceKey(routePref, true); - return routeProfiles.containsKey(routePrefKey); - } - - public RoutingProfile getRouteProfile(int routePref) { - return getRouteProfileByKey(getRoutePreferenceKey(routePref, false)); - } - - private RoutingProfile getRouteProfileByKey(int routePrefKey) { - return routeProfiles.getOrDefault(routePrefKey, null); - } - - private int getRoutePreferenceKey(int routePref, boolean chEnabled) { - int key = routePref; - if (chEnabled) - key += 100; - return key; - } - - public void printStatistics(Logger logger) { - logger.info("====> Memory usage by profiles:"); - long totalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); - long totalProfilesMemory = 0; - - int i = 0; - for(RoutingProfile profile : getUniqueProfiles()) { - i++; - long profileMemory = profile.getMemoryUsage(); - totalProfilesMemory += profileMemory; - logger.info("[%d] %s (%.1f%%)".formatted(i, RuntimeUtility.getMemorySize(profileMemory), ((double) profileMemory / totalUsedMemory) * 100)); - } - logger.info("Total: %s (%.1f%%)".formatted(RuntimeUtility.getMemorySize(totalProfilesMemory), ((double) totalProfilesMemory / totalUsedMemory) * 100)); - logger.info("========================================================================"); - } + private final HashMap routeProfiles; + private final ArrayList uniqueProfiles; + + public RoutingProfilesCollection() { + routeProfiles = new HashMap<>(); + uniqueProfiles = new ArrayList<>(); + } + + public void destroy() { + for (RoutingProfile rp : uniqueProfiles) { + rp.close(); + } + routeProfiles.clear(); + } + + public List getUniqueProfiles() { + return uniqueProfiles; + } + + public int size() { + return uniqueProfiles.size(); + } + + public void clear() { + routeProfiles.clear(); + uniqueProfiles.clear(); + } + + public boolean add(RoutingProfile rp) { + boolean result = true; + synchronized (uniqueProfiles) { + uniqueProfiles.add(rp); + Integer[] routePrefs = rp.getPreferences(); + if (routePrefs != null) { + for (int j = 0; j < routePrefs.length; j++) { + if (!add(routePrefs[j], rp, false)) + result = false; + } + } + } + return result; + } + + public boolean add(int routePref, RoutingProfile rp, boolean isUnique) { + boolean res = false; + + synchronized (routeProfiles) { + int key = getRoutePreferenceKey(routePref, rp.isCHEnabled()); + + if (!routeProfiles.containsKey(key)) { + routeProfiles.put(key, rp); + if (isUnique) + uniqueProfiles.add(rp); + + res = true; + } + + if (rp.isCHEnabled()) { + // add the same profile but with dynamic weights + key = getRoutePreferenceKey(routePref, false); + + if (!routeProfiles.containsKey(key)) { + routeProfiles.put(key, rp); + if (isUnique) + uniqueProfiles.add(rp); + + res = true; + } + } + } + + return res; + } + + public List getCarProfiles() { + ArrayList result = new ArrayList<>(); + for (RoutingProfile rp : routeProfiles.values()) { + if (rp.hasCarPreferences()) + result.add(rp); + } + return result; + } + + public RoutingProfile getRouteProfile(int routePref, boolean chEnabled) { + int routePrefKey = getRoutePreferenceKey(routePref, chEnabled); + //Fall back to non-CH version if CH routing profile does not exist + if (!routeProfiles.containsKey(routePrefKey)) { + routePrefKey = getRoutePreferenceKey(routePref, false); + if (!routeProfiles.containsKey(routePrefKey)) + return null; + } + return routeProfiles.get(routePrefKey); + } + + /** + * Check if the CH graph of the specified profile has been built. + * + * @param routePref The chosen routing profile + */ + + public boolean isCHProfileAvailable(int routePref) { + int routePrefKey = getRoutePreferenceKey(routePref, true); + return routeProfiles.containsKey(routePrefKey); + } + + public RoutingProfile getRouteProfile(int routePref) { + return getRouteProfileByKey(getRoutePreferenceKey(routePref, false)); + } + + private RoutingProfile getRouteProfileByKey(int routePrefKey) { + return routeProfiles.getOrDefault(routePrefKey, null); + } + + private int getRoutePreferenceKey(int routePref, boolean chEnabled) { + int key = routePref; + if (chEnabled) + key += 100; + return key; + } + + public void printStatistics(Logger logger) { + logger.info("====> Memory usage by profiles:"); + long totalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); + long totalProfilesMemory = 0; + + int i = 0; + for (RoutingProfile profile : getUniqueProfiles()) { + i++; + long profileMemory = profile.getMemoryUsage(); + totalProfilesMemory += profileMemory; + logger.info("[%d] %s (%.1f%%)".formatted(i, RuntimeUtility.getMemorySize(profileMemory), ((double) profileMemory / totalUsedMemory) * 100)); + } + logger.info("Total: %s (%.1f%%)".formatted(RuntimeUtility.getMemorySize(totalProfilesMemory), ((double) totalProfilesMemory / totalUsedMemory) * 100)); + logger.info("========================================================================"); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingRequest.java b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingRequest.java index 0f830c4a1d..8e06a71fff 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/RoutingRequest.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/RoutingRequest.java @@ -1,23 +1,22 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing; import com.graphhopper.util.Helper; -import org.locationtech.jts.geom.Coordinate; - import org.heigit.ors.common.DistanceUnit; import org.heigit.ors.common.ServiceRequest; +import org.locationtech.jts.geom.Coordinate; import java.time.Duration; import java.util.ArrayList; @@ -27,237 +26,239 @@ public class RoutingRequest extends ServiceRequest { public static final String ATTR_DETOURFACTOR = "detourfactor"; private Coordinate[] coordinates; - private RouteSearchParameters searchParameters; - private DistanceUnit units = DistanceUnit.METERS; - private String language = "en"; - private String geometryFormat = "encodedpolyline"; - private boolean geometrySimplify = false; - private RouteInstructionsFormat instructionsFormat = RouteInstructionsFormat.TEXT; - private boolean includeInstructions = true; - private boolean includeElevation = false; - private boolean includeGeometry = true; - private boolean includeManeuvers = false; + private RouteSearchParameters searchParameters; + private DistanceUnit units = DistanceUnit.METERS; + private String language = "en"; + private String geometryFormat = "encodedpolyline"; + private boolean geometrySimplify = false; + private RouteInstructionsFormat instructionsFormat = RouteInstructionsFormat.TEXT; + private boolean includeInstructions = true; + private boolean includeElevation = false; + private boolean includeGeometry = true; + private boolean includeManeuvers = false; private boolean includeRoundaboutExits = false; - private String[] attributes = null; + private String[] attributes = null; private int extraInfo; private int locationIndex = -1; private boolean continueStraight = false; - private List skipSegments = new ArrayList<>(); - private boolean includeCountryInfo = false; - private double maximumSpeed; - - private String responseFormat = "json"; - // Fields specific to GraphHopper GTFS - private boolean schedule; - private Duration walkingTime; - private int scheduleRows; - private boolean ignoreTransfers; - private Duration scheduleDuration; - - public RoutingRequest() - { - searchParameters = new RouteSearchParameters(); - } - - public Coordinate[] getCoordinates() { - return coordinates; - } - - public Coordinate getDestination() - { - return coordinates[coordinates.length - 1]; - } - - public void setCoordinates(Coordinate[] coordinates) { - this.coordinates = coordinates; - } - - public RouteSearchParameters getSearchParameters() { - return searchParameters; - } - - public void setSearchParameters(RouteSearchParameters searchParameters) { - this.searchParameters = searchParameters; - } - - public boolean getIncludeInstructions() { - return includeInstructions; - } - - public void setIncludeInstructions(boolean includeInstructions) { - this.includeInstructions = includeInstructions; - } - - public DistanceUnit getUnits() { - return units; - } - - public void setUnits(DistanceUnit units) { - this.units = units; - } - - public String getGeometryFormat() { - return geometryFormat; - } - - public void setGeometryFormat(String geometryFormat) { - this.geometryFormat = geometryFormat; - } - - public boolean getGeometrySimplify() { return geometrySimplify; } - - public void setGeometrySimplify(boolean geometrySimplify) { this.geometrySimplify = geometrySimplify; } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public RouteInstructionsFormat getInstructionsFormat() { - return instructionsFormat; - } - - public void setInstructionsFormat(RouteInstructionsFormat format) { - instructionsFormat = format; - } - - public int getExtraInfo() { - return extraInfo; - } - - public void setExtraInfo(int extraInfo) { - this.extraInfo = extraInfo; - } - - public boolean getIncludeElevation() { - return includeElevation; - } - - public void setIncludeElevation(boolean includeElevation) { - this.includeElevation = includeElevation; - } - - public boolean getIncludeGeometry() { - return includeGeometry; - } - - public void setIncludeGeometry(boolean includeGeometry) { - this.includeGeometry = includeGeometry; - } - - public String[] getAttributes() { - return attributes; - } - - public void setAttributes(String[] attributes) { - this.attributes = attributes; - } - - public boolean hasAttribute(String attr) { - if (attributes == null || attr == null) - return false; - - for (String attribute : attributes) - if (attr.equalsIgnoreCase(attribute)) - return true; - - return false; - } + private List skipSegments = new ArrayList<>(); + private boolean includeCountryInfo = false; + private double maximumSpeed; + + private String responseFormat = "json"; + // Fields specific to GraphHopper GTFS + private boolean schedule; + private Duration walkingTime; + private int scheduleRows; + private boolean ignoreTransfers; + private Duration scheduleDuration; + + public RoutingRequest() { + searchParameters = new RouteSearchParameters(); + } + + public Coordinate[] getCoordinates() { + return coordinates; + } + + public Coordinate getDestination() { + return coordinates[coordinates.length - 1]; + } + + public void setCoordinates(Coordinate[] coordinates) { + this.coordinates = coordinates; + } + + public RouteSearchParameters getSearchParameters() { + return searchParameters; + } + + public void setSearchParameters(RouteSearchParameters searchParameters) { + this.searchParameters = searchParameters; + } + + public boolean getIncludeInstructions() { + return includeInstructions; + } + + public void setIncludeInstructions(boolean includeInstructions) { + this.includeInstructions = includeInstructions; + } + + public DistanceUnit getUnits() { + return units; + } + + public void setUnits(DistanceUnit units) { + this.units = units; + } + + public String getGeometryFormat() { + return geometryFormat; + } + + public void setGeometryFormat(String geometryFormat) { + this.geometryFormat = geometryFormat; + } + + public boolean getGeometrySimplify() { + return geometrySimplify; + } + + public void setGeometrySimplify(boolean geometrySimplify) { + this.geometrySimplify = geometrySimplify; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public RouteInstructionsFormat getInstructionsFormat() { + return instructionsFormat; + } + + public void setInstructionsFormat(RouteInstructionsFormat format) { + instructionsFormat = format; + } + + public int getExtraInfo() { + return extraInfo; + } + + public void setExtraInfo(int extraInfo) { + this.extraInfo = extraInfo; + } + + public boolean getIncludeElevation() { + return includeElevation; + } + + public void setIncludeElevation(boolean includeElevation) { + this.includeElevation = includeElevation; + } + + public boolean getIncludeGeometry() { + return includeGeometry; + } + + public void setIncludeGeometry(boolean includeGeometry) { + this.includeGeometry = includeGeometry; + } + + public String[] getAttributes() { + return attributes; + } + + public void setAttributes(String[] attributes) { + this.attributes = attributes; + } + + public boolean hasAttribute(String attr) { + if (attributes == null || attr == null) + return false; + + for (String attribute : attributes) + if (attr.equalsIgnoreCase(attribute)) + return true; + + return false; + } + + public int getLocationIndex() { + return locationIndex; + } + + public void setLocationIndex(int locationIndex) { + this.locationIndex = locationIndex; + } + + public boolean getIncludeManeuvers() { + return includeManeuvers; + } + + public void setIncludeManeuvers(boolean includeManeuvers) { + this.includeManeuvers = includeManeuvers; + } + + public boolean getContinueStraight() { + return continueStraight; + } + + public void setContinueStraight(boolean continueStraight) { + this.continueStraight = continueStraight; + } - public int getLocationIndex() { - return locationIndex; - } + public boolean getIncludeRoundaboutExits() { + return includeRoundaboutExits; + } - public void setLocationIndex(int locationIndex) { - this.locationIndex = locationIndex; - } + public void setIncludeRoundaboutExits(boolean includeRoundaboutExits) { + this.includeRoundaboutExits = includeRoundaboutExits; + } - public boolean getIncludeManeuvers() { - return includeManeuvers; - } + public boolean isValid() { + return coordinates != null; + } - public void setIncludeManeuvers(boolean includeManeuvers) { - this.includeManeuvers = includeManeuvers; - } + public List getSkipSegments() { + return skipSegments; + } - public boolean getContinueStraight() { - return continueStraight; - } + public void setSkipSegments(List skipSegments) { + this.skipSegments = skipSegments; + } - public void setContinueStraight(boolean continueStraight) { - this.continueStraight = continueStraight; - } + public boolean getIncludeCountryInfo() { + return includeCountryInfo; + } - public boolean getIncludeRoundaboutExits() { - return includeRoundaboutExits; - } + public void setIncludeCountryInfo(boolean includeCountryInfo) { + this.includeCountryInfo = includeCountryInfo; + } - public void setIncludeRoundaboutExits(boolean includeRoundaboutExits) { - this.includeRoundaboutExits = includeRoundaboutExits; - } + public void setMaximumSpeed(double maximumSpeed) { + this.maximumSpeed = maximumSpeed; + } - public boolean isValid() { - return coordinates != null; - } + public double getMaximumSpeed() { + return maximumSpeed; + } - public List getSkipSegments() { - return skipSegments; - } - - public void setSkipSegments(List skipSegments) { - this.skipSegments = skipSegments; - } - - public boolean getIncludeCountryInfo() { - return includeCountryInfo; - } - - public void setIncludeCountryInfo(boolean includeCountryInfo) { - this.includeCountryInfo = includeCountryInfo; - } - - public void setMaximumSpeed(double maximumSpeed){ - this.maximumSpeed = maximumSpeed; - } - - public double getMaximumSpeed(){ - return maximumSpeed; - } - - public void setResponseFormat(String responseFormat) { - if (!Helper.isEmpty(responseFormat)) { - this.responseFormat = responseFormat; - } - } - - public String getResponseFormat() { - return this.responseFormat; - } - - public boolean isRoundTripRequest() { - return this.coordinates.length == 1 && this.searchParameters.getRoundTripLength() > 0; - } - - public void setSchedule(boolean schedule) { - this.schedule = schedule; - } - - public void setWalkingTime(Duration walkingTime) { - this.walkingTime = walkingTime; - } - - public void setScheduleRows(int scheduleRows) { - this.scheduleRows = scheduleRows; - } - - public void setIgnoreTransfers(boolean ignoreTransfers) { - this.ignoreTransfers = ignoreTransfers; - } - - public void setScheduleDuaration(Duration scheduleDuration) { - this.scheduleDuration = scheduleDuration; - } + public void setResponseFormat(String responseFormat) { + if (!Helper.isEmpty(responseFormat)) { + this.responseFormat = responseFormat; + } + } + + public String getResponseFormat() { + return this.responseFormat; + } + + public boolean isRoundTripRequest() { + return this.coordinates.length == 1 && this.searchParameters.getRoundTripLength() > 0; + } + + public void setSchedule(boolean schedule) { + this.schedule = schedule; + } + + public void setWalkingTime(Duration walkingTime) { + this.walkingTime = walkingTime; + } + + public void setScheduleRows(int scheduleRows) { + this.scheduleRows = scheduleRows; + } + + public void setIgnoreTransfers(boolean ignoreTransfers) { + this.ignoreTransfers = ignoreTransfers; + } + + public void setScheduleDuaration(Duration scheduleDuration) { + this.scheduleDuration = scheduleDuration; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/WeightingMethod.java b/ors-engine/src/main/java/org/heigit/ors/routing/WeightingMethod.java index 8c1e1dfffd..57fa0e54f1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/WeightingMethod.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/WeightingMethod.java @@ -14,30 +14,31 @@ package org.heigit.ors.routing; public class WeightingMethod { - public static final int UNKNOWN = 0; - public static final int FASTEST = 1; - public static final int SHORTEST = 2; - public static final int RECOMMENDED = 3; + public static final int UNKNOWN = 0; + public static final int FASTEST = 1; + public static final int SHORTEST = 2; + public static final int RECOMMENDED = 3; - private WeightingMethod() {} + private WeightingMethod() { + } - public static int getFromString(String method) { - if ("fastest".equalsIgnoreCase(method)) { - return WeightingMethod.FASTEST; - } else if ("shortest".equalsIgnoreCase(method)) { - return WeightingMethod.SHORTEST; - } else if ("recommended".equalsIgnoreCase(method)) { - return WeightingMethod.RECOMMENDED; - } - return WeightingMethod.UNKNOWN; - } + public static int getFromString(String method) { + if ("fastest".equalsIgnoreCase(method)) { + return WeightingMethod.FASTEST; + } else if ("shortest".equalsIgnoreCase(method)) { + return WeightingMethod.SHORTEST; + } else if ("recommended".equalsIgnoreCase(method)) { + return WeightingMethod.RECOMMENDED; + } + return WeightingMethod.UNKNOWN; + } - public static String getName(int profileType) { - return switch (profileType) { - case FASTEST -> "fastest"; - case SHORTEST -> "shortest"; - case RECOMMENDED -> "recommended"; - default -> ""; - }; - } + public static String getName(int profileType) { + return switch (profileType) { + case FASTEST -> "fastest"; + case SHORTEST -> "shortest"; + case RECOMMENDED -> "recommended"; + default -> ""; + }; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractManyToManyRoutingAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractManyToManyRoutingAlgorithm.java index 4abd3df4bf..cb437c575e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractManyToManyRoutingAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractManyToManyRoutingAlgorithm.java @@ -55,7 +55,7 @@ public AbstractManyToManyRoutingAlgorithm setEdgeFilter(CHEdgeFilter additionalE this.additionalEdgeFilter = additionalEdgeFilter; return this; } - + protected boolean accept(RoutingCHEdgeIterator iter, int prevOrNextEdgeId, boolean reverse) { if (hasInfiniteUTurnCost) { if (iter.getEdge() == prevOrNextEdgeId) @@ -69,14 +69,14 @@ protected boolean accept(RoutingCHEdgeIterator iter, int prevOrNextEdgeId, boole /** * Get the incoming edge for iter. This is the last edge of the iter coming into the next edge. * This algorithm only uses forwards searches, therefore its always last edge, never first edge. + * * @param iter The iterator whose edge is incoming * @return the incoming edge */ protected int getIncEdge(RoutingCHEdgeIteratorState iter, boolean reverse) { if (iter.isShortcut()) { return reverse ? iter.getSkippedEdge1() : iter.getSkippedEdge2(); - } - else { + } else { return iter.getOrigEdge(); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractOneToManyRoutingAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractOneToManyRoutingAlgorithm.java index 87aabc186a..1d45b0a2de 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractOneToManyRoutingAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/AbstractOneToManyRoutingAlgorithm.java @@ -1,18 +1,19 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.algorithms; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.util.AccessFilter; import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.routing.util.FlagEncoder; @@ -20,7 +21,6 @@ import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; import com.graphhopper.storage.NodeAccess; -import com.graphhopper.routing.SPTEntry; import com.graphhopper.util.EdgeExplorer; import com.graphhopper.util.EdgeIterator; import org.heigit.ors.exceptions.MaxVisitedNodesExceededException; @@ -50,7 +50,7 @@ public AbstractOneToManyRoutingAlgorithm(Graph graph, Weighting weighting, Trave outEdgeExplorer = graph.createEdgeExplorer(AccessFilter.outEdges(flagEncoder.getAccessEnc())); inEdgeExplorer = graph.createEdgeExplorer(AccessFilter.inEdges(flagEncoder.getAccessEnc())); } - + @Override public void setMaxVisitedNodes(int numberOfNodes) { this.maxVisitedNodes = numberOfNodes; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraCostCondition.java b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraCostCondition.java index f206f10820..d0446a458a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraCostCondition.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraCostCondition.java @@ -1,30 +1,29 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.algorithms; import com.carrotsearch.hppc.IntObjectMap; import com.graphhopper.routing.Dijkstra; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; -import com.graphhopper.routing.SPTEntry; -public class DijkstraCostCondition extends Dijkstra -{ - private double weightLimit = -1; - public DijkstraCostCondition(Graph g, Weighting weighting, double maxCost, boolean reverseDirection, TraversalMode tMode) - { +public class DijkstraCostCondition extends Dijkstra { + private double weightLimit = -1; + + public DijkstraCostCondition(Graph g, Weighting weighting, double maxCost, boolean reverseDirection, TraversalMode tMode) { super(g, weighting, tMode); initCollections(1000); this.weightLimit = maxCost; @@ -33,25 +32,22 @@ public DijkstraCostCondition(Graph g, Weighting weighting, double maxCost, boole @Override protected boolean finished() { - return super.finished() || currEdge.weight > weightLimit; + return super.finished() || currEdge.weight > weightLimit; } - - public IntObjectMap getMap() - { - return fromMap; + + public IntObjectMap getMap() { + return fromMap; } - - public SPTEntry getCurrentEdge() - { - if (currEdge == null || !finished()) - return null; - else - return currEdge; + + public SPTEntry getCurrentEdge() { + if (currEdge == null || !finished()) + return null; + else + return currEdge; } @Override - public String getName() - { + public String getName() { return "dijkstracc"; } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraOneToManyAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraOneToManyAlgorithm.java index 780d6c0970..3d52081a1c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraOneToManyAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/DijkstraOneToManyAlgorithm.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.algorithms; @@ -30,7 +30,7 @@ public class DijkstraOneToManyAlgorithm extends AbstractOneToManyRoutingAlgorith protected PriorityQueue fromHeap; protected SPTEntry currEdge; private int visitedNodes; - + private int targetsFound = 0; private IntObjectMap targets; private int targetsCount = 0; @@ -46,59 +46,52 @@ protected void initCollections(int size) { fromMap = new GHIntObjectHashMap<>(size); targets = new GHIntObjectHashMap<>(); } - - public void reset() - { - fromHeap.clear(); - fromMap.clear(); - targetsFound = 0; + + public void reset() { + fromHeap.clear(); + fromMap.clear(); + targetsFound = 0; } - - public int getFoundTargets() - { - return targetsFound; + + public int getFoundTargets() { + return targetsFound; } - - public int getTargetsCount() - { - return targetsCount; + + public int getTargetsCount() { + return targetsCount; } - - public void prepare(int[] from, int[] to) - { - this.targets.clear(); - - for (int i = 0; i < to.length; ++i) - { - int nodeId = to[i]; - if (nodeId >= 0) - this.targets.put(nodeId, new SPTEntry(EdgeIterator.NO_EDGE, nodeId, 1)); - } + + public void prepare(int[] from, int[] to) { + this.targets.clear(); + + for (int i = 0; i < to.length; ++i) { + int nodeId = to[i]; + if (nodeId >= 0) + this.targets.put(nodeId, new SPTEntry(EdgeIterator.NO_EDGE, nodeId, 1)); + } } - + @Override public SPTEntry[] calcPaths(int from, int[] to) { - targetsCount = targets.containsKey(from) ? targets.size() - 1 : targets.size(); - - if (targetsCount > 0) - { - currEdge = createSPTEntry(from, 0); - if (!traversalMode.isEdgeBased()) { - fromMap.put(from, currEdge); - } - - runAlgo(); - } - - SPTEntry[] res = new SPTEntry[to.length]; - - for (int i = 0; i < to.length; i++) - { - int nodeId = to[i]; - if (nodeId >= 0) - res[i] = fromMap.get(to[i]); - } - + targetsCount = targets.containsKey(from) ? targets.size() - 1 : targets.size(); + + if (targetsCount > 0) { + currEdge = createSPTEntry(from, 0); + if (!traversalMode.isEdgeBased()) { + fromMap.put(from, currEdge); + } + + runAlgo(); + } + + SPTEntry[] res = new SPTEntry[to.length]; + + for (int i = 0; i < to.length; i++) { + int nodeId = to[i]; + if (nodeId >= 0) + res[i] = fromMap.get(to[i]); + } + return res; } @@ -145,23 +138,21 @@ protected void runAlgo() { } private boolean finished() { - if (currEdge.edge != -1) - { - SPTEntry entry = targets.get(currEdge.adjNode); - if (entry != null) - { - entry.adjNode = currEdge.adjNode; - entry.weight = currEdge.weight; - entry.edge = currEdge.edge; - entry.parent = currEdge.parent; + if (currEdge.edge != -1) { + SPTEntry entry = targets.get(currEdge.adjNode); + if (entry != null) { + entry.adjNode = currEdge.adjNode; + entry.weight = currEdge.weight; + entry.edge = currEdge.edge; + entry.parent = currEdge.parent; entry.originalEdge = currEdge.originalEdge; - targetsFound++; - } - } - - return targetsFound == targetsCount; + targetsFound++; + } + } + + return targetsFound == targetsCount; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/ManyToManyRoutingAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/ManyToManyRoutingAlgorithm.java index 9bcfb0ca3f..ef776bbb59 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/ManyToManyRoutingAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/ManyToManyRoutingAlgorithm.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.algorithms; @@ -17,24 +17,24 @@ public interface ManyToManyRoutingAlgorithm { - void prepare(int[] from, int[] to); + void prepare(int[] from, int[] to); - MultiTreeSPEntry[] calcPaths(int[] from, int[] to); + MultiTreeSPEntry[] calcPaths(int[] from, int[] to); - void reset(); + void reset(); - /** - * Limit the search to numberOfNodes. See #681 - */ - void setMaxVisitedNodes(int numberOfNodes); + /** + * Limit the search to numberOfNodes. See #681 + */ + void setMaxVisitedNodes(int numberOfNodes); - /** - * @return name of this algorithm - */ - String getName(); + /** + * @return name of this algorithm + */ + String getName(); - /** - * Returns the visited nodes after searching. Useful for debugging. - */ - int getVisitedNodes(); + /** + * Returns the visited nodes after searching. Useful for debugging. + */ + int getVisitedNodes(); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/OneToManyRoutingAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/OneToManyRoutingAlgorithm.java index 1b1f056945..9e461f0726 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/OneToManyRoutingAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/OneToManyRoutingAlgorithm.java @@ -1,26 +1,26 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.algorithms; import com.graphhopper.routing.SPTEntry; public interface OneToManyRoutingAlgorithm { - + void prepare(int[] from, int[] to); - + SPTEntry[] calcPaths(int from, int[] to); - + void reset(); /** diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/TDDijkstraCostCondition.java b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/TDDijkstraCostCondition.java index 3f61f78655..48eb23bdc0 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/TDDijkstraCostCondition.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/algorithms/TDDijkstraCostCondition.java @@ -14,11 +14,11 @@ package org.heigit.ors.routing.algorithms; import com.carrotsearch.hppc.IntObjectMap; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.TDDijkstra; import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; -import com.graphhopper.routing.SPTEntry; public class TDDijkstraCostCondition extends TDDijkstra { private double weightLimit = -1; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RouteProfileConfiguration.java b/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RouteProfileConfiguration.java index f612b552fa..75a9d7cd53 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RouteProfileConfiguration.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RouteProfileConfiguration.java @@ -13,45 +13,44 @@ */ package org.heigit.ors.routing.configuration; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; - import com.typesafe.config.Config; +import org.heigit.ors.routing.RoutingProfileType; import org.locationtech.jts.geom.Envelope; -import org.heigit.ors.routing.RoutingProfileType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; public class RouteProfileConfiguration { - private String name = ""; - private boolean enabled = true; - private String profiles = ""; // comma separated - private String graphPath; - private Map> extStorages; - private Map> graphBuilders; - private Double maximumDistance = 0.0; - private Double maximumDistanceDynamicWeights = 0.0; - private Double maximumDistanceAvoidAreas = 0.0; - private Double maximumDistanceAlternativeRoutes = 0.0; - private Double maximumDistanceRoundTripRoutes = 0.0; - private Integer maximumWayPoints = 0; - private boolean instructions = true; - private boolean optimize = false; - - private int encoderFlagsSize = 4; - private String encoderOptions = ""; - private String gtfsFile = ""; - private Config isochronePreparationOpts; - private Config preparationOpts; - private Config executionOpts; - - private String elevationProvider = null; - private String elevationCachePath = null; - private String elevationDataAccess = "MMAP"; - private boolean elevationCacheClear = true; - private boolean elevationSmoothing = true; - private boolean interpolateBridgesAndTunnels = true; - private int maximumSnappingRadius = 350; + private String name = ""; + private boolean enabled = true; + private String profiles = ""; // comma separated + private String graphPath; + private Map> extStorages; + private Map> graphBuilders; + private Double maximumDistance = 0.0; + private Double maximumDistanceDynamicWeights = 0.0; + private Double maximumDistanceAvoidAreas = 0.0; + private Double maximumDistanceAlternativeRoutes = 0.0; + private Double maximumDistanceRoundTripRoutes = 0.0; + private Integer maximumWayPoints = 0; + private boolean instructions = true; + private boolean optimize = false; + + private int encoderFlagsSize = 4; + private String encoderOptions = ""; + private String gtfsFile = ""; + private Config isochronePreparationOpts; + private Config preparationOpts; + private Config executionOpts; + + private String elevationProvider = null; + private String elevationCachePath = null; + private String elevationDataAccess = "MMAP"; + private boolean elevationCacheClear = true; + private boolean elevationSmoothing = true; + private boolean interpolateBridgesAndTunnels = true; + private int maximumSnappingRadius = 350; private Envelope extent; private boolean hasMaximumSnappingRadius = false; @@ -61,17 +60,17 @@ public class RouteProfileConfiguration { private double maximumSpeedLowerBound = 80; - private int trafficExpirationMin = 15; + private final int trafficExpirationMin = 15; - private int maximumVisitedNodesPT = 1000000; + private int maximumVisitedNodesPT = 1000000; private boolean turnCostEnabled = false; - private boolean enforceTurnCosts = false; + private boolean enforceTurnCosts = false; - public RouteProfileConfiguration() { - extStorages = new HashMap<>(); - graphBuilders = new HashMap<>(); - } + public RouteProfileConfiguration() { + extStorages = new HashMap<>(); + graphBuilders = new HashMap<>(); + } public static boolean hasTurnCosts(String encoderOptions) { for (String option : encoderOptions.split("\\|")) { @@ -345,27 +344,27 @@ public void setTurnCostEnabled(boolean turnCostEnabled) { this.turnCostEnabled = turnCostEnabled; } - public void setEnforceTurnCosts(boolean enforceTurnCosts) { - this.enforceTurnCosts = enforceTurnCosts; - } + public void setEnforceTurnCosts(boolean enforceTurnCosts) { + this.enforceTurnCosts = enforceTurnCosts; + } - public boolean isEnforceTurnCosts() { - return enforceTurnCosts; - } + public boolean isEnforceTurnCosts() { + return enforceTurnCosts; + } - public void setGtfsFile(String gtfsFile) { - this.gtfsFile = gtfsFile; - } + public void setGtfsFile(String gtfsFile) { + this.gtfsFile = gtfsFile; + } - public String getGtfsFile() { - return this.gtfsFile; - } + public String getGtfsFile() { + return this.gtfsFile; + } - public int getMaximumVisitedNodesPT() { - return maximumVisitedNodesPT; - } + public int getMaximumVisitedNodesPT() { + return maximumVisitedNodesPT; + } - public void setMaximumVisitedNodesPT(int maximumVisitedNodesPT) { - this.maximumVisitedNodesPT = maximumVisitedNodesPT; - } + public void setMaximumVisitedNodesPT(int maximumVisitedNodesPT) { + this.maximumVisitedNodesPT = maximumVisitedNodesPT; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RoutingManagerConfiguration.java b/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RoutingManagerConfiguration.java index a349cb74dd..6d6b398b2c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RoutingManagerConfiguration.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/configuration/RoutingManagerConfiguration.java @@ -20,7 +20,6 @@ import org.heigit.ors.routing.RoutingProfileType; import org.heigit.ors.util.FileUtility; import org.heigit.ors.util.StringUtility; -import org.locationtech.jts.geom.Envelope; import java.nio.file.Paths; import java.util.ArrayList; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/AccessRestrictionType.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/AccessRestrictionType.java index 5ebe3dd3b4..f6bae5ee48 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/AccessRestrictionType.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/AccessRestrictionType.java @@ -1,26 +1,27 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; public abstract class AccessRestrictionType { - public static final int NONE = 0; - public static final int NO = 1; - public static final int CUSTOMERS = 2; - public static final int DESTINATION = 4; - public static final int DELIVERY = 8; - public static final int PRIVATE = 16; - public static final int PERMISSIVE = 32; + public static final int NONE = 0; + public static final int NO = 1; + public static final int CUSTOMERS = 2; + public static final int DESTINATION = 4; + public static final int DELIVERY = 8; + public static final int PRIVATE = 16; + public static final int PERMISSIVE = 32; - private AccessRestrictionType() {} + private AccessRestrictionType() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/CorePathCalculator.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/CorePathCalculator.java index 798f3e77b8..54d1f1a6f0 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/CorePathCalculator.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/CorePathCalculator.java @@ -23,7 +23,7 @@ public class CorePathCalculator implements PathCalculator { private final QueryGraph queryGraph; private final RoutingAlgorithmFactory algoFactory; - private Weighting weighting; + private final Weighting weighting; private final AlgorithmOptions algoOpts; private String debug; private int visitedNodes; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/DataReaderContext.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/DataReaderContext.java index c99ca07ccb..404cf020bb 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/DataReaderContext.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/DataReaderContext.java @@ -1,31 +1,31 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; -import java.util.Collection; - import com.carrotsearch.hppc.LongIndexedContainer; import com.graphhopper.coll.LongIntMap; import com.graphhopper.storage.IntsRef; import com.graphhopper.util.EdgeIteratorState; +import java.util.Collection; + public interface DataReaderContext { - LongIntMap getNodeMap(); - - double getNodeLongitude(int nodeId); - - double getNodeLatitude(int nodeId); + LongIntMap getNodeMap(); + + double getNodeLongitude(int nodeId); + + double getNodeLatitude(int nodeId); - Collection addWay(final LongIndexedContainer subgraphNodes, final IntsRef wayFlags, final long wayId); + Collection addWay(final LongIndexedContainer subgraphNodes, final IntsRef wayFlags, final long wayId); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/GraphProcessContext.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/GraphProcessContext.java index e3c1ae12e4..27df31e723 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/GraphProcessContext.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/GraphProcessContext.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; @@ -18,155 +18,153 @@ import com.graphhopper.reader.ReaderWay; import com.graphhopper.storage.IntsRef; import com.graphhopper.util.EdgeIteratorState; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.Envelope; import org.heigit.ors.plugins.PluginManager; import org.heigit.ors.routing.configuration.RouteProfileConfiguration; import org.heigit.ors.routing.graphhopper.extensions.graphbuilders.GraphBuilder; import org.heigit.ors.routing.graphhopper.extensions.storages.builders.GraphStorageBuilder; import org.heigit.ors.routing.graphhopper.extensions.storages.builders.HereTrafficGraphStorageBuilder; +import org.locationtech.jts.geom.Coordinate; import java.util.List; import java.util.Map; import java.util.logging.Logger; public class GraphProcessContext { - private static final Logger LOGGER = Logger.getLogger(GraphProcessContext.class.getName()); - private List graphBuilders; - private GraphBuilder[] arrGraphBuilders; - private List storageBuilders; - private GraphStorageBuilder[] arrStorageBuilders; - private int trafficArrStorageBuilderLocation = -1; - private final double maximumSpeedLowerBound; - - private boolean getElevationFromPreprocessedData; - - public GraphProcessContext(RouteProfileConfiguration config) throws Exception { - PluginManager mgrGraphStorageBuilders = PluginManager.getPluginManager(GraphStorageBuilder.class); - - if (config.getExtStorages() != null) { - storageBuilders = mgrGraphStorageBuilders.createInstances(config.getExtStorages()); - } - - PluginManager mgrGraphBuilders = PluginManager.getPluginManager(GraphBuilder.class); - if (config.getGraphBuilders() != null) { - graphBuilders = mgrGraphBuilders.createInstances(config.getGraphBuilders()); - } - - maximumSpeedLowerBound = config.getMaximumSpeedLowerBound(); - } - - public void init(GraphHopper gh) { - if (graphBuilders != null && !graphBuilders.isEmpty()) { - for(GraphBuilder builder : graphBuilders) { - try { - builder.init(gh); - } catch(Exception ex) { - LOGGER.warning(ex.getMessage()); - } - } - } - } - - public void initArrays() { - if (storageBuilders != null && !storageBuilders.isEmpty()) { - arrStorageBuilders = new GraphStorageBuilder[storageBuilders.size()]; - arrStorageBuilders = storageBuilders.toArray(arrStorageBuilders); - } - if (graphBuilders != null && !graphBuilders.isEmpty()) { - arrGraphBuilders = new GraphBuilder[graphBuilders.size()]; - arrGraphBuilders = graphBuilders.toArray(arrGraphBuilders); - } - } - - public List getStorageBuilders() - { - return storageBuilders; - } - - public void processWay(ReaderWay way) { - try { - if (arrStorageBuilders != null) { - for (GraphStorageBuilder builder: arrStorageBuilders) { - builder.processWay(way); - } - } - } catch(Exception ex) { - LOGGER.warning(ex.getMessage() + ". Way id = " + way.getId()); - } - } - - /** - * Pass the way read along with its geometry (a LineString) to the graph storage builders. - * - * @param way The OSM data for the way (including tags) - * @param coords Coordinates of the linestring - * @param nodeTags Tags for nodes found on the way - */ - public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags, Coordinate[] allCoordinates) { - try { - if (arrStorageBuilders != null) { - int nStorages = arrStorageBuilders.length; - if (nStorages > 0) { - for (int i = 0; i < nStorages; ++i) { - if (trafficArrStorageBuilderLocation == -1 && arrStorageBuilders[i].getName().equals(HereTrafficGraphStorageBuilder.BUILDER_NAME)){ - trafficArrStorageBuilderLocation = i; - } - arrStorageBuilders[i].processWay(way, coords, nodeTags); - } - if (trafficArrStorageBuilderLocation >= 0){ - arrStorageBuilders[trafficArrStorageBuilderLocation].processWay(way, allCoordinates, nodeTags); - } - } - } - } catch(Exception ex) { - LOGGER.warning(ex.getMessage() + ". Way id = " + way.getId()); - } - } - - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - if (arrStorageBuilders != null) { - for (GraphStorageBuilder builder: arrStorageBuilders) { - builder.processEdge(way, edge); - } - } - } - - public void processEdge(ReaderWay way, EdgeIteratorState edge, Coordinate[] coords) { - if(arrStorageBuilders != null) { - for (GraphStorageBuilder builder: arrStorageBuilders) { - builder.processEdge(way, edge, coords); - } - } - } - - public boolean createEdges(DataReaderContext readerCntx, ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) throws Exception { - boolean res = false; - if (arrGraphBuilders != null) { - for (GraphBuilder builder: arrGraphBuilders) { - res |= builder.createEdges(readerCntx, way, osmNodeIds, wayFlags, createdEdges); - } - } - return res; - } - - public void finish() { - if (arrStorageBuilders != null) { - for (GraphStorageBuilder builder: arrStorageBuilders) { - builder.finish(); - } - } - } - - public double getMaximumSpeedLowerBound(){ - return maximumSpeedLowerBound; - } - - public void setGetElevationFromPreprocessedData(boolean getElevationFromPreprocessedData) { - this.getElevationFromPreprocessedData = getElevationFromPreprocessedData; - } - - public boolean getElevationFromPreprocessedData() { - return getElevationFromPreprocessedData; - } + private static final Logger LOGGER = Logger.getLogger(GraphProcessContext.class.getName()); + private List graphBuilders; + private GraphBuilder[] arrGraphBuilders; + private List storageBuilders; + private GraphStorageBuilder[] arrStorageBuilders; + private int trafficArrStorageBuilderLocation = -1; + private final double maximumSpeedLowerBound; + + private boolean getElevationFromPreprocessedData; + + public GraphProcessContext(RouteProfileConfiguration config) throws Exception { + PluginManager mgrGraphStorageBuilders = PluginManager.getPluginManager(GraphStorageBuilder.class); + + if (config.getExtStorages() != null) { + storageBuilders = mgrGraphStorageBuilders.createInstances(config.getExtStorages()); + } + + PluginManager mgrGraphBuilders = PluginManager.getPluginManager(GraphBuilder.class); + if (config.getGraphBuilders() != null) { + graphBuilders = mgrGraphBuilders.createInstances(config.getGraphBuilders()); + } + + maximumSpeedLowerBound = config.getMaximumSpeedLowerBound(); + } + + public void init(GraphHopper gh) { + if (graphBuilders != null && !graphBuilders.isEmpty()) { + for (GraphBuilder builder : graphBuilders) { + try { + builder.init(gh); + } catch (Exception ex) { + LOGGER.warning(ex.getMessage()); + } + } + } + } + + public void initArrays() { + if (storageBuilders != null && !storageBuilders.isEmpty()) { + arrStorageBuilders = new GraphStorageBuilder[storageBuilders.size()]; + arrStorageBuilders = storageBuilders.toArray(arrStorageBuilders); + } + if (graphBuilders != null && !graphBuilders.isEmpty()) { + arrGraphBuilders = new GraphBuilder[graphBuilders.size()]; + arrGraphBuilders = graphBuilders.toArray(arrGraphBuilders); + } + } + + public List getStorageBuilders() { + return storageBuilders; + } + + public void processWay(ReaderWay way) { + try { + if (arrStorageBuilders != null) { + for (GraphStorageBuilder builder : arrStorageBuilders) { + builder.processWay(way); + } + } + } catch (Exception ex) { + LOGGER.warning(ex.getMessage() + ". Way id = " + way.getId()); + } + } + + /** + * Pass the way read along with its geometry (a LineString) to the graph storage builders. + * + * @param way The OSM data for the way (including tags) + * @param coords Coordinates of the linestring + * @param nodeTags Tags for nodes found on the way + */ + public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags, Coordinate[] allCoordinates) { + try { + if (arrStorageBuilders != null) { + int nStorages = arrStorageBuilders.length; + if (nStorages > 0) { + for (int i = 0; i < nStorages; ++i) { + if (trafficArrStorageBuilderLocation == -1 && arrStorageBuilders[i].getName().equals(HereTrafficGraphStorageBuilder.BUILDER_NAME)) { + trafficArrStorageBuilderLocation = i; + } + arrStorageBuilders[i].processWay(way, coords, nodeTags); + } + if (trafficArrStorageBuilderLocation >= 0) { + arrStorageBuilders[trafficArrStorageBuilderLocation].processWay(way, allCoordinates, nodeTags); + } + } + } + } catch (Exception ex) { + LOGGER.warning(ex.getMessage() + ". Way id = " + way.getId()); + } + } + + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + if (arrStorageBuilders != null) { + for (GraphStorageBuilder builder : arrStorageBuilders) { + builder.processEdge(way, edge); + } + } + } + + public void processEdge(ReaderWay way, EdgeIteratorState edge, Coordinate[] coords) { + if (arrStorageBuilders != null) { + for (GraphStorageBuilder builder : arrStorageBuilders) { + builder.processEdge(way, edge, coords); + } + } + } + + public boolean createEdges(DataReaderContext readerCntx, ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) throws Exception { + boolean res = false; + if (arrGraphBuilders != null) { + for (GraphBuilder builder : arrGraphBuilders) { + res |= builder.createEdges(readerCntx, way, osmNodeIds, wayFlags, createdEdges); + } + } + return res; + } + + public void finish() { + if (arrStorageBuilders != null) { + for (GraphStorageBuilder builder : arrStorageBuilders) { + builder.finish(); + } + } + } + + public double getMaximumSpeedLowerBound() { + return maximumSpeedLowerBound; + } + + public void setGetElevationFromPreprocessedData(boolean getElevationFromPreprocessedData) { + this.getElevationFromPreprocessedData = getElevationFromPreprocessedData; + } + + public boolean getElevationFromPreprocessedData() { + return getElevationFromPreprocessedData; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/HeavyVehicleAttributes.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/HeavyVehicleAttributes.java index f082ae8208..5a686a3970 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/HeavyVehicleAttributes.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/HeavyVehicleAttributes.java @@ -1,47 +1,48 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; public class HeavyVehicleAttributes { - public static final int UNKNOWN = 0; - // Vehicle type and - public static final int GOODS = 1; - public static final int HGV = 2; - public static final int BUS = 4; - public static final int AGRICULTURE = 8; - public static final int FORESTRY = 16; - public static final int DELIVERY = 32; - public static final int ANY = GOODS | HGV | BUS | AGRICULTURE | FORESTRY | DELIVERY; - // Load characteristics - public static final int HAZMAT = 128; + public static final int UNKNOWN = 0; + // Vehicle type and + public static final int GOODS = 1; + public static final int HGV = 2; + public static final int BUS = 4; + public static final int AGRICULTURE = 8; + public static final int FORESTRY = 16; + public static final int DELIVERY = 32; + public static final int ANY = GOODS | HGV | BUS | AGRICULTURE | FORESTRY | DELIVERY; + // Load characteristics + public static final int HAZMAT = 128; - private HeavyVehicleAttributes() {} + private HeavyVehicleAttributes() { + } - public static int getFromString(String value) { - if ("goods".equalsIgnoreCase(value)) { - return HeavyVehicleAttributes.GOODS; - } else if ("hgv".equalsIgnoreCase(value)) { - return HeavyVehicleAttributes.HGV; - } else if ("bus".equalsIgnoreCase(value)) { - return HeavyVehicleAttributes.BUS; - } else if ("agricultural".equalsIgnoreCase(value)) { - return HeavyVehicleAttributes.AGRICULTURE; - } else if ("forestry".equalsIgnoreCase(value)) { - return HeavyVehicleAttributes.FORESTRY; - } else if ("delivery".equalsIgnoreCase(value)) { - return HeavyVehicleAttributes.DELIVERY; - } - return HeavyVehicleAttributes.UNKNOWN; - } + public static int getFromString(String value) { + if ("goods".equalsIgnoreCase(value)) { + return HeavyVehicleAttributes.GOODS; + } else if ("hgv".equalsIgnoreCase(value)) { + return HeavyVehicleAttributes.HGV; + } else if ("bus".equalsIgnoreCase(value)) { + return HeavyVehicleAttributes.BUS; + } else if ("agricultural".equalsIgnoreCase(value)) { + return HeavyVehicleAttributes.AGRICULTURE; + } else if ("forestry".equalsIgnoreCase(value)) { + return HeavyVehicleAttributes.FORESTRY; + } else if ("delivery".equalsIgnoreCase(value)) { + return HeavyVehicleAttributes.DELIVERY; + } + return HeavyVehicleAttributes.UNKNOWN; + } } \ No newline at end of file diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSDefaultFlagEncoderFactory.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSDefaultFlagEncoderFactory.java index 70ec2f00b5..5166faa8b7 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSDefaultFlagEncoderFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSDefaultFlagEncoderFactory.java @@ -25,7 +25,7 @@ public class ORSDefaultFlagEncoderFactory extends DefaultFlagEncoderFactory impl @Override public FlagEncoder createFlagEncoder(String name, PMap configuration) { - switch(name){ + switch (name) { case FlagEncoderNames.CAR_ORS: return new org.heigit.ors.routing.graphhopper.extensions.flagencoders.CarFlagEncoder(configuration); @@ -44,7 +44,7 @@ public FlagEncoder createFlagEncoder(String name, PMap configuration) { case FlagEncoderNames.MTB_ORS: // MARQ24 hardcoded "ignore" consider_elevation for the NextGenMountainBike FlagEncoder - when // consider_elevation is enabled we have various detours (over smaler tracks) - if(configuration.getBool(KEY_CONSIDER_ELEVATION, false)){ + if (configuration.getBool(KEY_CONSIDER_ELEVATION, false)) { configuration.remove(KEY_CONSIDER_ELEVATION); } return new org.heigit.ors.routing.graphhopper.extensions.flagencoders.bike.MountainBikeFlagEncoder(configuration); @@ -52,7 +52,7 @@ public FlagEncoder createFlagEncoder(String name, PMap configuration) { case FlagEncoderNames.BIKE_ELECTRO: // MARQ24 hardcoded "ignore" consider_elevation for the NextGenMountainBike FlagEncoder - when // consider_elevation is enabled we have various detours (over smaler tracks) - if(configuration.getBool(KEY_CONSIDER_ELEVATION, false)){ + if (configuration.getBool(KEY_CONSIDER_ELEVATION, false)) { configuration.remove(KEY_CONSIDER_ELEVATION); } return new org.heigit.ors.routing.graphhopper.extensions.flagencoders.bike.ElectroBikeFlagEncoder(configuration); @@ -61,7 +61,7 @@ public FlagEncoder createFlagEncoder(String name, PMap configuration) { // MARQ24 hardcoded "ignore" consider_elevation for the NextGenRoadbike FlagEncoder - when // consider_elevation is enabled we have various detours (over smaler tracks) // see http://localhost:3035/directions?n1=51.562385&n2=8.724582&n3=15&a=51.573202,8.709326,51.54879,8.710184&b=1c&c=0&g1=-1&g2=0&h2=3&k1=en-US&k2=km - if(configuration.getBool(KEY_CONSIDER_ELEVATION, false)){ + if (configuration.getBool(KEY_CONSIDER_ELEVATION, false)) { configuration.remove(KEY_CONSIDER_ELEVATION); } return new org.heigit.ors.routing.graphhopper.extensions.flagencoders.bike.RoadBikeFlagEncoder(configuration); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSEdgeFilterFactory.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSEdgeFilterFactory.java index 029aa3a135..493ae538ec 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSEdgeFilterFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSEdgeFilterFactory.java @@ -19,12 +19,12 @@ import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.util.PMap; -import org.locationtech.jts.geom.Polygon; +import org.apache.log4j.Logger; import org.heigit.ors.routing.RouteSearchParameters; import org.heigit.ors.routing.graphhopper.extensions.edgefilters.*; import org.heigit.ors.routing.parameters.VehicleParameters; import org.heigit.ors.routing.parameters.WheelchairParameters; -import org.apache.log4j.Logger; +import org.locationtech.jts.geom.Polygon; public class ORSEdgeFilterFactory implements EdgeFilterFactory { private static final Logger LOGGER = Logger.getLogger(ORSEdgeFilterFactory.class.getName()); @@ -51,7 +51,7 @@ public EdgeFilter createEdgeFilter(PMap opts, FlagEncoder flagEncoder, GraphHopp if (opts.has("avoid_areas")) { edgeFilters.add(new AvoidAreasEdgeFilter(opts.getObject("avoid_areas", new Polygon[]{}))); } - + /* Heavy vehicle filter */ if (opts.has("edgefilter_hgv")) { edgeFilters.add(new HeavyVehicleEdgeFilter(opts.getInt("edgefilter_hgv", 0), opts.getObject("routing_profile_params", new VehicleParameters()), gs)); @@ -61,17 +61,17 @@ public EdgeFilter createEdgeFilter(PMap opts, FlagEncoder flagEncoder, GraphHopp else if (opts.has("edgefilter_wheelchair")) { edgeFilters.add(new WheelchairEdgeFilter(opts.getObject("routing_profile_params", new WheelchairParameters()), gs)); } - + /* Avoid features */ if (opts.has("avoid_features") && opts.has("routing_profile_type")) { edgeFilters.add(new AvoidFeaturesEdgeFilter(opts.getInt("routing_profile_type", 0), opts.getObject("avoid_features", new RouteSearchParameters()), gs)); } - + /* Avoid borders */ if (opts.has("avoid_borders")) { edgeFilters.add(new AvoidBordersEdgeFilter(opts.getObject("avoid_borders", new RouteSearchParameters()), gs)); } - + } catch (Exception ex) { LOGGER.error(ex); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopper.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopper.java index e5df024de9..c30e118d1b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopper.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopper.java @@ -39,9 +39,6 @@ import com.graphhopper.util.details.PathDetailsBuilderFactory; import com.graphhopper.util.exceptions.ConnectionNotFoundException; import org.geotools.feature.SchemaException; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.GeometryFactory; -import org.locationtech.jts.geom.LineString; import org.heigit.ors.common.TravelRangeType; import org.heigit.ors.fastisochrones.Contour; import org.heigit.ors.fastisochrones.Eccentricity; @@ -67,6 +64,9 @@ import org.heigit.ors.routing.graphhopper.extensions.weighting.HgvAccessWeighting; import org.heigit.ors.routing.pathprocessors.BordersExtractor; import org.heigit.ors.util.CoordTools; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.GeometryFactory; +import org.locationtech.jts.geom.LineString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -79,32 +79,32 @@ public class ORSGraphHopper extends GraphHopperGtfs { - private static final Logger LOGGER = LoggerFactory.getLogger(ORSGraphHopper.class); - public static final String KEY_DEPARTURE = "departure"; - public static final String KEY_ARRIVAL = "arrival"; + private static final Logger LOGGER = LoggerFactory.getLogger(ORSGraphHopper.class); + public static final String KEY_DEPARTURE = "departure"; + public static final String KEY_ARRIVAL = "arrival"; - private GraphProcessContext processContext; - private HashMap> osmId2EdgeIds; // one osm id can correspond to multiple edges - private HashMap tmcEdges; - private Eccentricity eccentricity; + private GraphProcessContext processContext; + private HashMap> osmId2EdgeIds; // one osm id can correspond to multiple edges + private HashMap tmcEdges; + private Eccentricity eccentricity; - private int minNetworkSize = 200; - private int minOneWayNetworkSize = 0; + private int minNetworkSize = 200; + private int minOneWayNetworkSize = 0; - private final CorePreparationHandler corePreparationHandler = new CorePreparationHandler(); - private final CoreLMPreparationHandler coreLMPreparationHandler = new CoreLMPreparationHandler(); - private final FastIsochroneFactory fastIsochroneFactory = new FastIsochroneFactory(); + private final CorePreparationHandler corePreparationHandler = new CorePreparationHandler(); + private final CoreLMPreparationHandler coreLMPreparationHandler = new CoreLMPreparationHandler(); + private final FastIsochroneFactory fastIsochroneFactory = new FastIsochroneFactory(); - public GraphHopperConfig getConfig() { - return config; - } + public GraphHopperConfig getConfig() { + return config; + } - private GraphHopperConfig config; + private GraphHopperConfig config; - public ORSGraphHopper(GraphProcessContext procCntx) { - processContext = procCntx; - processContext.init(this); + public ORSGraphHopper(GraphProcessContext procCntx) { + processContext = procCntx; + processContext.init(this); } @@ -112,52 +112,52 @@ public ORSGraphHopper() { // used to initialize tests more easily without the need to create GraphProcessContext etc. when they're anyway not used in the tested functions. } - @Override - public GraphHopper init(GraphHopperConfig ghConfig) { - GraphHopper ret = super.init(ghConfig); - - if (ghConfig instanceof ORSGraphHopperConfig orsConfig) { - corePreparationHandler.init(orsConfig); - coreLMPreparationHandler.init(orsConfig); - } - - fastIsochroneFactory.init(ghConfig); - - minNetworkSize = ghConfig.getInt("prepare.min_network_size", minNetworkSize); - minOneWayNetworkSize = ghConfig.getInt("prepare.min_one_way_network_size", minOneWayNetworkSize); - config = ghConfig; - return ret; - } - - @Override - protected void cleanUp() { - if (LOGGER.isInfoEnabled()) - LOGGER.info("call cleanUp for '%s' ".formatted(getGraphHopperLocation())); - GraphHopperStorage ghs = getGraphHopperStorage(); - if (ghs != null) { - if (LOGGER.isInfoEnabled()) - LOGGER.info("graph %s, details:%s".formatted(ghs, ghs.toDetailsString())); - int prevNodeCount = ghs.getNodes(); - int ex = ghs.getAllEdges().length(); - List list = getEncodingManager().fetchEdgeEncoders(); - if (LOGGER.isDebugEnabled()) - LOGGER.debug("will create PrepareRoutingSubnetworks with: NodeCountBefore: '%d' getAllEdges().getMaxId(): '%d' List: '%s' minNetworkSize: '%d' minOneWayNetworkSize: '%d'".formatted(prevNodeCount, ex, list, minNetworkSize, minOneWayNetworkSize) - ); - ghs.getProperties().put("elevation", hasElevation()); - } else { - LOGGER.info("graph GraphHopperStorage is null?!"); - } - super.cleanUp(); - } - - @Override - protected OSMReader createOSMReader() { - return new ORSOSMReader(getGraphHopperStorage(), processContext); - } - - @Override - public GraphHopper importOrLoad() { - GraphHopper gh = super.importOrLoad(); + @Override + public GraphHopper init(GraphHopperConfig ghConfig) { + GraphHopper ret = super.init(ghConfig); + + if (ghConfig instanceof ORSGraphHopperConfig orsConfig) { + corePreparationHandler.init(orsConfig); + coreLMPreparationHandler.init(orsConfig); + } + + fastIsochroneFactory.init(ghConfig); + + minNetworkSize = ghConfig.getInt("prepare.min_network_size", minNetworkSize); + minOneWayNetworkSize = ghConfig.getInt("prepare.min_one_way_network_size", minOneWayNetworkSize); + config = ghConfig; + return ret; + } + + @Override + protected void cleanUp() { + if (LOGGER.isInfoEnabled()) + LOGGER.info("call cleanUp for '%s' ".formatted(getGraphHopperLocation())); + GraphHopperStorage ghs = getGraphHopperStorage(); + if (ghs != null) { + if (LOGGER.isInfoEnabled()) + LOGGER.info("graph %s, details:%s".formatted(ghs, ghs.toDetailsString())); + int prevNodeCount = ghs.getNodes(); + int ex = ghs.getAllEdges().length(); + List list = getEncodingManager().fetchEdgeEncoders(); + if (LOGGER.isDebugEnabled()) + LOGGER.debug("will create PrepareRoutingSubnetworks with: NodeCountBefore: '%d' getAllEdges().getMaxId(): '%d' List: '%s' minNetworkSize: '%d' minOneWayNetworkSize: '%d'".formatted(prevNodeCount, ex, list, minNetworkSize, minOneWayNetworkSize) + ); + ghs.getProperties().put("elevation", hasElevation()); + } else { + LOGGER.info("graph GraphHopperStorage is null?!"); + } + super.cleanUp(); + } + + @Override + protected OSMReader createOSMReader() { + return new ORSOSMReader(getGraphHopperStorage(), processContext); + } + + @Override + public GraphHopper importOrLoad() { + GraphHopper gh = super.importOrLoad(); if ((tmcEdges != null) && (osmId2EdgeIds != null)) { java.nio.file.Path path = Paths.get(gh.getGraphHopperLocation(), "edges_ors_traffic"); @@ -195,67 +195,68 @@ public GraphHopper importOrLoad() { return gh; } - @Override - protected Router doCreateRouter(GraphHopperStorage ghStorage, LocationIndex locationIndex, Map profilesByName, - PathDetailsBuilderFactory pathBuilderFactory, TranslationMap trMap, RouterConfig routerConfig, - WeightingFactory weightingFactory, Map chGraphs, Map landmarks) { - ORSRouter r = new ORSRouter(ghStorage, locationIndex, profilesByName, pathBuilderFactory, trMap, routerConfig, weightingFactory, chGraphs, landmarks); - r.setEdgeFilterFactory(new ORSEdgeFilterFactory()); - r.setPathProcessorFactory(pathProcessorFactory); - - if (!(ghStorage instanceof ORSGraphHopperStorage)) - throw new IllegalStateException("Expected an instance of ORSGraphHopperStorage"); - - Map coreGraphs = new LinkedHashMap<>(); - for (com.graphhopper.config.CHProfile chProfile : corePreparationHandler.getCHProfiles()) { - String chGraphName = corePreparationHandler.getPreparation(chProfile.getProfile()).getCHConfig().getName(); - coreGraphs.put(chProfile.getProfile(), ((ORSGraphHopperStorage) ghStorage).getCoreGraph(chGraphName)); - } - r.setCoreGraphs(coreGraphs); - - Map coreLandmarks = new LinkedHashMap<>(); - for (PrepareLandmarks preparation : coreLMPreparationHandler.getPreparations()) { - coreLandmarks.put(preparation.getLMConfig().getName(), (PrepareCoreLandmarks) preparation); - } - r.setCoreLandmarks(coreLandmarks); - - return r; - } - - @Override - protected WeightingFactory createWeightingFactory() { - return new ORSWeightingFactory(getGraphHopperStorage(), getEncodingManager()); - } - - /** - * Check whether the route processing has to start. If avoid all borders is set and the routing points are in different countries, - * there is no need to even start routing. - * @param request To get the avoid borders setting - * @param queryResult To get the edges of the queries and check which country they're in - */ - private void checkAvoidBorders(GHRequest request, List queryResult) { - /* Avoid borders */ - PMap params = request.getAdditionalHints(); - if (params == null) { - params = new PMap(); - } - boolean isRouteable = true; - - if (params.has("avoid_borders")) { - RouteSearchParameters routeSearchParameters = params.getObject("avoid_borders", new RouteSearchParameters()); - //Avoiding All borders - if(routeSearchParameters.hasAvoidBorders() && routeSearchParameters.getAvoidBorders() == BordersExtractor.Avoid.ALL) { - List edgeIds = new ArrayList<>(); - for (int placeIndex = 0; placeIndex < queryResult.size(); placeIndex++) { - edgeIds.add(queryResult.get(placeIndex).getClosestEdge().getEdge()); - } - BordersExtractor bordersExtractor = new BordersExtractor(GraphStorageUtils.getGraphExtension(getGraphHopperStorage(), BordersGraphStorage.class), null); - isRouteable = bordersExtractor.isSameCountry(edgeIds); - } - //TODO Refactoring : Avoiding CONTROLLED borders - //Currently this is extremely messy, as for some reason the READER stores data in addition to the BordersStorage. - //At the same time, it is not possible to get isOpen from the Reader via ids, because it only takes Strings. But there are no Strings in the Storage. - //So no controlled borders for now until this whole thing is refactored and the Reader is an actual reader and not a storage. + @Override + protected Router doCreateRouter(GraphHopperStorage ghStorage, LocationIndex locationIndex, Map profilesByName, + PathDetailsBuilderFactory pathBuilderFactory, TranslationMap trMap, RouterConfig routerConfig, + WeightingFactory weightingFactory, Map chGraphs, Map landmarks) { + ORSRouter r = new ORSRouter(ghStorage, locationIndex, profilesByName, pathBuilderFactory, trMap, routerConfig, weightingFactory, chGraphs, landmarks); + r.setEdgeFilterFactory(new ORSEdgeFilterFactory()); + r.setPathProcessorFactory(pathProcessorFactory); + + if (!(ghStorage instanceof ORSGraphHopperStorage)) + throw new IllegalStateException("Expected an instance of ORSGraphHopperStorage"); + + Map coreGraphs = new LinkedHashMap<>(); + for (com.graphhopper.config.CHProfile chProfile : corePreparationHandler.getCHProfiles()) { + String chGraphName = corePreparationHandler.getPreparation(chProfile.getProfile()).getCHConfig().getName(); + coreGraphs.put(chProfile.getProfile(), ((ORSGraphHopperStorage) ghStorage).getCoreGraph(chGraphName)); + } + r.setCoreGraphs(coreGraphs); + + Map coreLandmarks = new LinkedHashMap<>(); + for (PrepareLandmarks preparation : coreLMPreparationHandler.getPreparations()) { + coreLandmarks.put(preparation.getLMConfig().getName(), (PrepareCoreLandmarks) preparation); + } + r.setCoreLandmarks(coreLandmarks); + + return r; + } + + @Override + protected WeightingFactory createWeightingFactory() { + return new ORSWeightingFactory(getGraphHopperStorage(), getEncodingManager()); + } + + /** + * Check whether the route processing has to start. If avoid all borders is set and the routing points are in different countries, + * there is no need to even start routing. + * + * @param request To get the avoid borders setting + * @param queryResult To get the edges of the queries and check which country they're in + */ + private void checkAvoidBorders(GHRequest request, List queryResult) { + /* Avoid borders */ + PMap params = request.getAdditionalHints(); + if (params == null) { + params = new PMap(); + } + boolean isRouteable = true; + + if (params.has("avoid_borders")) { + RouteSearchParameters routeSearchParameters = params.getObject("avoid_borders", new RouteSearchParameters()); + //Avoiding All borders + if (routeSearchParameters.hasAvoidBorders() && routeSearchParameters.getAvoidBorders() == BordersExtractor.Avoid.ALL) { + List edgeIds = new ArrayList<>(); + for (int placeIndex = 0; placeIndex < queryResult.size(); placeIndex++) { + edgeIds.add(queryResult.get(placeIndex).getClosestEdge().getEdge()); + } + BordersExtractor bordersExtractor = new BordersExtractor(GraphStorageUtils.getGraphExtension(getGraphHopperStorage(), BordersGraphStorage.class), null); + isRouteable = bordersExtractor.isSameCountry(edgeIds); + } + //TODO Refactoring : Avoiding CONTROLLED borders + //Currently this is extremely messy, as for some reason the READER stores data in addition to the BordersStorage. + //At the same time, it is not possible to get isOpen from the Reader via ids, because it only takes Strings. But there are no Strings in the Storage. + //So no controlled borders for now until this whole thing is refactored and the Reader is an actual reader and not a storage. // if(routeSearchParameters.hasAvoidBorders() && routeSearchParameters.getAvoidBorders() == BordersExtractor.Avoid.CONTROLLED) { // GraphStorageBuilder countryBordersReader; @@ -278,9 +279,9 @@ private void checkAvoidBorders(GHRequest request, List queryResult) { // } // } // } - } - if(!isRouteable) - throw new ConnectionNotFoundException("Route not found due to avoiding borders", Collections.emptyMap()); + } + if (!isRouteable) + throw new ConnectionNotFoundException("Route not found due to avoiding borders", Collections.emptyMap()); } @@ -294,7 +295,7 @@ public GHResponse constructFreeHandRoute(GHRequest request) { } private ResponsePath constructFreeHandRoutePathWrapper(LineString lineString) { - ResponsePath responsePath = new ResponsePath(); + ResponsePath responsePath = new ResponsePath(); PointList pointList = new PointList(); PointList startPointList = new PointList(); PointList endPointList = new PointList(); @@ -357,205 +358,205 @@ private void matchTraffic() { } } - private void addTrafficSpeedCalculator(LMPreparationHandler lmPreparationHandler) { - if (isTrafficEnabled()) - ORSWeightingFactory.addTrafficSpeedCalculator(lmPreparationHandler.getWeightings(), getGraphHopperStorage()); - } + private void addTrafficSpeedCalculator(LMPreparationHandler lmPreparationHandler) { + if (isTrafficEnabled()) + ORSWeightingFactory.addTrafficSpeedCalculator(lmPreparationHandler.getWeightings(), getGraphHopperStorage()); + } /** - * Does the preparation and creates the location index - * - * @param closeEarly release resources as early as possible - */ - @Override - protected void postProcessing(boolean closeEarly) { - super.postProcessing(closeEarly); - - //Create the core - GraphHopperStorage gs = getGraphHopperStorage(); - if(corePreparationHandler.isEnabled()) - corePreparationHandler.setProcessContext(processContext).createPreparations(gs); - if (isCorePrepared()) { - // check loaded profiles - for (CHProfile profile : corePreparationHandler.getCHProfiles()) { - if (!getProfileVersion(profile.getProfile()).isEmpty() && !getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) - throw new IllegalArgumentException("Core preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); - } - } else { - prepareCore(closeEarly); - } - - //Create the landmarks in the core - if (coreLMPreparationHandler.isEnabled()) { - initCoreLMPreparationHandler(); - coreLMPreparationHandler.createPreparations(gs, super.getLocationIndex()); - addTrafficSpeedCalculator(coreLMPreparationHandler); - } - loadOrPrepareCoreLM(); - - if (fastIsochroneFactory.isEnabled()) { - EdgeFilterSequence partitioningEdgeFilter = new EdgeFilterSequence(); - try { - partitioningEdgeFilter.add(new AvoidFeaturesEdgeFilter(AvoidFeatureFlags.FERRIES, getGraphHopperStorage())); - } catch (Exception e) { - LOGGER.debug(e.getLocalizedMessage()); - } - fastIsochroneFactory.createPreparation(gs, partitioningEdgeFilter); - - if (!isPartitionPrepared()) - preparePartition(); - else { - fastIsochroneFactory.setExistingStorages(); - fastIsochroneFactory.getCellStorage().loadExisting(); - fastIsochroneFactory.getIsochroneNodeStorage().loadExisting(); - } - //No fast isochrones without partition - if (isPartitionPrepared()) { - // Initialize edge filter sequence for fast isochrones - calculateContours(); - List profiles = fastIsochroneFactory.getFastIsochroneProfiles(); - for (Profile profile : profiles) { - Weighting weighting = ((ORSWeightingFactory) createWeightingFactory()).createIsochroneWeighting(profile, new PMap(profile.getName()).putObject("isochroneWeighting", "true")); - - for (FlagEncoder encoder : super.getEncodingManager().fetchEdgeEncoders()) { - calculateCellProperties(weighting, partitioningEdgeFilter, encoder, fastIsochroneFactory.getIsochroneNodeStorage(), fastIsochroneFactory.getCellStorage()); - } - } - } - } - } - - @Override - protected void postProcessingHook() { - matchTraffic(); - - if (getLMPreparationHandler().isEnabled()) - addTrafficSpeedCalculator(getLMPreparationHandler()); - } + * Does the preparation and creates the location index + * + * @param closeEarly release resources as early as possible + */ + @Override + protected void postProcessing(boolean closeEarly) { + super.postProcessing(closeEarly); + + //Create the core + GraphHopperStorage gs = getGraphHopperStorage(); + if (corePreparationHandler.isEnabled()) + corePreparationHandler.setProcessContext(processContext).createPreparations(gs); + if (isCorePrepared()) { + // check loaded profiles + for (CHProfile profile : corePreparationHandler.getCHProfiles()) { + if (!getProfileVersion(profile.getProfile()).isEmpty() && !getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) + throw new IllegalArgumentException("Core preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); + } + } else { + prepareCore(closeEarly); + } + + //Create the landmarks in the core + if (coreLMPreparationHandler.isEnabled()) { + initCoreLMPreparationHandler(); + coreLMPreparationHandler.createPreparations(gs, super.getLocationIndex()); + addTrafficSpeedCalculator(coreLMPreparationHandler); + } + loadOrPrepareCoreLM(); + + if (fastIsochroneFactory.isEnabled()) { + EdgeFilterSequence partitioningEdgeFilter = new EdgeFilterSequence(); + try { + partitioningEdgeFilter.add(new AvoidFeaturesEdgeFilter(AvoidFeatureFlags.FERRIES, getGraphHopperStorage())); + } catch (Exception e) { + LOGGER.debug(e.getLocalizedMessage()); + } + fastIsochroneFactory.createPreparation(gs, partitioningEdgeFilter); + + if (!isPartitionPrepared()) + preparePartition(); + else { + fastIsochroneFactory.setExistingStorages(); + fastIsochroneFactory.getCellStorage().loadExisting(); + fastIsochroneFactory.getIsochroneNodeStorage().loadExisting(); + } + //No fast isochrones without partition + if (isPartitionPrepared()) { + // Initialize edge filter sequence for fast isochrones + calculateContours(); + List profiles = fastIsochroneFactory.getFastIsochroneProfiles(); + for (Profile profile : profiles) { + Weighting weighting = ((ORSWeightingFactory) createWeightingFactory()).createIsochroneWeighting(profile, new PMap(profile.getName()).putObject("isochroneWeighting", "true")); + + for (FlagEncoder encoder : super.getEncodingManager().fetchEdgeEncoders()) { + calculateCellProperties(weighting, partitioningEdgeFilter, encoder, fastIsochroneFactory.getIsochroneNodeStorage(), fastIsochroneFactory.getCellStorage()); + } + } + } + } + } + + @Override + protected void postProcessingHook() { + matchTraffic(); + + if (getLMPreparationHandler().isEnabled()) + addTrafficSpeedCalculator(getLMPreparationHandler()); + } //TODO Refactoring : This is a duplication with code in RoutingProfile and should probably be moved to a status keeping class. private boolean hasCHProfile(String profileName) { - return contains(getGraphHopperStorage().getCHGraphNames(), profileName); - } - - private boolean hasCoreProfile(String profileName) { - if (getGraphHopperStorage() instanceof ORSGraphHopperStorage) { - List profiles = ((ORSGraphHopperStorage) getGraphHopperStorage()).getCoreGraphNames(); - return contains(profiles, profileName); - } - return false; - } - - private boolean hasLMProfile(String profileName) { - List profiles = getLMPreparationHandler().getLMConfigs().stream().map(LMConfig::getName).collect(Collectors.toList()); - return contains(profiles, profileName); - } - - private boolean contains(List profiles, String profileName) { - for (String profile : profiles) { - if (profileName.equals(profile)) - return true; - } - return false; - } - - public final boolean isCoreEnabled() { - return corePreparationHandler.isEnabled(); - } - - public final CorePreparationHandler getCorePreparationHandler() { - return corePreparationHandler; - } - - @Override - protected void initCHPreparationHandler() { - CHPreparationHandler chPreparationHandler = getCHPreparationHandler(); - if (chPreparationHandler.hasCHConfigs()) { - return; - } - - for (CHProfile chProfile : chPreparationHandler.getCHProfiles()) { - Profile profile = profilesByName.get(chProfile.getProfile()); - Weighting weighting = createWeighting(profile, new PMap()); - - if (profile.getVehicle().equals(FlagEncoderNames.HEAVYVEHICLE)) { - HeavyVehicleAttributesGraphStorage hgvStorage = GraphStorageUtils.getGraphExtension(getGraphHopperStorage(), HeavyVehicleAttributesGraphStorage.class); - EdgeFilter hgvEdgeFilter = new HeavyVehicleEdgeFilter(HeavyVehicleAttributes.HGV, null, hgvStorage); - weighting = new HgvAccessWeighting(weighting, hgvEdgeFilter); - } - - if (profile.isTurnCosts()) { - chPreparationHandler.addCHConfig(CHConfig.edgeBased(profile.getName(), weighting)); - } else { - chPreparationHandler.addCHConfig(CHConfig.nodeBased(profile.getName(), weighting)); - } - } - } - - protected void loadORS() { - List chConfigs; - if (corePreparationHandler.isEnabled()) { - initCorePreparationHandler(); - chConfigs = corePreparationHandler.getCHConfigs(); - } else { - chConfigs = emptyList(); - } - - if (getGraphHopperStorage() instanceof ORSGraphHopperStorage) - ((ORSGraphHopperStorage) getGraphHopperStorage()).addCoreGraphs(chConfigs); - else - throw new IllegalStateException("Expected an instance of ORSGraphHopperStorage"); - } - - private void initCorePreparationHandler() { - if (corePreparationHandler.hasCHConfigs()) { - return; - } - - for (com.graphhopper.config.CHProfile chProfile : corePreparationHandler.getCHProfiles()) { - Profile profile = profilesByName.get(chProfile.getProfile()); - corePreparationHandler.addCHConfig(new CHConfig(profile.getName(), createWeighting(profile, new PMap()), profile.isTurnCosts(), CHConfig.TYPE_CORE)); - } - } - - private void initCoreLMPreparationHandler() { - if (coreLMPreparationHandler.hasLMProfiles()) - return; - - CoreLMOptions coreLMOptions = coreLMPreparationHandler.getCoreLMOptions(); - coreLMOptions.createRestrictionFilters(getGraphHopperStorage()); - - for (LMProfile lmProfile : coreLMPreparationHandler.getLMProfiles()) { - if (lmProfile.usesOtherPreparation()) - continue; - Profile profile = profilesByName.get(lmProfile.getProfile()); - Weighting weighting = createWeighting(profile, new PMap(), true); - for (LMEdgeFilterSequence edgeFilter : coreLMOptions.getFilters()) { - CoreLMConfig coreLMConfig = new CoreLMConfig(profile.getName(), weighting); - coreLMConfig.setEdgeFilter(edgeFilter); - coreLMPreparationHandler.addLMConfig(coreLMConfig); - } - } - } - - protected void prepareCore(boolean closeEarly) { - for (CHProfile profile : corePreparationHandler.getCHProfiles()) { - if (!getProfileVersion(profile.getProfile()).isEmpty() - && !getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) - throw new IllegalArgumentException("Core preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); - } - if (isCoreEnabled()) { - ensureWriteAccess(); - GraphHopperStorage ghStorage = getGraphHopperStorage(); - ghStorage.freeze(); - corePreparationHandler.prepare(ghStorage.getProperties(), closeEarly); - ghStorage.getProperties().put(ORSParameters.Core.PREPARE + "done", true); - for (CHProfile profile : corePreparationHandler.getCHProfiles()) { - // potentially overwrite existing keys from CH/LM - setProfileVersion(profile.getProfile(), profilesByName.get(profile.getProfile()).getVersion()); - } - } - } + return contains(getGraphHopperStorage().getCHGraphNames(), profileName); + } + + private boolean hasCoreProfile(String profileName) { + if (getGraphHopperStorage() instanceof ORSGraphHopperStorage) { + List profiles = ((ORSGraphHopperStorage) getGraphHopperStorage()).getCoreGraphNames(); + return contains(profiles, profileName); + } + return false; + } + + private boolean hasLMProfile(String profileName) { + List profiles = getLMPreparationHandler().getLMConfigs().stream().map(LMConfig::getName).collect(Collectors.toList()); + return contains(profiles, profileName); + } + + private boolean contains(List profiles, String profileName) { + for (String profile : profiles) { + if (profileName.equals(profile)) + return true; + } + return false; + } + + public final boolean isCoreEnabled() { + return corePreparationHandler.isEnabled(); + } + + public final CorePreparationHandler getCorePreparationHandler() { + return corePreparationHandler; + } + + @Override + protected void initCHPreparationHandler() { + CHPreparationHandler chPreparationHandler = getCHPreparationHandler(); + if (chPreparationHandler.hasCHConfigs()) { + return; + } + + for (CHProfile chProfile : chPreparationHandler.getCHProfiles()) { + Profile profile = profilesByName.get(chProfile.getProfile()); + Weighting weighting = createWeighting(profile, new PMap()); + + if (profile.getVehicle().equals(FlagEncoderNames.HEAVYVEHICLE)) { + HeavyVehicleAttributesGraphStorage hgvStorage = GraphStorageUtils.getGraphExtension(getGraphHopperStorage(), HeavyVehicleAttributesGraphStorage.class); + EdgeFilter hgvEdgeFilter = new HeavyVehicleEdgeFilter(HeavyVehicleAttributes.HGV, null, hgvStorage); + weighting = new HgvAccessWeighting(weighting, hgvEdgeFilter); + } + + if (profile.isTurnCosts()) { + chPreparationHandler.addCHConfig(CHConfig.edgeBased(profile.getName(), weighting)); + } else { + chPreparationHandler.addCHConfig(CHConfig.nodeBased(profile.getName(), weighting)); + } + } + } + + protected void loadORS() { + List chConfigs; + if (corePreparationHandler.isEnabled()) { + initCorePreparationHandler(); + chConfigs = corePreparationHandler.getCHConfigs(); + } else { + chConfigs = emptyList(); + } + + if (getGraphHopperStorage() instanceof ORSGraphHopperStorage) + ((ORSGraphHopperStorage) getGraphHopperStorage()).addCoreGraphs(chConfigs); + else + throw new IllegalStateException("Expected an instance of ORSGraphHopperStorage"); + } + + private void initCorePreparationHandler() { + if (corePreparationHandler.hasCHConfigs()) { + return; + } + + for (com.graphhopper.config.CHProfile chProfile : corePreparationHandler.getCHProfiles()) { + Profile profile = profilesByName.get(chProfile.getProfile()); + corePreparationHandler.addCHConfig(new CHConfig(profile.getName(), createWeighting(profile, new PMap()), profile.isTurnCosts(), CHConfig.TYPE_CORE)); + } + } + + private void initCoreLMPreparationHandler() { + if (coreLMPreparationHandler.hasLMProfiles()) + return; + + CoreLMOptions coreLMOptions = coreLMPreparationHandler.getCoreLMOptions(); + coreLMOptions.createRestrictionFilters(getGraphHopperStorage()); + + for (LMProfile lmProfile : coreLMPreparationHandler.getLMProfiles()) { + if (lmProfile.usesOtherPreparation()) + continue; + Profile profile = profilesByName.get(lmProfile.getProfile()); + Weighting weighting = createWeighting(profile, new PMap(), true); + for (LMEdgeFilterSequence edgeFilter : coreLMOptions.getFilters()) { + CoreLMConfig coreLMConfig = new CoreLMConfig(profile.getName(), weighting); + coreLMConfig.setEdgeFilter(edgeFilter); + coreLMPreparationHandler.addLMConfig(coreLMConfig); + } + } + } + + protected void prepareCore(boolean closeEarly) { + for (CHProfile profile : corePreparationHandler.getCHProfiles()) { + if (!getProfileVersion(profile.getProfile()).isEmpty() + && !getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) + throw new IllegalArgumentException("Core preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); + } + if (isCoreEnabled()) { + ensureWriteAccess(); + GraphHopperStorage ghStorage = getGraphHopperStorage(); + ghStorage.freeze(); + corePreparationHandler.prepare(ghStorage.getProperties(), closeEarly); + ghStorage.getProperties().put(ORSParameters.Core.PREPARE + "done", true); + for (CHProfile profile : corePreparationHandler.getCHProfiles()) { + // potentially overwrite existing keys from CH/LM + setProfileVersion(profile.getProfile(), profilesByName.get(profile.getProfile()).getVersion()); + } + } + } private boolean isCorePrepared() { return "true".equals(getGraphHopperStorage().getProperties().get(ORSParameters.Core.PREPARE + "done")) @@ -563,22 +564,22 @@ private boolean isCorePrepared() { || "true".equals(getGraphHopperStorage().getProperties().get("prepare.done")); } - public final boolean isCoreLMEnabled() { - return coreLMPreparationHandler.isEnabled(); - } + public final boolean isCoreLMEnabled() { + return coreLMPreparationHandler.isEnabled(); + } - /** - * For landmarks it is required to always call this method: either it creates the landmark data or it loads it. - */ - protected void loadOrPrepareCoreLM() { - boolean tmpPrepare = coreLMPreparationHandler.isEnabled(); - if (tmpPrepare) { - ensureWriteAccess(); - getGraphHopperStorage().freeze(); - if (coreLMPreparationHandler.loadOrDoWork(getGraphHopperStorage().getProperties(), false)) - getGraphHopperStorage().getProperties().put(ORSParameters.CoreLandmark.PREPARE + "done", true); - } - } + /** + * For landmarks it is required to always call this method: either it creates the landmark data or it loads it. + */ + protected void loadOrPrepareCoreLM() { + boolean tmpPrepare = coreLMPreparationHandler.isEnabled(); + if (tmpPrepare) { + ensureWriteAccess(); + getGraphHopperStorage().freeze(); + if (coreLMPreparationHandler.loadOrDoWork(getGraphHopperStorage().getProperties(), false)) + getGraphHopperStorage().getProperties().put(ORSParameters.CoreLandmark.PREPARE + "done", true); + } + } //TODO Refactoring : This is a duplication with code in RoutingProfile and should probably be moved to a status keeping class. public final boolean isCHAvailable(String profileName) { @@ -586,16 +587,16 @@ public final boolean isCHAvailable(String profileName) { } public final boolean isLMAvailable(String profileName) { - return getLMPreparationHandler().isEnabled() && hasLMProfile(profileName); - } + return getLMPreparationHandler().isEnabled() && hasLMProfile(profileName); + } - public final boolean isCoreAvailable(String profileName) { - return getCorePreparationHandler().isEnabled() && hasCoreProfile(profileName); - } + public final boolean isCoreAvailable(String profileName) { + return getCorePreparationHandler().isEnabled() && hasCoreProfile(profileName); + } - public final boolean isFastIsochroneAvailable(RouteSearchContext searchContext, TravelRangeType travelRangeType) { - return eccentricity != null && eccentricity.isAvailable(ORSWeightingFactory.createIsochroneWeighting(searchContext, travelRangeType)); - } + public final boolean isFastIsochroneAvailable(RouteSearchContext searchContext, TravelRangeType travelRangeType) { + return eccentricity != null && eccentricity.isAvailable(ORSWeightingFactory.createIsochroneWeighting(searchContext, travelRangeType)); + } /** * Partitioning @@ -642,18 +643,19 @@ public Eccentricity getEccentricity() { public boolean isTrafficEnabled() { return GraphStorageUtils.getGraphExtension(getGraphHopperStorage(), TrafficGraphStorage.class) != null; } - public long getMemoryUsage() { - long mem = 0; - if (getLMPreparationHandler().isEnabled()) { - mem += getLMPreparationHandler().getPreparations().stream().mapToLong(lm -> lm.getLandmarkStorage().getCapacity()).sum(); - } - if (isCoreEnabled()) { - // core CH preparations are handled in ORSGraphHopperStorage.getCapacity() - mem += coreLMPreparationHandler.getPreparations().stream().mapToLong(lm -> lm.getLandmarkStorage().getCapacity()).sum(); - } - if (fastIsochroneFactory.isEnabled()) { - mem += fastIsochroneFactory.getCapacity(); - } - return mem + getGraphHopperStorage().getCapacity(); - } + + public long getMemoryUsage() { + long mem = 0; + if (getLMPreparationHandler().isEnabled()) { + mem += getLMPreparationHandler().getPreparations().stream().mapToLong(lm -> lm.getLandmarkStorage().getCapacity()).sum(); + } + if (isCoreEnabled()) { + // core CH preparations are handled in ORSGraphHopperStorage.getCapacity() + mem += coreLMPreparationHandler.getPreparations().stream().mapToLong(lm -> lm.getLandmarkStorage().getCapacity()).sum(); + } + if (fastIsochroneFactory.isEnabled()) { + mem += fastIsochroneFactory.getCapacity(); + } + return mem + getGraphHopperStorage().getCapacity(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopperStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopperStorage.java index 52626d08ab..211c1cb548 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopperStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphHopperStorage.java @@ -101,13 +101,13 @@ public ORSGraphHopperStorage create(long byteCount) { @Override public void loadExistingORS() { - coreEntries.forEach(cg -> { - if (!cg.chStore.loadExisting()) - throw new IllegalStateException("Cannot load " + cg); - }); - if (getExtensions() != null) { - getExtensions().loadExisting(); - } + coreEntries.forEach(cg -> { + if (!cg.chStore.loadExisting()) + throw new IllegalStateException("Cannot load " + cg); + }); + if (getExtensions() != null) { + getExtensions().loadExisting(); + } } public void flush() { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphStorageFactory.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphStorageFactory.java index ea2910b423..b40b134f4e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphStorageFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSGraphStorageFactory.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; @@ -24,37 +24,37 @@ public class ORSGraphStorageFactory implements GraphStorageFactory { - private static final Logger LOGGER = Logger.getLogger(ORSGraphStorageFactory.class.getName()); - - private final List graphStorageBuilders; - - public ORSGraphStorageFactory(List graphStorageBuilders) { - this.graphStorageBuilders = graphStorageBuilders; - } - - @Override - public GraphHopperStorage createStorage(GHDirectory dir, GraphHopper gh) { - EncodingManager encodingManager = gh.getEncodingManager(); - ArrayList graphExtensions = new ArrayList<>(); - - if (graphStorageBuilders != null) { - List iterateGraphStorageBuilders = new ArrayList<>(graphStorageBuilders); - for(GraphStorageBuilder builder : iterateGraphStorageBuilders) { - try { - GraphExtension ext = builder.init(gh); - if (ext != null) - graphExtensions.add(ext); - } catch(Exception ex) { - graphStorageBuilders.remove(builder); - LOGGER.error(ex); - } - } - } - - GraphHopperStorage ghs = new ORSGraphHopperStorage(dir, encodingManager, gh.hasElevation(), true, -1); - ExtendedStorageSequence extendedStorages = new ExtendedStorageSequence(graphExtensions); - extendedStorages.init(ghs.getBaseGraph(), dir); - ghs.setExtendedStorages(extendedStorages); - return ghs; - } + private static final Logger LOGGER = Logger.getLogger(ORSGraphStorageFactory.class.getName()); + + private final List graphStorageBuilders; + + public ORSGraphStorageFactory(List graphStorageBuilders) { + this.graphStorageBuilders = graphStorageBuilders; + } + + @Override + public GraphHopperStorage createStorage(GHDirectory dir, GraphHopper gh) { + EncodingManager encodingManager = gh.getEncodingManager(); + ArrayList graphExtensions = new ArrayList<>(); + + if (graphStorageBuilders != null) { + List iterateGraphStorageBuilders = new ArrayList<>(graphStorageBuilders); + for (GraphStorageBuilder builder : iterateGraphStorageBuilders) { + try { + GraphExtension ext = builder.init(gh); + if (ext != null) + graphExtensions.add(ext); + } catch (Exception ex) { + graphStorageBuilders.remove(builder); + LOGGER.error(ex); + } + } + } + + GraphHopperStorage ghs = new ORSGraphHopperStorage(dir, encodingManager, gh.hasElevation(), true, -1); + ExtendedStorageSequence extendedStorages = new ExtendedStorageSequence(graphExtensions); + extendedStorages.init(ghs.getBaseGraph(), dir); + ghs.setExtendedStorages(extendedStorages); + return ghs; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSOSMReader.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSOSMReader.java index 2551ca258c..3bfbd90487 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSOSMReader.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSOSMReader.java @@ -21,15 +21,11 @@ import com.graphhopper.storage.IntsRef; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.shapes.GHPoint; -import org.locationtech.jts.geom.Coordinate; import org.apache.log4j.Logger; import org.heigit.ors.routing.graphhopper.extensions.reader.osmfeatureprocessors.OSMFeatureFilter; import org.heigit.ors.routing.graphhopper.extensions.reader.osmfeatureprocessors.WheelchairWayFilter; -import org.heigit.ors.routing.graphhopper.extensions.storages.builders.BordersGraphStorageBuilder; -import org.heigit.ors.routing.graphhopper.extensions.storages.builders.GraphStorageBuilder; -import org.heigit.ors.routing.graphhopper.extensions.storages.builders.HereTrafficGraphStorageBuilder; -import org.heigit.ors.routing.graphhopper.extensions.storages.builders.RoadAccessRestrictionsGraphStorageBuilder; -import org.heigit.ors.routing.graphhopper.extensions.storages.builders.WheelchairGraphStorageBuilder; +import org.heigit.ors.routing.graphhopper.extensions.storages.builders.*; +import org.locationtech.jts.geom.Coordinate; import java.io.InvalidObjectException; import java.util.*; @@ -37,401 +33,398 @@ public class ORSOSMReader extends OSMReader { - private static final Logger LOGGER = Logger.getLogger(ORSOSMReader.class.getName()); + private static final Logger LOGGER = Logger.getLogger(ORSOSMReader.class.getName()); - private final GraphProcessContext procCntx; - private boolean processNodeTags; - private final OSMDataReaderContext readerCntx; + private final GraphProcessContext procCntx; + private boolean processNodeTags; + private final OSMDataReaderContext readerCntx; - private final HashMap> nodeTags = new HashMap<>(); + private final HashMap> nodeTags = new HashMap<>(); - private boolean processGeom = false; - private boolean processSimpleGeom = false; - private boolean processWholeGeom = false; - private boolean detachSidewalksFromRoad = false; + private boolean processGeom = false; + private boolean processSimpleGeom = false; + private boolean processWholeGeom = false; + private boolean detachSidewalksFromRoad = false; - private final boolean getElevationFromPreprocessedData; - private boolean getElevationFromPreprocessedDataErrorLogged = false; + private final boolean getElevationFromPreprocessedData; + private boolean getElevationFromPreprocessedDataErrorLogged = false; - private final List filtersToApply = new ArrayList<>(); + private final List filtersToApply = new ArrayList<>(); - private final HashSet extraTagKeys; + private final HashSet extraTagKeys; - public ORSOSMReader(GraphHopperStorage storage, GraphProcessContext procCntx) { - super(storage); + public ORSOSMReader(GraphHopperStorage storage, GraphProcessContext procCntx) { + super(storage); - enforce2D(); - this.procCntx = procCntx; - this.procCntx.initArrays(); - this.readerCntx = new OSMDataReaderContext(this); - getElevationFromPreprocessedData = procCntx.getElevationFromPreprocessedData(); + enforce2D(); + this.procCntx = procCntx; + this.procCntx.initArrays(); + this.readerCntx = new OSMDataReaderContext(this); + getElevationFromPreprocessedData = procCntx.getElevationFromPreprocessedData(); - initNodeTagsToStore(new HashSet<>(Arrays.asList("maxheight", "maxweight", "maxweight:hgv", "maxwidth", "maxlength", "maxlength:hgv", "maxaxleload"))); - extraTagKeys = new HashSet<>(); - // Look if we should do border processing - if so then we have to process the geometry - for(GraphStorageBuilder b : this.procCntx.getStorageBuilders()) { - if ( b instanceof BordersGraphStorageBuilder) { - this.processGeom = true; - } + initNodeTagsToStore(new HashSet<>(Arrays.asList("maxheight", "maxweight", "maxweight:hgv", "maxwidth", "maxlength", "maxlength:hgv", "maxaxleload"))); + extraTagKeys = new HashSet<>(); + // Look if we should do border processing - if so then we have to process the geometry + for (GraphStorageBuilder b : this.procCntx.getStorageBuilders()) { + if (b instanceof BordersGraphStorageBuilder) { + this.processGeom = true; + } - if (b instanceof HereTrafficGraphStorageBuilder) { - this.processGeom = true; - this.processWholeGeom = true; - } + if (b instanceof HereTrafficGraphStorageBuilder) { + this.processGeom = true; + this.processWholeGeom = true; + } - if ( b instanceof WheelchairGraphStorageBuilder) { - filtersToApply.add(new WheelchairWayFilter()); - this.processNodeTags = true; - this.detachSidewalksFromRoad = true; - this.processSimpleGeom = true; - extraTagKeys.add("kerb"); - extraTagKeys.add("kerb:both"); + if (b instanceof WheelchairGraphStorageBuilder) { + filtersToApply.add(new WheelchairWayFilter()); + this.processNodeTags = true; + this.detachSidewalksFromRoad = true; + this.processSimpleGeom = true; + extraTagKeys.add("kerb"); + extraTagKeys.add("kerb:both"); extraTagKeys.add("kerb:left"); extraTagKeys.add("kerb:right"); - extraTagKeys.add("kerb:height"); + extraTagKeys.add("kerb:height"); extraTagKeys.add("kerb:both:height"); extraTagKeys.add("kerb:left:height"); extraTagKeys.add("kerb:right:height"); - } - - if ( b instanceof RoadAccessRestrictionsGraphStorageBuilder) { - this.processNodeTags = true; - extraTagKeys.add("access"); - extraTagKeys.add("bicycle"); - extraTagKeys.add("foot"); - extraTagKeys.add("horse"); - extraTagKeys.add("motor_vehicle"); - extraTagKeys.add("motorcar"); - extraTagKeys.add("motorcycle"); - } - } - } - - @Override - public ReaderNode onProcessNode(ReaderNode node) { - // On OSM, nodes are seperate entities which are used to make up ways. So basically, a node is read before a - // way and if it has some properties that could affect routing, these properties need to be stored so that they - // can be accessed when it comes to using ways - if(processNodeTags && node.hasTags()) { - // Check each node and store the tags that are required - HashMap tagValues = new HashMap<>(); - Set nodeKeys = node.getTags().keySet(); - for(String key : nodeKeys) { - if(extraTagKeys.contains(key)) { - tagValues.put(key, node.getTag(key)); - } - } - - // Now if we have tag data, we need to store it - if(tagValues.size() > 0) { - nodeTags.put(node.getId(), tagValues); - } - } - return node; - } - - @Override - protected void processWay(ReaderWay way) { - // As a first step we need to check to see if we should try to split the way - if(this.detachSidewalksFromRoad) { - // If we are requesting to split sidewalks, then we need to create multiple ways from a single road - // For example, if a road way has been tagged as having sidewalks on both sides (sidewalk=both), then we - // need to create two ways - one for the left sidewalk and one for the right. The Graph Builder would then - // process these ways separately so that additional edges are created in the graph. - - for(OSMFeatureFilter filter : filtersToApply) { - try { - filter.assignFeatureForFiltering(way); - } catch (InvalidObjectException ioe) { - LOGGER.error("Invalid object for filtering - " + ioe.getMessage()); - } - - if(filter.accept()) { - // We can only perform the processing of the ways here and so we cannot delegate it to another object. - while (!filter.isWayProcessingComplete()) { - filter.prepareForProcessing(); - super.processWay(way); - } - } - } - - return; - - } - - // Normal processing - super.processWay(way); - } - - /** - * Method to be run against each way obtained from the data. If one of the storage builders needs geometry - * determined in the constructor then we need to get the geometry as well as the tags. - * Also we need to pass through any important tag values obtained from nodes through to the processing stage so - * that they can be evaluated. - * - * @param way The way object read from the OSM data (not including geometry) - */ - @Override - public void onProcessWay(ReaderWay way) { - - Map> tags = new HashMap<>(); - ArrayList coords = new ArrayList<>(); - ArrayList allCoordinates = new ArrayList<>(); - - if(processNodeTags) { - // If we are processing the node tags then we need to obtain the tags for nodes that are on the way. We - // should store the internal node id though rather than the osm node as during the edge processing, we - // do not know the osm node id - - LongArrayList osmNodeIds = way.getNodes(); - int size = osmNodeIds.size(); - - for(int i=0; i tagsForNode = nodeTags.get(id); - - if(tagsForNode != null) { - tags.put(internalId, nodeTags.get(id)); - } - } - } - - if(processGeom || processSimpleGeom) { - // We need to pass the geometry of the way aswell as the ReaderWay object - // This is slower so should only be done when needed - - // First we need to generate the geometry - LongArrayList osmNodeIds = new LongArrayList(); - LongArrayList allOsmNodes = way.getNodes(); - - if(allOsmNodes.size() > 1) { - if (processSimpleGeom) { - // We only want the start and end nodes - osmNodeIds.add(allOsmNodes.get(0)); - osmNodeIds.add(allOsmNodes.get(allOsmNodes.size()-1)); - } else { - // Process all nodes - osmNodeIds = allOsmNodes; - } - } - - if(osmNodeIds.size() > 1) { - - for (int i=0; i 0 || coords.size() > 1) { - // Use an overloaded method that allows the passing of parameters from this reader - procCntx.processWay(way, coords.toArray(new Coordinate[0]), tags, allCoordinates.toArray(new Coordinate[0])); - } else { - procCntx.processWay(way); - } - } - - /* The following two methods are not ideal, but due to a preprocessing stage of GH they are required if you want - * the geometry of the whole way. */ - - /** - * Find the latitude of the node with the given ID. It checks to see what type of node it is and then finds the - * latitude from the correct storage location. - * - * @param id Internal ID of the OSM node. - * @return Return the latitude as double. - */ - private double getLatitudeOfNode(int id, boolean onlyTower) { - // for speed, we only want to handle the geometry of tower nodes (those at junctions) - if (id == EMPTY_NODE) - return Double.NaN; - if (id < TOWER_NODE) { - // tower node - id = -id - 3; - return getNodeAccess().getLat(id); - } else if (id > -TOWER_NODE) { - // pillar node - // Do we want to return it if it is not a tower node? - if(onlyTower) { - return Double.NaN; - } else { - return pillarInfo.getLat(id); - } - } else { - // e.g. if id is not handled from preparse (e.g. was ignored via isInBounds) - return Double.NaN; - } - } - - /** - * Find the longitude of the node with the given ID. It checks to see what type of node it is and then finds the - * longitude from the correct storage location. - * - * @param id Internal ID of the OSM node - * @return Return the longitude as double - */ - private double getLongitudeOfNode(int id, boolean onlyTower) { - if (id == EMPTY_NODE) - return Double.NaN; - if (id < TOWER_NODE) { - // tower node - id = -id - 3; - return getNodeAccess().getLon(id); - } else if (id > -TOWER_NODE) { - // pillar node - // Do we want to return it if it is not a tower node? - if(onlyTower) { - return Double.NaN; - } else { - return pillarInfo.getLat(id); - } - } else { - // e.g. if id is not handled from preparse (e.g. was ignored via isInBounds) - return Double.NaN; - } - } - - /** - * Applies tags of nodes that lie on a way onto the way itself so that they are - * regarded in the following storage building process. E.g. a maxheight tag on a node will - * be treated like a maxheight tag on the way the node belongs to. - * - * @param way the way to process - */ - @Override - public void applyNodeTagsToWay(ReaderWay way){ - LongArrayList osmNodeIds = way.getNodes(); - int size = osmNodeIds.size(); - if (size > 2) { - // If it is a crossing then we need to apply any kerb tags to the way, but we need to make sure we keep the "worse" one - for (int i = 1; i < size-1; i++) { - long nodeId = osmNodeIds.get(i); - if (nodeHasTagsStored(nodeId)) { - java.util.Iterator> it = getStoredTagsForNode(nodeId).entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pairs = it.next(); - String key = pairs.getKey(); - String value = pairs.getValue().toString(); - way.setTag(key, value); - } - } - } - } - } - - - @Override - protected void onProcessEdge(ReaderWay way, EdgeIteratorState edge) { - try { - // Pass through the coordinates of the graph nodes - Coordinate baseCoord = new Coordinate( - getLongitudeOfNode(edge.getBaseNode(), false), - getLatitudeOfNode(edge.getBaseNode(), false) - ); - Coordinate adjCoordinate = new Coordinate( - getLongitudeOfNode(edge.getAdjNode(), false), - getLatitudeOfNode(edge.getAdjNode(), false) - ); - - procCntx.processEdge(way, edge, new Coordinate[] {baseCoord, adjCoordinate}); - } catch (Exception ex) { - LOGGER.warn(ex.getMessage() + ". Way id = " + way.getId()); - } - } - - @Override - protected boolean onCreateEdges(ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) - { - try - { - return procCntx.createEdges(readerCntx, way, osmNodeIds, wayFlags, createdEdges); - } - catch (Exception ex) { - LOGGER.warn(ex.getMessage() + ". Way id = " + way.getId()); - } - - return false; + } + + if (b instanceof RoadAccessRestrictionsGraphStorageBuilder) { + this.processNodeTags = true; + extraTagKeys.add("access"); + extraTagKeys.add("bicycle"); + extraTagKeys.add("foot"); + extraTagKeys.add("horse"); + extraTagKeys.add("motor_vehicle"); + extraTagKeys.add("motorcar"); + extraTagKeys.add("motorcycle"); + } + } + } + + @Override + public ReaderNode onProcessNode(ReaderNode node) { + // On OSM, nodes are seperate entities which are used to make up ways. So basically, a node is read before a + // way and if it has some properties that could affect routing, these properties need to be stored so that they + // can be accessed when it comes to using ways + if (processNodeTags && node.hasTags()) { + // Check each node and store the tags that are required + HashMap tagValues = new HashMap<>(); + Set nodeKeys = node.getTags().keySet(); + for (String key : nodeKeys) { + if (extraTagKeys.contains(key)) { + tagValues.put(key, node.getTag(key)); + } + } + + // Now if we have tag data, we need to store it + if (tagValues.size() > 0) { + nodeTags.put(node.getId(), tagValues); + } + } + return node; + } + + @Override + protected void processWay(ReaderWay way) { + // As a first step we need to check to see if we should try to split the way + if (this.detachSidewalksFromRoad) { + // If we are requesting to split sidewalks, then we need to create multiple ways from a single road + // For example, if a road way has been tagged as having sidewalks on both sides (sidewalk=both), then we + // need to create two ways - one for the left sidewalk and one for the right. The Graph Builder would then + // process these ways separately so that additional edges are created in the graph. + + for (OSMFeatureFilter filter : filtersToApply) { + try { + filter.assignFeatureForFiltering(way); + } catch (InvalidObjectException ioe) { + LOGGER.error("Invalid object for filtering - " + ioe.getMessage()); + } + + if (filter.accept()) { + // We can only perform the processing of the ways here and so we cannot delegate it to another object. + while (!filter.isWayProcessingComplete()) { + filter.prepareForProcessing(); + super.processWay(way); + } + } + } + + return; + + } + + // Normal processing + super.processWay(way); + } + + /** + * Method to be run against each way obtained from the data. If one of the storage builders needs geometry + * determined in the constructor then we need to get the geometry as well as the tags. + * Also we need to pass through any important tag values obtained from nodes through to the processing stage so + * that they can be evaluated. + * + * @param way The way object read from the OSM data (not including geometry) + */ + @Override + public void onProcessWay(ReaderWay way) { + + Map> tags = new HashMap<>(); + ArrayList coords = new ArrayList<>(); + ArrayList allCoordinates = new ArrayList<>(); + + if (processNodeTags) { + // If we are processing the node tags then we need to obtain the tags for nodes that are on the way. We + // should store the internal node id though rather than the osm node as during the edge processing, we + // do not know the osm node id + + LongArrayList osmNodeIds = way.getNodes(); + int size = osmNodeIds.size(); + + for (int i = 0; i < size; i++) { + // find the node + long id = osmNodeIds.get(i); + // replace the osm id with the internal id + int internalId = getNodeMap().get(id); + HashMap tagsForNode = nodeTags.get(id); + + if (tagsForNode != null) { + tags.put(internalId, nodeTags.get(id)); + } + } + } + + if (processGeom || processSimpleGeom) { + // We need to pass the geometry of the way aswell as the ReaderWay object + // This is slower so should only be done when needed + + // First we need to generate the geometry + LongArrayList osmNodeIds = new LongArrayList(); + LongArrayList allOsmNodes = way.getNodes(); + + if (allOsmNodes.size() > 1) { + if (processSimpleGeom) { + // We only want the start and end nodes + osmNodeIds.add(allOsmNodes.get(0)); + osmNodeIds.add(allOsmNodes.get(allOsmNodes.size() - 1)); + } else { + // Process all nodes + osmNodeIds = allOsmNodes; + } + } + + if (osmNodeIds.size() > 1) { + + for (int i = 0; i < osmNodeIds.size(); i++) { + int id = getNodeMap().get(osmNodeIds.get(i)); + try { + double lat = getLatitudeOfNode(id, false); + double lon = getLongitudeOfNode(id, false); + boolean validGeometry = !(lat == 0 || lon == 0 || Double.isNaN(lat) || Double.isNaN(lon)); + if (processWholeGeom && validGeometry) { + allCoordinates.add(new Coordinate(getTmpLongitude(id), getTmpLatitude(id))); + } + // Add the point to the line + // Check that we have a tower node + lat = getLatitudeOfNode(id, true); + lon = getLongitudeOfNode(id, true); + if (validGeometry) { + coords.add(new Coordinate(lon, lat)); + } + } catch (Exception e) { + LOGGER.error("Could not process node " + osmNodeIds.get(i)); + } + } + } + + } + + if (tags.size() > 0 || coords.size() > 1) { + // Use an overloaded method that allows the passing of parameters from this reader + procCntx.processWay(way, coords.toArray(new Coordinate[0]), tags, allCoordinates.toArray(new Coordinate[0])); + } else { + procCntx.processWay(way); + } + } + + /* The following two methods are not ideal, but due to a preprocessing stage of GH they are required if you want + * the geometry of the whole way. */ + + /** + * Find the latitude of the node with the given ID. It checks to see what type of node it is and then finds the + * latitude from the correct storage location. + * + * @param id Internal ID of the OSM node. + * @return Return the latitude as double. + */ + private double getLatitudeOfNode(int id, boolean onlyTower) { + // for speed, we only want to handle the geometry of tower nodes (those at junctions) + if (id == EMPTY_NODE) + return Double.NaN; + if (id < TOWER_NODE) { + // tower node + id = -id - 3; + return getNodeAccess().getLat(id); + } else if (id > -TOWER_NODE) { + // pillar node + // Do we want to return it if it is not a tower node? + if (onlyTower) { + return Double.NaN; + } else { + return pillarInfo.getLat(id); + } + } else { + // e.g. if id is not handled from preparse (e.g. was ignored via isInBounds) + return Double.NaN; + } + } + + /** + * Find the longitude of the node with the given ID. It checks to see what type of node it is and then finds the + * longitude from the correct storage location. + * + * @param id Internal ID of the OSM node + * @return Return the longitude as double + */ + private double getLongitudeOfNode(int id, boolean onlyTower) { + if (id == EMPTY_NODE) + return Double.NaN; + if (id < TOWER_NODE) { + // tower node + id = -id - 3; + return getNodeAccess().getLon(id); + } else if (id > -TOWER_NODE) { + // pillar node + // Do we want to return it if it is not a tower node? + if (onlyTower) { + return Double.NaN; + } else { + return pillarInfo.getLat(id); + } + } else { + // e.g. if id is not handled from preparse (e.g. was ignored via isInBounds) + return Double.NaN; + } + } + + /** + * Applies tags of nodes that lie on a way onto the way itself so that they are + * regarded in the following storage building process. E.g. a maxheight tag on a node will + * be treated like a maxheight tag on the way the node belongs to. + * + * @param way the way to process + */ + @Override + public void applyNodeTagsToWay(ReaderWay way) { + LongArrayList osmNodeIds = way.getNodes(); + int size = osmNodeIds.size(); + if (size > 2) { + // If it is a crossing then we need to apply any kerb tags to the way, but we need to make sure we keep the "worse" one + for (int i = 1; i < size - 1; i++) { + long nodeId = osmNodeIds.get(i); + if (nodeHasTagsStored(nodeId)) { + java.util.Iterator> it = getStoredTagsForNode(nodeId).entrySet().iterator(); + while (it.hasNext()) { + Map.Entry pairs = it.next(); + String key = pairs.getKey(); + String value = pairs.getValue().toString(); + way.setTag(key, value); + } + } + } + } + } + + + @Override + protected void onProcessEdge(ReaderWay way, EdgeIteratorState edge) { + try { + // Pass through the coordinates of the graph nodes + Coordinate baseCoord = new Coordinate( + getLongitudeOfNode(edge.getBaseNode(), false), + getLatitudeOfNode(edge.getBaseNode(), false) + ); + Coordinate adjCoordinate = new Coordinate( + getLongitudeOfNode(edge.getAdjNode(), false), + getLatitudeOfNode(edge.getAdjNode(), false) + ); + + procCntx.processEdge(way, edge, new Coordinate[]{baseCoord, adjCoordinate}); + } catch (Exception ex) { + LOGGER.warn(ex.getMessage() + ". Way id = " + way.getId()); + } + } + + @Override + protected boolean onCreateEdges(ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) { + try { + return procCntx.createEdges(readerCntx, way, osmNodeIds, wayFlags, createdEdges); + } catch (Exception ex) { + LOGGER.warn(ex.getMessage() + ". Way id = " + way.getId()); + } + + return false; + } + + @Override + protected void recordExactWayDistance(ReaderWay way, LongArrayList osmNodeIds) { + super.recordExactWayDistance(way, osmNodeIds); + + // compute exact way distance for ferries in order to improve travel time estimate, see #1037 + if (way.hasTag("route", "ferry", "shuttle_train")) { + double totalDist = 0d; + long nodeId = osmNodeIds.get(0); + int first = getNodeMap().get(nodeId); + double firstLat = getTmpLatitude(first); + double firstLon = getTmpLongitude(first); + double currLat = firstLat; + double currLon = firstLon; + double latSum = currLat; + double lonSum = currLon; + int sumCount = 1; + int len = osmNodeIds.size(); + for (int i = 1; i < len; i++) { + long nextNodeId = osmNodeIds.get(i); + int next = getNodeMap().get(nextNodeId); + double nextLat = getTmpLatitude(next); + double nextLon = getTmpLongitude(next); + if (!Double.isNaN(currLat) && !Double.isNaN(currLon) && !Double.isNaN(nextLat) && !Double.isNaN(nextLon)) { + latSum = latSum + nextLat; + lonSum = lonSum + nextLon; + sumCount++; + totalDist = totalDist + getDistanceCalc().calcDist(currLat, currLon, nextLat, nextLon); + + currLat = nextLat; + currLon = nextLon; + } + } + if (totalDist > 0) { + way.setTag("exact_distance", totalDist); + way.setTag("exact_center", new GHPoint(latSum / sumCount, lonSum / sumCount)); + } + } } @Override - protected void recordExactWayDistance(ReaderWay way, LongArrayList osmNodeIds) { - super.recordExactWayDistance(way, osmNodeIds); - - // compute exact way distance for ferries in order to improve travel time estimate, see #1037 - if (way.hasTag("route", "ferry", "shuttle_train")) { - double totalDist = 0d; - long nodeId = osmNodeIds.get(0); - int first = getNodeMap().get(nodeId); - double firstLat = getTmpLatitude(first); - double firstLon = getTmpLongitude(first); - double currLat = firstLat; - double currLon = firstLon; - double latSum = currLat; - double lonSum = currLon; - int sumCount = 1; - int len = osmNodeIds.size(); - for (int i = 1; i < len; i++) { - long nextNodeId = osmNodeIds.get(i); - int next = getNodeMap().get(nextNodeId); - double nextLat = getTmpLatitude(next); - double nextLon = getTmpLongitude(next); - if (!Double.isNaN(currLat) && !Double.isNaN(currLon) && !Double.isNaN(nextLat) && !Double.isNaN(nextLon)) { - latSum = latSum + nextLat; - lonSum = lonSum + nextLon; - sumCount++; - totalDist = totalDist + getDistanceCalc().calcDist(currLat, currLon, nextLat, nextLon); - - currLat = nextLat; - currLon = nextLon; - } - } - if (totalDist > 0) { - way.setTag("exact_distance", totalDist); - way.setTag("exact_center", new GHPoint(latSum / sumCount, lonSum / sumCount)); - } - } - } - - @Override - protected void finishedReading() { - super.finishedReading(); - procCntx.finish(); - } - - @Override - protected double getElevation(ReaderNode node) { - if (getElevationFromPreprocessedData) { - double ele = node.getEle(); - if (Double.isNaN(ele)) { - if (!getElevationFromPreprocessedDataErrorLogged) { - LOGGER.warn("elevation_preprocessed set to true in ors config, still found a Node with invalid ele tag! Set this flag only if you use a preprocessed pbf file! Node ID: " + node.getId()); - getElevationFromPreprocessedDataErrorLogged = true; - } - ele = 0; - } - return ele; - } - return super.getElevation(node); - } + protected void finishedReading() { + super.finishedReading(); + procCntx.finish(); + } + + @Override + protected double getElevation(ReaderNode node) { + if (getElevationFromPreprocessedData) { + double ele = node.getEle(); + if (Double.isNaN(ele)) { + if (!getElevationFromPreprocessedDataErrorLogged) { + LOGGER.warn("elevation_preprocessed set to true in ors config, still found a Node with invalid ele tag! Set this flag only if you use a preprocessed pbf file! Node ID: " + node.getId()); + getElevationFromPreprocessedDataErrorLogged = true; + } + ele = 0; + } + return ele; + } + return super.getElevation(node); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSRouter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSRouter.java index 723823726f..155fcf40bd 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSRouter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSRouter.java @@ -144,7 +144,7 @@ private RoutingAlgorithmFactory getRoutingAlgorithmFactory(RoutingCHGraph chGrap } } - if (lms==null) { + if (lms == null) { return new CoreRoutingAlgorithmFactory(chGraph, queryGraph); } else { return new CoreRoutingAlgorithmFactory(chGraph, queryGraph, lms); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSWeightingFactory.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSWeightingFactory.java index 9b9c79dc39..c192cc6088 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSWeightingFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/ORSWeightingFactory.java @@ -22,7 +22,6 @@ import org.heigit.ors.routing.traffic.RoutingTrafficSpeedCalculator; import java.time.Instant; -import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; @@ -80,7 +79,7 @@ public Weighting createWeighting(Profile profile, PMap requestHints, boolean dis weightingStr = toLowerCase(profile.getWeighting()); // ORS-GH MOD END if (weightingStr.isEmpty()) - throw new IllegalArgumentException("You need to specify a weighting"); + throw new IllegalArgumentException("You need to specify a weighting"); Weighting weighting = null; if ("shortest".equalsIgnoreCase(weightingStr)) { @@ -131,15 +130,12 @@ public Weighting createIsochroneWeighting(Profile profile, PMap requestHints) { //Isochrones only support fastest or shortest as no path is found. //CalcWeight must be directly comparable to the isochrone limit - if ("shortest".equalsIgnoreCase(weightingStr)) - { + if ("shortest".equalsIgnoreCase(weightingStr)) { result = new ShortestWeighting(encoder); - } - else if ("fastest".equalsIgnoreCase(weightingStr) + } else if ("fastest".equalsIgnoreCase(weightingStr) || "priority".equalsIgnoreCase(weightingStr) || "recommended_pref".equalsIgnoreCase(weightingStr) - || "recommended".equalsIgnoreCase(weightingStr)) - { + || "recommended".equalsIgnoreCase(weightingStr)) { result = new FastestWeighting(encoder, requestHints); } @@ -181,13 +177,11 @@ protected boolean isRequestTimeDependent(PMap hints) { protected Weighting applySoftWeightings(PMap hints, FlagEncoder encoder, Weighting weighting) { // TODO (cleanup): The term "custom_weighting" is easily confused with GH's custom // weighting and should be renamed. - if (hints.getBool("custom_weightings", false)) - { + if (hints.getBool("custom_weightings", false)) { Map map = hints.toMap(); List weightingNames = new ArrayList<>(); - for (Map.Entry kv : map.entrySet()) - { + for (Map.Entry kv : map.entrySet()) { String name = ProfileWeighting.decodeName(kv.getKey()); if (name != null && !weightingNames.contains(name)) weightingNames.add(name); @@ -221,15 +215,13 @@ protected Weighting applySoftWeightings(PMap hints, FlagEncoder encoder, Weighti return weighting; } - private PMap getWeightingProps(String weightingName, Map map) - { + private PMap getWeightingProps(String weightingName, Map map) { PMap res = new PMap(); String prefix = "weighting_#" + weightingName; int n = prefix.length(); - for (Map.Entry kv : map.entrySet()) - { + for (Map.Entry kv : map.entrySet()) { String name = kv.getKey(); int p = name.indexOf(prefix); if (p >= 0) @@ -250,7 +242,7 @@ private static void addTrafficSpeedCalculator(Weighting weighting, GraphHopperSt if (trafficGraphStorage != null) { RoutingTrafficSpeedCalculator routingTrafficSpeedCalculator = new RoutingTrafficSpeedCalculator(weighting.getSpeedCalculator(), ghStorage, weighting.getFlagEncoder()); - if (time!=null) { + if (time != null) { //Use fixed time zone because original implementation was for German traffic data ZonedDateTime zdt = time.atZone(ZoneId.of("Europe/Berlin")); routingTrafficSpeedCalculator.setZonedDateTime(zdt); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMDataReaderContext.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMDataReaderContext.java index f2162b2fa8..d631fc2bd9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMDataReaderContext.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMDataReaderContext.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; @@ -23,29 +23,29 @@ public class OSMDataReaderContext implements DataReaderContext { - private final OSMReader osmReader; - - public OSMDataReaderContext(OSMReader osmReader) { - this.osmReader = osmReader; - } - - @Override - public LongIntMap getNodeMap() { - return osmReader.getNodeMap(); - } - - @Override - public double getNodeLongitude(int nodeId) { - return osmReader.getTmpLongitude(nodeId); - } - - @Override - public double getNodeLatitude(int nodeId) { - return osmReader.getTmpLatitude(nodeId); - } - - @Override - public Collection addWay(LongIndexedContainer subgraphNodes, IntsRef wayFlags, long wayId) { - return osmReader.addOSMWay(subgraphNodes, wayFlags, wayId); - } + private final OSMReader osmReader; + + public OSMDataReaderContext(OSMReader osmReader) { + this.osmReader = osmReader; + } + + @Override + public LongIntMap getNodeMap() { + return osmReader.getNodeMap(); + } + + @Override + public double getNodeLongitude(int nodeId) { + return osmReader.getTmpLongitude(nodeId); + } + + @Override + public double getNodeLatitude(int nodeId) { + return osmReader.getTmpLatitude(nodeId); + } + + @Override + public Collection addWay(LongIndexedContainer subgraphNodes, IntsRef wayFlags, long wayId) { + return osmReader.addOSMWay(subgraphNodes, wayFlags, wayId); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMTags.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMTags.java index 811ae686e4..33a532137a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMTags.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/OSMTags.java @@ -16,14 +16,17 @@ package org.heigit.ors.routing.graphhopper.extensions; public class OSMTags { - private OSMTags() {} + private OSMTags() { + } public static class Keys { - private Keys() {} + private Keys() { + } + public static final String HIGHWAY = "highway"; public static final String SIDEWALK = "sidewalk"; public static final String ROUTE = "route"; - public static final String FOOT = "foot"; + public static final String FOOT = "foot"; public static final String SAC_SCALE = "sac_scale"; public static final String FORD = "ford"; public static final String MOTOR_ROAD = "motorroad"; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/SurfaceType.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/SurfaceType.java index c0146153ed..c75cfe67af 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/SurfaceType.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/SurfaceType.java @@ -1,89 +1,90 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; public class SurfaceType { - public static final int UNKNOWN = 0; - public static final int PAVED = 1; - public static final int UNPAVED = 2; - public static final int ASPHALT = 3; - public static final int CONCRETE = 4; - public static final int COBBLESTONE = 5; - public static final int METAL = 6; - public static final int WOOD = 7; - public static final int COMPACTED_GRAVEL = 8; - public static final int FINE_GRAVEL = 9; - public static final int GRAVEL = 10; - public static final int DIRT = 11; - public static final int GROUND = 12; - public static final int ICE = 13; - public static final int PAVING_STONE = 14; - public static final int SAND = 15; - public static final int WOODCHIPS = 16; - public static final int GRASS = 17; - public static final int GRASS_PAVER = 18; + public static final int UNKNOWN = 0; + public static final int PAVED = 1; + public static final int UNPAVED = 2; + public static final int ASPHALT = 3; + public static final int CONCRETE = 4; + public static final int COBBLESTONE = 5; + public static final int METAL = 6; + public static final int WOOD = 7; + public static final int COMPACTED_GRAVEL = 8; + public static final int FINE_GRAVEL = 9; + public static final int GRAVEL = 10; + public static final int DIRT = 11; + public static final int GROUND = 12; + public static final int ICE = 13; + public static final int PAVING_STONE = 14; + public static final int SAND = 15; + public static final int WOODCHIPS = 16; + public static final int GRASS = 17; + public static final int GRASS_PAVER = 18; - private SurfaceType() {} + private SurfaceType() { + } - public static int getFromString(String surface) { - - if (surface.contains(";")) - surface = surface.split(";")[0]; - - if ("paved".equalsIgnoreCase(surface)) { - return SurfaceType.PAVED; - } else if ("unpaved".equalsIgnoreCase(surface)) { - return SurfaceType.UNPAVED; - } else if ("asphalt".equalsIgnoreCase(surface)) { - return SurfaceType.ASPHALT; - } else if ("concrete".equalsIgnoreCase(surface) || "concrete:lanes".equalsIgnoreCase(surface) - || "concrete:plates".equalsIgnoreCase(surface)) { - return SurfaceType.CONCRETE; - } else if ("paving_stones".equalsIgnoreCase(surface) || "paving_stones:20".equalsIgnoreCase(surface) || "paving_stones:30".equalsIgnoreCase(surface) || "paving_stones:50".equalsIgnoreCase(surface) || "paved_stones".equalsIgnoreCase(surface)) { - return SurfaceType.PAVING_STONE; - } else if ("cobblestone:flattened".equalsIgnoreCase(surface) - || "sett".equalsIgnoreCase(surface)) { - return SurfaceType.PAVING_STONE; - } else if ("cobblestone".equalsIgnoreCase(surface)) { - return SurfaceType.COBBLESTONE; - } else if ("metal".equalsIgnoreCase(surface)) { - return SurfaceType.METAL; - } else if ("wood".equalsIgnoreCase(surface)) { - return SurfaceType.WOOD; - } else if ("compacted".equalsIgnoreCase(surface) || "pebblestone".equalsIgnoreCase(surface)) { - return SurfaceType.COMPACTED_GRAVEL; - } else if ("fine_gravel".equalsIgnoreCase(surface)) { - return SurfaceType.FINE_GRAVEL; - } else if ("gravel".equalsIgnoreCase(surface)) { - return SurfaceType.GRAVEL; - } else if ("dirt".equalsIgnoreCase(surface)) { - return SurfaceType.DIRT; - } else if ("ground".equalsIgnoreCase(surface) || "earth".equalsIgnoreCase(surface) - || "mud".equalsIgnoreCase(surface)) { - return SurfaceType.GROUND; - } else if ("ice".equalsIgnoreCase(surface) || "snow".equalsIgnoreCase(surface)) { - return SurfaceType.ICE; - } else if ("sand".equalsIgnoreCase(surface)) { - return SurfaceType.SAND; - } else if ("woodchips".equalsIgnoreCase(surface)) { - return SurfaceType.WOODCHIPS; - } else if ("grass".equalsIgnoreCase(surface)) { - return SurfaceType.GRASS; - } else if ("grass_paver".equalsIgnoreCase(surface)) { - return SurfaceType.GRASS_PAVER; - } + public static int getFromString(String surface) { - return SurfaceType.UNKNOWN; - } + if (surface.contains(";")) + surface = surface.split(";")[0]; + + if ("paved".equalsIgnoreCase(surface)) { + return SurfaceType.PAVED; + } else if ("unpaved".equalsIgnoreCase(surface)) { + return SurfaceType.UNPAVED; + } else if ("asphalt".equalsIgnoreCase(surface)) { + return SurfaceType.ASPHALT; + } else if ("concrete".equalsIgnoreCase(surface) || "concrete:lanes".equalsIgnoreCase(surface) + || "concrete:plates".equalsIgnoreCase(surface)) { + return SurfaceType.CONCRETE; + } else if ("paving_stones".equalsIgnoreCase(surface) || "paving_stones:20".equalsIgnoreCase(surface) || "paving_stones:30".equalsIgnoreCase(surface) || "paving_stones:50".equalsIgnoreCase(surface) || "paved_stones".equalsIgnoreCase(surface)) { + return SurfaceType.PAVING_STONE; + } else if ("cobblestone:flattened".equalsIgnoreCase(surface) + || "sett".equalsIgnoreCase(surface)) { + return SurfaceType.PAVING_STONE; + } else if ("cobblestone".equalsIgnoreCase(surface)) { + return SurfaceType.COBBLESTONE; + } else if ("metal".equalsIgnoreCase(surface)) { + return SurfaceType.METAL; + } else if ("wood".equalsIgnoreCase(surface)) { + return SurfaceType.WOOD; + } else if ("compacted".equalsIgnoreCase(surface) || "pebblestone".equalsIgnoreCase(surface)) { + return SurfaceType.COMPACTED_GRAVEL; + } else if ("fine_gravel".equalsIgnoreCase(surface)) { + return SurfaceType.FINE_GRAVEL; + } else if ("gravel".equalsIgnoreCase(surface)) { + return SurfaceType.GRAVEL; + } else if ("dirt".equalsIgnoreCase(surface)) { + return SurfaceType.DIRT; + } else if ("ground".equalsIgnoreCase(surface) || "earth".equalsIgnoreCase(surface) + || "mud".equalsIgnoreCase(surface)) { + return SurfaceType.GROUND; + } else if ("ice".equalsIgnoreCase(surface) || "snow".equalsIgnoreCase(surface)) { + return SurfaceType.ICE; + } else if ("sand".equalsIgnoreCase(surface)) { + return SurfaceType.SAND; + } else if ("woodchips".equalsIgnoreCase(surface)) { + return SurfaceType.WOODCHIPS; + } else if ("grass".equalsIgnoreCase(surface)) { + return SurfaceType.GRASS; + } else if ("grass_paver".equalsIgnoreCase(surface)) { + return SurfaceType.GRASS_PAVER; + } + + return SurfaceType.UNKNOWN; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/TollwayType.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/TollwayType.java index d3c620dba0..a4b5d8a1b0 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/TollwayType.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/TollwayType.java @@ -1,58 +1,59 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; public class TollwayType { - public static final int NONE = 0; + public static final int NONE = 0; - // https://en.wikipedia.org/wiki/Vehicle_category + // https://en.wikipedia.org/wiki/Vehicle_category - public static final int M1 = 1; - public static final int M2 = 2; - public static final int M3 = 4; - public static final int M = M1 | M2 | M3; + public static final int M1 = 1; + public static final int M2 = 2; + public static final int M3 = 4; + public static final int M = M1 | M2 | M3; - public static final int N1 = 8; - public static final int N2 = 16; - public static final int N3 = 32; + public static final int N1 = 8; + public static final int N2 = 16; + public static final int N3 = 32; - public static final int N = N1 | N2 | N3; + public static final int N = N1 | N2 | N3; - public static final int GENERAL = M | N; + public static final int GENERAL = M | N; - // OSM classification - public static final int MOTORCAR = M1; - public static final int GOODS = N1; - public static final int HGV = N2 | N3; + // OSM classification + public static final int MOTORCAR = M1; + public static final int GOODS = N1; + public static final int HGV = N2 | N3; - private TollwayType() {} + private TollwayType() { + } public static boolean isSet(int flag, int value) { return (flag & value) == flag; } - public static boolean isType(int flag, int value) { - return (flag & value) != 0; - } + public static boolean isType(int flag, int value) { + return (flag & value) != 0; + } - public static boolean isMType(int value) { - return isType(M, value); - } + public static boolean isMType(int value) { + return isType(M, value); + } - public static boolean isNType(int value) { - return isType(N, value); - } + public static boolean isNType(int value) { + return isType(N, value); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleDimensionRestrictions.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleDimensionRestrictions.java index 18cf5089df..511bbab3a1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleDimensionRestrictions.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleDimensionRestrictions.java @@ -1,25 +1,26 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; public class VehicleDimensionRestrictions { - public static final int MAX_HEIGHT = 0; - public static final int MAX_WEIGHT = 1; - public static final int MAX_WIDTH = 2; - public static final int MAX_LENGTH = 3; - public static final int MAX_AXLE_LOAD = 4; - public static final int COUNT = 5; + public static final int MAX_HEIGHT = 0; + public static final int MAX_WEIGHT = 1; + public static final int MAX_WIDTH = 2; + public static final int MAX_LENGTH = 3; + public static final int MAX_AXLE_LOAD = 4; + public static final int COUNT = 5; - private VehicleDimensionRestrictions() {} + private VehicleDimensionRestrictions() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleLoadCharacteristicsFlags.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleLoadCharacteristicsFlags.java index 4e83c4a426..35f4c73573 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleLoadCharacteristicsFlags.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/VehicleLoadCharacteristicsFlags.java @@ -1,34 +1,32 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; public class VehicleLoadCharacteristicsFlags { - public static final int NONE = 0; - public static final int HAZMAT = 1; - - public int getFromString(String value) - { - int res = NONE; - - if ("hazmat".equalsIgnoreCase(value)) - res |= HAZMAT; - - return res; - } - - public static boolean isSet(int characteristics, int value) - { - return (characteristics & value) == value; - } + public static final int NONE = 0; + public static final int HAZMAT = 1; + + public int getFromString(String value) { + int res = NONE; + + if ("hazmat".equalsIgnoreCase(value)) + res |= HAZMAT; + + return res; + } + + public static boolean isSet(int characteristics, int value) { + return (characteristics & value) == value; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WayType.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WayType.java index 03ba1cb05d..6d9b376ce6 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WayType.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WayType.java @@ -1,67 +1,68 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions; public class WayType { - public static final int UNKNOWN = 0; - public static final int STATE_ROAD = 1; - public static final int ROAD = 2; - public static final int STREET = 3; - public static final int PATH = 4; - public static final int TRACK = 5; - public static final int CYCLEWAY = 6; - public static final int FOOTWAY = 7; - public static final int STEPS = 8; - public static final int FERRY = 9; - public static final int CONSTRUCTION = 10; + public static final int UNKNOWN = 0; + public static final int STATE_ROAD = 1; + public static final int ROAD = 2; + public static final int STREET = 3; + public static final int PATH = 4; + public static final int TRACK = 5; + public static final int CYCLEWAY = 6; + public static final int FOOTWAY = 7; + public static final int STEPS = 8; + public static final int FERRY = 9; + public static final int CONSTRUCTION = 10; - private WayType() {} + private WayType() { + } - public static int getFromString(String highway) { - if ("primary".equalsIgnoreCase(highway) - || "primary_link".equalsIgnoreCase(highway) - || "motorway".equalsIgnoreCase(highway) - || "motorway_link".equalsIgnoreCase(highway) - || "trunk".equalsIgnoreCase(highway) - || "trunk_link".equalsIgnoreCase(highway)) { - return WayType.STATE_ROAD; - } else if ("secondary".equalsIgnoreCase(highway) - || "secondary_link".equalsIgnoreCase(highway) - || "tertiary".equalsIgnoreCase(highway) - || "tertiary_link".equalsIgnoreCase(highway) - || "road".equalsIgnoreCase(highway) - || "unclassified".equalsIgnoreCase(highway)) { - return WayType.ROAD; - } else if ("residential".equalsIgnoreCase(highway) - || "service".equalsIgnoreCase(highway) - || "living_street".equalsIgnoreCase(highway)) { - return WayType.STREET; - } else if ("path".equalsIgnoreCase(highway)) { - return WayType.PATH; - } else if ("track".equalsIgnoreCase(highway)) { - return WayType.TRACK; - } else if ("cycleway".equalsIgnoreCase(highway)) { - return WayType.CYCLEWAY; - } else if ("footway".equalsIgnoreCase(highway) - || "pedestrian".equalsIgnoreCase(highway) - || "crossing".equalsIgnoreCase(highway)) { - return WayType.FOOTWAY; - } else if ("steps".equalsIgnoreCase(highway)) { - return WayType.STEPS; - } else if ("construction".equalsIgnoreCase(highway)) { - return WayType.CONSTRUCTION; - } - return WayType.UNKNOWN; - } + public static int getFromString(String highway) { + if ("primary".equalsIgnoreCase(highway) + || "primary_link".equalsIgnoreCase(highway) + || "motorway".equalsIgnoreCase(highway) + || "motorway_link".equalsIgnoreCase(highway) + || "trunk".equalsIgnoreCase(highway) + || "trunk_link".equalsIgnoreCase(highway)) { + return WayType.STATE_ROAD; + } else if ("secondary".equalsIgnoreCase(highway) + || "secondary_link".equalsIgnoreCase(highway) + || "tertiary".equalsIgnoreCase(highway) + || "tertiary_link".equalsIgnoreCase(highway) + || "road".equalsIgnoreCase(highway) + || "unclassified".equalsIgnoreCase(highway)) { + return WayType.ROAD; + } else if ("residential".equalsIgnoreCase(highway) + || "service".equalsIgnoreCase(highway) + || "living_street".equalsIgnoreCase(highway)) { + return WayType.STREET; + } else if ("path".equalsIgnoreCase(highway)) { + return WayType.PATH; + } else if ("track".equalsIgnoreCase(highway)) { + return WayType.TRACK; + } else if ("cycleway".equalsIgnoreCase(highway)) { + return WayType.CYCLEWAY; + } else if ("footway".equalsIgnoreCase(highway) + || "pedestrian".equalsIgnoreCase(highway) + || "crossing".equalsIgnoreCase(highway)) { + return WayType.FOOTWAY; + } else if ("steps".equalsIgnoreCase(highway)) { + return WayType.STEPS; + } else if ("construction".equalsIgnoreCase(highway)) { + return WayType.CONSTRUCTION; + } + return WayType.UNKNOWN; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WheelchairTypesEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WheelchairTypesEncoder.java index f633f2a79f..4d53189576 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WheelchairTypesEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/WheelchairTypesEncoder.java @@ -20,45 +20,46 @@ public final class WheelchairTypesEncoder { - // surface - // ======= - // http://wiki.openstreetmap.org/wiki/DE:Key:surface - // http://wiki.openstreetmap.org/wiki/Wheelchair_routing#Path_properties.2C_in_general - // http://wiki.openstreetmap.org/wiki/DE:Wheelchair_routing#Weg_Eigenschaften_allgemein - // 26 Werte (5 bits) - private static final int SURFACE_PAVED = 1; - private static final int SURFACE_ASPHALT = 2; - private static final int SURFACE_CONCRETE = 3; - private static final int SURFACE_PAVING_STONES = 4; - private static final int SURFACE_CONCRETE_PLATES = 5; - private static final int SURFACE_COBBLESTONE_FLATTENED = 6; - private static final int SURFACE_CONCRETE_LANES = 7; - private static final int SURFACE_COBBLESTONE = 8; - - // http://wiki.openstreetmap.org/wiki/Key:surface - // these might still be "feasable" for experienced wheelchair users - private static final int SURFACE_UNPAVED = 9; - private static final int SURFACE_UNPAVED_FINE_GRAVEL = 10; - private static final int SURFACE_UNPAVED_COMPACTED = 11; - private static final int SURFACE_UNPAVED_METAL = 12; - private static final int SURFACE_UNPAVED_ICE = 13; - private static final int SURFACE_UNPAVED_GRASS_PAVER = 14; - private static final int SURFACE_UNPAVED_SAND = 15; - // these are probably not "feasible" for wheelchair users - private static final int SURFACE_UNPAVED_DIRT = 16; - private static final int SURFACE_UNPAVED_EARTH = 17; - private static final int SURFACE_UNPAVED_GRASS = 18; - private static final int SURFACE_UNPAVED_GRAVEL = 19; - private static final int SURFACE_UNPAVED_GROUND = 20; - private static final int SURFACE_UNPAVED_MUD = 21; - private static final int SURFACE_UNPAVED_PEBBLESTONE = 22; - private static final int SURFACE_UNPAVED_SALT = 23; - private static final int SURFACE_UNPAVED_SNOW = 24; - private static final int SURFACE_UNPAVED_WOOD = 25; - private static final int SURFACE_UNPAVED_WOODCHIPS = 26; - - - private static final Map SURFACE_MAP = new HashMap<>(); + // surface + // ======= + // http://wiki.openstreetmap.org/wiki/DE:Key:surface + // http://wiki.openstreetmap.org/wiki/Wheelchair_routing#Path_properties.2C_in_general + // http://wiki.openstreetmap.org/wiki/DE:Wheelchair_routing#Weg_Eigenschaften_allgemein + // 26 Werte (5 bits) + private static final int SURFACE_PAVED = 1; + private static final int SURFACE_ASPHALT = 2; + private static final int SURFACE_CONCRETE = 3; + private static final int SURFACE_PAVING_STONES = 4; + private static final int SURFACE_CONCRETE_PLATES = 5; + private static final int SURFACE_COBBLESTONE_FLATTENED = 6; + private static final int SURFACE_CONCRETE_LANES = 7; + private static final int SURFACE_COBBLESTONE = 8; + + // http://wiki.openstreetmap.org/wiki/Key:surface + // these might still be "feasable" for experienced wheelchair users + private static final int SURFACE_UNPAVED = 9; + private static final int SURFACE_UNPAVED_FINE_GRAVEL = 10; + private static final int SURFACE_UNPAVED_COMPACTED = 11; + private static final int SURFACE_UNPAVED_METAL = 12; + private static final int SURFACE_UNPAVED_ICE = 13; + private static final int SURFACE_UNPAVED_GRASS_PAVER = 14; + private static final int SURFACE_UNPAVED_SAND = 15; + // these are probably not "feasible" for wheelchair users + private static final int SURFACE_UNPAVED_DIRT = 16; + private static final int SURFACE_UNPAVED_EARTH = 17; + private static final int SURFACE_UNPAVED_GRASS = 18; + private static final int SURFACE_UNPAVED_GRAVEL = 19; + private static final int SURFACE_UNPAVED_GROUND = 20; + private static final int SURFACE_UNPAVED_MUD = 21; + private static final int SURFACE_UNPAVED_PEBBLESTONE = 22; + private static final int SURFACE_UNPAVED_SALT = 23; + private static final int SURFACE_UNPAVED_SNOW = 24; + private static final int SURFACE_UNPAVED_WOOD = 25; + private static final int SURFACE_UNPAVED_WOODCHIPS = 26; + + + private static final Map SURFACE_MAP = new HashMap<>(); + static { SURFACE_MAP.put("paved", SURFACE_PAVED); SURFACE_MAP.put("asphalt", SURFACE_ASPHALT); @@ -92,10 +93,10 @@ public final class WheelchairTypesEncoder { // smoothness // ========== - // http://wiki.openstreetmap.org/wiki/DE:Key:smoothness - // http://wiki.openstreetmap.org/wiki/Wheelchair_routing#Path_properties.2C_in_general - // http://wiki.openstreetmap.org/wiki/DE:Wheelchair_routing#Weg_Eigenschaften_allgemein1 - // 8 Werte (4 Bits) + // http://wiki.openstreetmap.org/wiki/DE:Key:smoothness + // http://wiki.openstreetmap.org/wiki/Wheelchair_routing#Path_properties.2C_in_general + // http://wiki.openstreetmap.org/wiki/DE:Wheelchair_routing#Weg_Eigenschaften_allgemein1 + // 8 Werte (4 Bits) private static final int SMOOTHNESS_EXCELLENT = 1; private static final int SMOOTHNESS_GOOD = 2; private static final int SMOOTHNESS_INTERMEDIATE = 3; @@ -105,7 +106,8 @@ public final class WheelchairTypesEncoder { private static final int SMOOTHNESS_VERY_HORRIBLE = 7; private static final int SMOOTHNESS_IMPASSABLE = 8; - private static final HashMap SMOOTHNESS_MAP = new HashMap<>(); + private static final HashMap SMOOTHNESS_MAP = new HashMap<>(); + static { SMOOTHNESS_MAP.put("excellent", SMOOTHNESS_EXCELLENT); SMOOTHNESS_MAP.put("good", SMOOTHNESS_GOOD); @@ -119,19 +121,20 @@ public final class WheelchairTypesEncoder { // tracktype - // ========= - // http://wiki.openstreetmap.org/wiki/Key:tracktype - // http://wiki.openstreetmap.org/wiki/Wheelchair_routing#Path_properties.2C_in_general - // http://wiki.openstreetmap.org/wiki/DE:Wheelchair_routing#Weg_Eigenschaften_allgemein - // 5 Werte (3 Bits) + // ========= + // http://wiki.openstreetmap.org/wiki/Key:tracktype + // http://wiki.openstreetmap.org/wiki/Wheelchair_routing#Path_properties.2C_in_general + // http://wiki.openstreetmap.org/wiki/DE:Wheelchair_routing#Weg_Eigenschaften_allgemein + // 5 Werte (3 Bits) private static final int TRACKTYPE_GRADE1 = 1; private static final int TRACKTYPE_GRADE2 = 2; private static final int TRACKTYPE_GRADE3 = 3; private static final int TRACKTYPE_GRADE4 = 4; private static final int TRACKTYPE_GRADE5 = 5; - private static final HashMap TRACKTYPE_MAP = new HashMap<>(); - static { + private static final HashMap TRACKTYPE_MAP = new HashMap<>(); + + static { TRACKTYPE_MAP.put("grade1", TRACKTYPE_GRADE1); TRACKTYPE_MAP.put("grade2", TRACKTYPE_GRADE2); TRACKTYPE_MAP.put("grade3", TRACKTYPE_GRADE3); @@ -139,13 +142,14 @@ public final class WheelchairTypesEncoder { TRACKTYPE_MAP.put("grade5", TRACKTYPE_GRADE5); } - private WheelchairTypesEncoder() {} + private WheelchairTypesEncoder() { + } public static int getSurfaceType(String value) { - if ("any".equalsIgnoreCase(value)) - return 0; - else - return SURFACE_MAP.getOrDefault(value, -1); + if ("any".equalsIgnoreCase(value)) + return 0; + else + return SURFACE_MAP.getOrDefault(value, -1); } public static int getEncodedType(WheelchairAttributes.Attribute attribute, String value) throws Exception { @@ -158,11 +162,11 @@ public static int getEncodedType(WheelchairAttributes.Attribute attribute, Strin } public static int getSmoothnessType(APIEnums.SmoothnessTypes smoothnessType) { - return SMOOTHNESS_MAP.getOrDefault(smoothnessType.toString(), -1); + return SMOOTHNESS_MAP.getOrDefault(smoothnessType.toString(), -1); } public static int getTrackType(String value) { - return TRACKTYPE_MAP.getOrDefault(value, -1); + return TRACKTYPE_MAP.getOrDefault(value, -1); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/AbstractCoreRoutingAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/AbstractCoreRoutingAlgorithm.java index 6c08989797..434f1dbe34 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/AbstractCoreRoutingAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/AbstractCoreRoutingAlgorithm.java @@ -13,12 +13,16 @@ */ package org.heigit.ors.routing.graphhopper.extensions.core; -import com.graphhopper.routing.*; +import com.graphhopper.routing.AbstractRoutingAlgorithm; +import com.graphhopper.routing.Path; +import com.graphhopper.routing.RoutingAlgorithm; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.ch.CHEntry; import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.Weighting; -import com.graphhopper.storage.*; -import com.graphhopper.routing.SPTEntry; +import com.graphhopper.storage.RoutingCHEdgeExplorer; +import com.graphhopper.storage.RoutingCHEdgeIteratorState; +import com.graphhopper.storage.RoutingCHGraph; import com.graphhopper.util.EdgeIterator; import com.graphhopper.util.EdgeIteratorState; import org.heigit.ors.routing.graphhopper.extensions.util.GraphUtils; @@ -45,7 +49,8 @@ public abstract class AbstractCoreRoutingAlgorithm extends AbstractRoutingAlgori boolean inCore; - @Deprecated protected Weighting turnWeighting; + @Deprecated + protected Weighting turnWeighting; protected boolean hasTurnWeighting; protected boolean approximate = false; @@ -54,7 +59,7 @@ protected AbstractCoreRoutingAlgorithm(RoutingCHGraph graph, Weighting weighting chGraph = graph; - inEdgeExplorer = chGraph.createInEdgeExplorer(); + inEdgeExplorer = chGraph.createInEdgeExplorer(); outEdgeExplorer = chGraph.createOutEdgeExplorer(); // TODO Refactoring: remove this unnecessary duplication @@ -70,6 +75,7 @@ protected AbstractCoreRoutingAlgorithm(RoutingCHGraph graph, Weighting weighting } protected abstract void initCollections(int size); + protected SPTEntry bestFwdEntry; protected SPTEntry bestBwdEntry; protected double bestWeight = Double.MAX_VALUE; @@ -88,6 +94,7 @@ protected AbstractCoreRoutingAlgorithm(RoutingCHGraph graph, Weighting weighting /** * Stopping criterion for phase outside core + * * @return should stop */ public abstract boolean finishedPhase1(); @@ -99,6 +106,7 @@ protected AbstractCoreRoutingAlgorithm(RoutingCHGraph graph, Weighting weighting /** * Stopping criterion for phase inside core + * * @return should stop */ public abstract boolean finishedPhase2(); @@ -147,7 +155,8 @@ protected void runAlgo() { runPhase2(); } - protected void initPhase2() {} + protected void initPhase2() { + } @Override public Path calcPath(int from, int to, long at) { @@ -194,8 +203,7 @@ protected boolean accept(RoutingCHEdgeIteratorState iter, CHEntry prevOrNextEdge int getIncEdge(RoutingCHEdgeIteratorState iter, boolean reverse) { if (iter.isShortcut()) { return reverse ? iter.getSkippedEdge1() : iter.getSkippedEdge2(); - } - else { + } else { return iter.getOrigEdge(); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreALT.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreALT.java index b6e6cecacd..2d7b22cecc 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreALT.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreALT.java @@ -16,14 +16,16 @@ import com.carrotsearch.hppc.IntObjectMap; import com.graphhopper.coll.GHIntObjectHashMap; import com.graphhopper.routing.ch.CHEntry; -import com.graphhopper.routing.weighting.BeelineWeightApproximator; import com.graphhopper.routing.weighting.BalancedWeightApproximator; +import com.graphhopper.routing.weighting.BeelineWeightApproximator; import com.graphhopper.routing.weighting.WeightApproximator; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.RoutingCHEdgeExplorer; import com.graphhopper.storage.RoutingCHEdgeIterator; import com.graphhopper.storage.RoutingCHGraph; -import com.graphhopper.util.*; +import com.graphhopper.util.DistancePlaneProjection; +import com.graphhopper.util.EdgeIterator; +import com.graphhopper.util.Parameters; import java.util.ArrayList; import java.util.List; @@ -32,7 +34,7 @@ /** * Calculates best path using CH routing outside core and ALT inside core. - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -136,8 +138,7 @@ public boolean fillEdgesFrom() { // for regular CH Dijkstra we don't expect an entry to exist because the picked node is supposed to be already settled if (considerTurnRestrictions(currFrom.adjNode)) initBestWeightMapEntryList(bestWeightMapFromCore, currFrom.adjNode).add(currFrom); - } - else { + } else { bestWeightMapOtherCH = bestWeightMapToCH; fillEdgesCH(currFrom, fromPriorityQueueCH, bestWeightMapFromCH, outEdgeExplorer, false); visitedCountFrom1++; @@ -159,8 +160,7 @@ public boolean fillEdgesTo() { // for regular CH Dijkstra we don't expect an entry to exist because the picked node is supposed to be already settled if (considerTurnRestrictions(currTo.adjNode)) initBestWeightMapEntryList(bestWeightMapToCore, currTo.adjNode).add(currTo); - } - else { + } else { bestWeightMapOtherCH = bestWeightMapFromCH; fillEdgesCH(currTo, toPriorityQueueCH, bestWeightMapToCH, inEdgeExplorer, true); visitedCountTo1++; @@ -245,7 +245,7 @@ private void recalculateWeights(PriorityQueue queue, boolean reverse public boolean finishedPhase2() { if (finishedFrom || finishedTo) return true; - // AO: in order to guarantee that the shortest path is found it is neccesary to account for possible precision loss in LM distance approximation by introducing the additional offset + // AO: in order to guarantee that the shortest path is found it is neccesary to account for possible precision loss in LM distance approximation by introducing the additional offset return currFrom.weight + currTo.weight >= bestWeight + approximatorOffset; } @@ -366,8 +366,7 @@ private void fillEdgesCore(AStarEntry currEdge, PriorityQueue prioQu updateBestPathCore(aStarEntry, traversalId, reverse); } - } - else { + } else { AStarEntry aStarEntry = bestWeightMap.get(traversalId); if (aStarEntry == null || aStarEntry.getWeightOfVisitedPath() > alreadyVisitedWeight) { double currWeightToGoal = weightApprox.approximate(iter.getAdjNode(), reverse); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstra.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstra.java index b8ad77f469..89e58ca5c4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstra.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstra.java @@ -20,7 +20,7 @@ import com.graphhopper.storage.RoutingCHEdgeExplorer; import com.graphhopper.storage.RoutingCHEdgeIterator; import com.graphhopper.storage.RoutingCHGraph; -import com.graphhopper.util.*; +import com.graphhopper.util.Parameters; import java.util.ArrayList; import java.util.List; @@ -29,7 +29,7 @@ /** * Calculates best path using core routing algorithm. - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -105,8 +105,7 @@ public boolean fillEdgesFrom() { // for regular CH Dijkstra we don't expect an entry to exist because the picked node is supposed to be already settled if (considerTurnRestrictions(currFrom.adjNode)) initBestWeightMapEntryList(bestWeightMapFromCore, currFrom.adjNode).add(currFrom); - } - else { + } else { bestWeightMapOtherCH = bestWeightMapToCH; fillEdges(currFrom, fromPriorityQueueCH, bestWeightMapFromCH, null, outEdgeExplorer, false); visitedCountFrom1++; @@ -128,8 +127,7 @@ public boolean fillEdgesTo() { // for regular CH Dijkstra we don't expect an entry to exist because the picked node is supposed to be already settled if (considerTurnRestrictions(currTo.adjNode)) initBestWeightMapEntryList(bestWeightMapToCore, currTo.adjNode).add(currTo); - } - else { + } else { bestWeightMapOtherCH = bestWeightMapFromCH; fillEdges(currTo, toPriorityQueueCH, bestWeightMapToCH, null, inEdgeExplorer, true); visitedCountTo1++; @@ -264,8 +262,7 @@ void fillEdges(CHEntry currEdge, PriorityQueue prioQueue, IntObjectMap< prioQueue.add(ee); updateBestPathCore(ee, traversalId, reverse); - } - else { + } else { CHEntry ee = bestWeightMap.get(traversalId); if (ee == null) { ee = new CHEntry(iter.getEdge(), getIncEdge(iter, reverse), iter.getAdjNode(), tmpWeight); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMOptions.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMOptions.java index 491c0b0553..eb0956150f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMOptions.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMOptions.java @@ -32,6 +32,7 @@ public class CoreLMOptions { /** * Set the filters that are used while calculating landmarks and their distance + * * @param tmpCoreLMSets */ public void setRestrictionFilters(List tmpCoreLMSets) { @@ -42,12 +43,10 @@ public void setRestrictionFilters(List tmpCoreLMSets) { * Creates all LMSet-Filters from the sets specified in the ors-config.json * The filter is an LMEdgeFilterSequence, consisting of at most ONE AvoidFeaturesFilter and ONE AvoidCountriesFilter * These can contain multiple avoidfeatures and avoidcountries - * - * - * */ - public void createRestrictionFilters(GraphHopperStorage ghStorage){ + */ + public void createRestrictionFilters(GraphHopperStorage ghStorage) { //Create one edgefiltersequence for each lmset - for(String set : coreLMSets) { + for (String set : coreLMSets) { //Now iterate over all comma separated values in one lm set String[] tmpFilters = set.split(","); LMEdgeFilterSequence edgeFilterSequence = new LMEdgeFilterSequence(); @@ -79,9 +78,7 @@ public void createRestrictionFilters(GraphHopperStorage ghStorage){ if (filterType.matches(countryPattern)) { try { country = Integer.parseInt(filterType.replaceFirst(countryPattern, "$1")); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { country = 0; } // todo check for valid country @@ -92,12 +89,12 @@ public void createRestrictionFilters(GraphHopperStorage ghStorage){ } } - if(avoidFeatures != 0) + if (avoidFeatures != 0) edgeFilterSequence.add(new AvoidFeaturesCoreEdgeFilter(ghStorage, -1, avoidFeatures)); - if(!countries.isEmpty()){ + if (!countries.isEmpty()) { int[] avoidCountries = new int[countries.size()]; - for(int i = 0; i < countries.size(); i++){ + for (int i = 0; i < countries.size(); i++) { avoidCountries[i] = countries.get(i); } //Only one avoidBordersCoreEdgeFilter per set @@ -108,7 +105,7 @@ public void createRestrictionFilters(GraphHopperStorage ghStorage){ } } - public List getFilters(){ + public List getFilters() { return filters; } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMPreparationHandler.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMPreparationHandler.java index 54b9c02c06..e0f460ab68 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMPreparationHandler.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLMPreparationHandler.java @@ -24,11 +24,15 @@ import org.heigit.ors.routing.graphhopper.extensions.ORSGraphHopperStorage; import org.heigit.ors.routing.graphhopper.extensions.util.GraphUtils; import org.heigit.ors.routing.graphhopper.extensions.util.ORSParameters.CoreLandmark; -import java.util.*; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * This class implements the A*, landmark and triangulation (ALT) decorator for Core. - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -63,9 +67,9 @@ public void init(ORSGraphHopperConfig ghConfig) { protected void createPreparationsInternal(GraphHopperStorage ghStorage, List lmSuggestions) { for (LMConfig lmConfig : getLMConfigs()) { if (!(lmConfig instanceof CoreLMConfig coreLMConfig)) - throw(new IllegalStateException("Expected instance of CoreLMConfig")); + throw (new IllegalStateException("Expected instance of CoreLMConfig")); if (!(ghStorage instanceof ORSGraphHopperStorage)) - throw(new IllegalStateException("Expected instance of ORSGraphHopperStorage")); + throw (new IllegalStateException("Expected instance of ORSGraphHopperStorage")); String lmConfigName = coreLMConfig.getSuperName(); @@ -78,7 +82,7 @@ protected void createPreparationsInternal(GraphHopperStorage ghStorage, List createCoreNodeIdMap(RoutingCHGraph core) int maxNode = GraphUtils.getBaseGraph(core).getNodes(); int coreNodeLevel = maxNode; int index = 0; - for (int i = 0; i < maxNode; i++){ + for (int i = 0; i < maxNode; i++) { if (core.getLevel(i) < coreNodeLevel) continue; coreNodeIdMap.put(i, index); @@ -109,7 +113,7 @@ public static HashMap createCoreNodeIdMap(RoutingCHGraph core) return coreNodeIdMap; } - public CoreLMOptions getCoreLMOptions(){ + public CoreLMOptions getCoreLMOptions() { return coreLMOptions; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLandmarkStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLandmarkStorage.java index d836c6774f..4738faaa98 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLandmarkStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreLandmarkStorage.java @@ -46,7 +46,7 @@ /** * Store Landmark distances for core nodes - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -55,7 +55,7 @@ */ public class CoreLandmarkStorage extends LandmarkStorage { private static final Logger logger = Logger.getLogger(CoreLandmarkStorage.class); - private RoutingCHGraphImpl core; + private final RoutingCHGraphImpl core; private final LMEdgeFilterSequence landmarksFilter; private Map coreNodeIdMap; private final ORSGraphHopperStorage graph; @@ -63,7 +63,7 @@ public class CoreLandmarkStorage extends LandmarkStorage { private IntHashSet subnetworkNodes; public CoreLandmarkStorage(Directory dir, ORSGraphHopperStorage graph, final CoreLMConfig lmConfig, int landmarks) { - this(dir, graph, (RoutingCHGraphImpl) graph.getCoreGraph(lmConfig.getSuperName()), lmConfig, landmarks); + this(dir, graph, graph.getCoreGraph(lmConfig.getSuperName()), lmConfig, landmarks); } //needed primarily for unit tests @@ -76,7 +76,7 @@ public CoreLandmarkStorage(Directory dir, ORSGraphHopperStorage graph, RoutingCH setMinimumNodes(Math.min(getBaseNodes() / 2, 10000)); } - public void setCoreNodeIdMap (Map coreNodeIdMap) { + public void setCoreNodeIdMap(Map coreNodeIdMap) { this.coreNodeIdMap = coreNodeIdMap; } @@ -84,6 +84,7 @@ public void setCoreNodeIdMap (Map coreNodeIdMap) { public String getLandmarksFileName() { return "landmarks_core_"; } + /** * This method calculates the landmarks and initial weightings to & from them. */ @@ -193,7 +194,7 @@ public void createLandmarks() { int subnetworkCount = landmarkIDs.size(); // store all landmark node IDs and one int for the factor itself. - landmarkWeightDA.ensureCapacity(maxBytes /* landmark weights */ + subnetworkCount * landmarks /* landmark mapping per subnetwork */); + landmarkWeightDA.ensureCapacity(maxBytes /* landmark weights */ + (long) subnetworkCount * landmarks /* landmark mapping per subnetwork */); // calculate offset to point into landmark mapping long bytePos = maxBytes; @@ -204,8 +205,8 @@ public void createLandmarks() { } } - landmarkWeightDA.setHeader(0 * 4, coreNodes); - landmarkWeightDA.setHeader(1 * 4, landmarks); + landmarkWeightDA.setHeader(0, coreNodes); + landmarkWeightDA.setHeader(4, landmarks); landmarkWeightDA.setHeader(2 * 4, subnetworkCount); if (factor * DOUBLE_MLTPL > Integer.MAX_VALUE) throw new UnsupportedOperationException("landmark weight factor cannot be bigger than Integer.MAX_VALUE " + factor * DOUBLE_MLTPL); @@ -263,7 +264,7 @@ private boolean isCoreEdge(RoutingCHEdgeIteratorState edgeState) { } private boolean acceptEdge(RoutingCHEdgeIteratorState edgeState) { - if (edgeFilter==null) + if (edgeFilter == null) return true; if (edgeState.isShortcut()) return true; @@ -366,7 +367,7 @@ public boolean setSubnetworks(final byte[] subnetworks, final int subnetworkId) if (sn != UNSET_SUBNETWORK && sn != UNCLEAR_SUBNETWORK) { // this is ugly but can happen in real world, see testWithOnewaySubnetworks logger.error("subnetworkId for node " + nodeId - + " (" + createPoint(graph.getBaseGraph(), nodeId) + ") already set (" + sn + "). " + "Cannot change to " + subnetworkId); + + " (" + createPoint(graph.getBaseGraph(), nodeId) + ") already set (" + sn + "). " + "Cannot change to " + subnetworkId); failed.set(true); return false; @@ -387,7 +388,7 @@ public void initLandmarkWeights(final int lmIdx, int lmNodeId, final long rowSiz map.forEach((IntObjectProcedure) (nodeId, b) -> { nodeId = getIndex(nodeId); - if (!setWeight(nodeId * rowSize + lmIdx * 4 + offset, b.weight)) { + if (!setWeight(nodeId * rowSize + lmIdx * 4L + offset, b.weight)) { maxedout.incrementAndGet(); finalMaxWeight.setValue(Math.max(b.weight, finalMaxWeight.getValue())); } @@ -432,8 +433,7 @@ private int expandEdge(RoutingCHEdgeIteratorState mainEdgeState) { if (iter1 == null) { iter1 = core.getEdgeIteratorState(skippedEdge2, from); iter2 = core.getEdgeIteratorState(skippedEdge1, to); - } - else { + } else { iter2 = core.getEdgeIteratorState(skippedEdge2, to); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreNodeContractor.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreNodeContractor.java index 414fa927fb..1624e7042f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreNodeContractor.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreNodeContractor.java @@ -278,7 +278,7 @@ private void addOrUpdateShortcut(int fromNode, int toNode, double weight, int ti } } if (!exists) - prepareGraph.addShortcut(fromNode, toNode, incomingEdge, outgoingEdge, weight, time,inOrigEdgeCount + outOrigEdgeCount); + prepareGraph.addShortcut(fromNode, toNode, incomingEdge, outgoingEdge, weight, time, inOrigEdgeCount + outOrigEdgeCount); } @Override diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationGraph.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationGraph.java index fe534ca185..1475528109 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationGraph.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationGraph.java @@ -109,8 +109,7 @@ public PrepareCoreGraphEdgeExplorerImpl(PrepareEdge[] prepareEdges, boolean reve public int getTime() { if (isShortcut()) { return ((PrepareCoreShortcut) currEdge).getTime(); - } - else { + } else { PrepareCoreBaseEdge baseEdge = (PrepareCoreBaseEdge) currEdge; if (nodeAisBase()) { return reverse ? baseEdge.getTimeBA() : baseEdge.getTimeAB(); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationHandler.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationHandler.java index be0d7d3fa0..1f9834bcb5 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationHandler.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CorePreparationHandler.java @@ -18,7 +18,8 @@ import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.routing.util.EncodingManager; import com.graphhopper.routing.util.FlagEncoder; -import com.graphhopper.storage.*; +import com.graphhopper.storage.CHConfig; +import com.graphhopper.storage.GraphHopperStorage; import org.heigit.ors.routing.RoutingProfileCategory; import org.heigit.ors.routing.graphhopper.extensions.GraphProcessContext; import org.heigit.ors.routing.graphhopper.extensions.ORSGraphHopperConfig; @@ -30,7 +31,7 @@ /** * This class implements the Core Algo decorator and provides several helper methods related to core * preparation and its vehicle profiles. - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -55,7 +56,7 @@ public void init(ORSGraphHopperConfig ghConfig) { @Override public void createPreparations(GraphHopperStorage ghStorage) { - if (processContext==null) + if (processContext == null) throw new IllegalStateException("Set processContext first!"); super.createPreparations(ghStorage); } @@ -101,9 +102,9 @@ private EdgeFilter createCoreEdgeFilter(CHConfig chProfile, GraphHopperStorage g } /* Maximum speed & turn restrictions */ - if ((routingProfileCategory & RoutingProfileCategory.DRIVING) !=0) { + if ((routingProfileCategory & RoutingProfileCategory.DRIVING) != 0) { String[] encoders = {FlagEncoderNames.CAR_ORS, FlagEncoderNames.HEAVYVEHICLE}; - for (String encoderName: encoders) { + for (String encoderName : encoders) { if (encodingManager.hasEncoder(encoderName)) { FlagEncoder flagEncoder = encodingManager.getEncoder(encoderName); edgeFilterSequence.add(new MaximumSpeedCoreEdgeFilter(flagEncoder, processContext.getMaximumSpeedLowerBound())); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreRoutingAlgorithmFactory.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreRoutingAlgorithmFactory.java index 1864dc4f64..6974d8e029 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreRoutingAlgorithmFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreRoutingAlgorithmFactory.java @@ -18,7 +18,9 @@ package org.heigit.ors.routing.graphhopper.extensions.core; -import com.graphhopper.routing.*; +import com.graphhopper.routing.AlgorithmOptions; +import com.graphhopper.routing.RoutingAlgorithm; +import com.graphhopper.routing.RoutingAlgorithmFactory; import com.graphhopper.routing.lm.LMApproximator; import com.graphhopper.routing.lm.LandmarkStorage; import com.graphhopper.routing.querygraph.QueryGraph; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCore.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCore.java index 3a57b27004..62a531d2db 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCore.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCore.java @@ -17,21 +17,23 @@ import com.carrotsearch.hppc.IntContainer; import com.carrotsearch.hppc.predicates.IntPredicate; import com.graphhopper.coll.MinHeapWithUpdate; -import com.graphhopper.routing.ch.*; -import com.graphhopper.routing.util.*; +import com.graphhopper.routing.ch.CHPreparationGraph; +import com.graphhopper.routing.ch.PrepareContractionHierarchies; +import com.graphhopper.routing.util.AllEdgesIterator; +import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.routing.weighting.AbstractAdjustedWeighting; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.*; import com.graphhopper.util.*; import org.heigit.ors.routing.graphhopper.extensions.ORSGraphHopperStorage; -import static com.graphhopper.routing.ch.CHParameters.*; +import static com.graphhopper.routing.ch.CHParameters.CONTRACTED_NODES; import static com.graphhopper.util.Helper.getMemInfo; /** * Prepare the core graph. The core graph is a contraction hierarchies graph in which specified parts are not contracted * but remain on the highest level. E.g. used to build the core from restrictions. - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -39,10 +41,10 @@ */ public class PrepareCore extends PrepareContractionHierarchies { private final EdgeFilter restrictionFilter; - private boolean [] restrictedNodes; + private boolean[] restrictedNodes; private int restrictedNodesCount = 0; - private static int nodesContractedPercentage = 99; + private static final int nodesContractedPercentage = 99; IntPredicate isCoreNode = new IntPredicate() { public boolean apply(int node) { @@ -52,13 +54,13 @@ public boolean apply(int node) { public PrepareCore(GraphHopperStorage ghStorage, CHConfig chConfig, EdgeFilter restrictionFilter) { super(ghStorage, chConfig); - PMap pMap = new PMap(CONTRACTED_NODES+"="+nodesContractedPercentage); + PMap pMap = new PMap(CONTRACTED_NODES + "=" + nodesContractedPercentage); setParams(pMap); this.restrictionFilter = restrictionFilter; } @Override - public CHStorage getCHStore (CHConfig chConfig) { + public CHStorage getCHStore(CHConfig chConfig) { if (CHConfig.TYPE_CORE.equals(chConfig.getType()) && graph instanceof ORSGraphHopperStorage ghStorage) { CHStorage chStore = ghStorage.getCoreStore(chConfig.getName()); if (chStore == null) @@ -166,7 +168,7 @@ protected IntContainer contractNode(int node, int level) { if (neighbors instanceof IntArrayList intArrayList) intArrayList.removeAll(isCoreNode); else - throw(new IllegalStateException("Not an isntance of IntArrayList")); + throw (new IllegalStateException("Not an isntance of IntArrayList")); return neighbors; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCoreLandmarks.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCoreLandmarks.java index 2dec4fabf7..a9a0b485ab 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCoreLandmarks.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/PrepareCoreLandmarks.java @@ -28,7 +28,7 @@ * This class does the preprocessing for the ALT algorithm (A* , landmark, triangle inequality) in the core. *

    * http://www.siam.org/meetings/alenex05/papers/03agoldberg.pdf - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -45,16 +45,16 @@ public PrepareCoreLandmarks(Directory dir, GraphHopperStorage graph, CoreLMConfi } @Override - public LandmarkStorage createLandmarkStorage (Directory dir, GraphHopperStorage graph, LMConfig lmConfig, int landmarks) { + public LandmarkStorage createLandmarkStorage(Directory dir, GraphHopperStorage graph, LMConfig lmConfig, int landmarks) { if (!(lmConfig instanceof CoreLMConfig)) - throw(new IllegalStateException("Expected instance of CoreLMConfig")); + throw (new IllegalStateException("Expected instance of CoreLMConfig")); if (!(graph instanceof ORSGraphHopperStorage)) - throw(new IllegalStateException("Expected instance of ORSGraphHopperStorage")); + throw (new IllegalStateException("Expected instance of ORSGraphHopperStorage")); return new CoreLandmarkStorage(dir, (ORSGraphHopperStorage) graph, (CoreLMConfig) lmConfig, landmarks); } - public boolean matchesFilter(PMap pmap){ + public boolean matchesFilter(PMap pmap) { //Returns true if the landmarkset is for the avoidables. //Also returns true if the query has no avoidables and the set has no avoidables return landmarksFilter.isFilter(pmap); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreALT.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreALT.java index f2053499df..5f237e7359 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreALT.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreALT.java @@ -14,14 +14,14 @@ package org.heigit.ors.routing.graphhopper.extensions.core; import com.graphhopper.routing.Path; -import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.routing.SPTEntry; +import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.RoutingCHEdgeIteratorState; import com.graphhopper.storage.RoutingCHGraph; import com.graphhopper.util.Parameters; public class TDCoreALT extends CoreALT { - private boolean reverse; + private final boolean reverse; public TDCoreALT(RoutingCHGraph graph, Weighting weighting, boolean reverse) { super(graph, weighting); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreDijkstra.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreDijkstra.java index 671d4eb3f1..7ce64b52d1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreDijkstra.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCoreDijkstra.java @@ -14,14 +14,14 @@ package org.heigit.ors.routing.graphhopper.extensions.core; import com.graphhopper.routing.Path; -import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.routing.SPTEntry; +import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.RoutingCHEdgeIteratorState; import com.graphhopper.storage.RoutingCHGraph; import com.graphhopper.util.Parameters; public class TDCoreDijkstra extends CoreDijkstra { - private boolean reverse; + private final boolean reverse; public TDCoreDijkstra(RoutingCHGraph graph, Weighting weighting, boolean reverse) { super(graph, weighting); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCorePathExtractor.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCorePathExtractor.java index a2a784cd66..dc08c63d07 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCorePathExtractor.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TDCorePathExtractor.java @@ -18,7 +18,8 @@ import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.RoutingCHEdgeIteratorState; import com.graphhopper.storage.RoutingCHGraph; -import com.graphhopper.util.*; +import com.graphhopper.util.EdgeIterator; +import com.graphhopper.util.EdgeIteratorState; public class TDCorePathExtractor extends CorePathExtractor { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TarjansCoreSCCAlgorithm.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TarjansCoreSCCAlgorithm.java index 9e9b7b2af9..cf9796f1bf 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TarjansCoreSCCAlgorithm.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/core/TarjansCoreSCCAlgorithm.java @@ -18,7 +18,10 @@ import com.graphhopper.coll.GHBitSet; import com.graphhopper.coll.GHBitSetImpl; import com.graphhopper.routing.util.EdgeFilter; -import com.graphhopper.storage.*; +import com.graphhopper.storage.CHEdgeFilter; +import com.graphhopper.storage.RoutingCHEdgeExplorer; +import com.graphhopper.storage.RoutingCHEdgeIterator; +import com.graphhopper.storage.RoutingCHGraph; import org.heigit.ors.routing.graphhopper.extensions.ORSGraphHopperStorage; import org.heigit.ors.routing.graphhopper.extensions.core.CoreLandmarkStorage.CoreEdgeFilter; import org.heigit.ors.routing.graphhopper.extensions.util.GraphUtils; @@ -35,10 +38,10 @@ *

    * See http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm. See * http://www.timl.id.au/?p=327 and http://homepages.ecs.vuw.ac.nz/~djp/files/P05.pdf - * - * + *

    + *

    * This has been adapted for use in the core. - * + *

    * This code is based on that from GraphHopper GmbH. * * @author Peter Karich @@ -76,9 +79,9 @@ public TarjansCoreSCCAlgorithm(ORSGraphHopperStorage ghStorage, RoutingCHGraph c int nodes = ghStorage.getNodes(); ignoreSet = new GHBitSetImpl(ghStorage.getCoreNodes()); for (int start = 0; start < nodes; start++) { - CoreEdgeIterator iter = new CoreEdgeIterator(explorer.setBaseNode(start), this.edgeFilter); - if (!iter.next()) - ignoreSet.add(start); + CoreEdgeIterator iter = new CoreEdgeIterator(explorer.setBaseNode(start), this.edgeFilter); + if (!iter.next()) + ignoreSet.add(start); } } else { ignoreSet = new GHBitSetImpl(); @@ -95,7 +98,7 @@ public GHBitSet getIgnoreSet() { public List findComponents() { int nodes = core.getNodes(); for (int start = 0; start < nodes; start++) { - if(core.getLevel(start) < coreNodeLevel) + if (core.getLevel(start) < coreNodeLevel) continue; if (nodeIndex[start] == 0 && !ignoreSet.contains(start)) strongConnect(start); @@ -111,7 +114,7 @@ public List findComponents() { * @param firstNode start search of SCC at this node */ private void strongConnect(int firstNode) { - final Deque stateStack = new ArrayDeque<>(); + final Deque stateStack = new ArrayDeque<>(); stateStack.push(TarjanState.startState(firstNode)); // nextState label is equivalent to the function entry point in the recursive Tarjan's algorithm. @@ -204,8 +207,8 @@ boolean isStart() { } private static class CoreEdgeIterator implements RoutingCHEdgeIterator { - private RoutingCHEdgeIterator chIterator; - private CHEdgeFilter coreFilter; + private final RoutingCHEdgeIterator chIterator; + private final CHEdgeFilter coreFilter; public CoreEdgeIterator(RoutingCHEdgeIterator chIterator, CHEdgeFilter coreFilter) { this.chIterator = chIterator; @@ -214,7 +217,7 @@ public CoreEdgeIterator(RoutingCHEdgeIterator chIterator, CHEdgeFilter coreFilte @Override public boolean next() { - while(chIterator.next()) { + while (chIterator.next()) { if (coreFilter.accept(chIterator)) return true; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilter.java index 0173a46cdf..6039e506cf 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilter.java @@ -23,297 +23,292 @@ public class AvoidAreasEdgeFilter implements EdgeFilter { - private Envelope env; - private final Polygon[] polys; - private DefaultCoordinateSequence coordSequence; - private final GeometryFactory geomFactory = new GeometryFactory(); - - /** - * Creates an edges filter which accepts both direction of the specified vehicle. - */ - public AvoidAreasEdgeFilter(Polygon[] polys) - { - this.polys = polys; - - if (polys != null && polys.length > 0) - { - double minX = Double.MAX_VALUE; - double minY = Double.MAX_VALUE; - double maxX = Double.MIN_VALUE; - double maxY = Double.MIN_VALUE; - - for (int i = 0; i < polys.length; i++) { - Polygon poly = polys[i]; - Envelope internal = poly.getEnvelopeInternal(); - if (internal.getMinX() < minX) - minX = internal.getMinX(); - if (internal.getMinY() < minY) - minY = internal.getMinY(); - if (internal.getMaxX() > maxX) - maxX = internal.getMaxX(); - if (internal.getMaxY() > maxY) - maxY = internal.getMaxY(); - } - - env = new Envelope(minX, maxX, minY, maxY); - - coordSequence = new DefaultCoordinateSequence(new Coordinate[1], 1); - } - } - - @Override - public final boolean accept(EdgeIteratorState iter ) { - if (env == null) - return true; - - boolean inEnv = false; - PointList pl = iter.fetchWayGeometry(FetchMode.ALL); - int size = pl.size(); - - double eMinX = Double.MAX_VALUE; - double eMinY = Double.MAX_VALUE; - double eMaxX = Double.MIN_VALUE; - double eMaxY = Double.MIN_VALUE; - - for (int j = 0; j < pl.size(); j++) - { - double x = pl.getLon(j); - double y = pl.getLat(j); - if (env.contains(x, y)) - { - inEnv = true; - break; - } - - if (x < eMinX) - eMinX = x; - if (y < eMinY) - eMinY = y; - if (x > eMaxX) - eMaxX = x; - if (y > eMaxY) - eMaxY = y; - } - - if (inEnv || !(eMinX > env.getMaxX() || eMaxX < env.getMinX() || eMinY > env.getMaxY() || eMaxY < env.getMinY())) - { - // We have to reset the coordinate sequence else for some reason the envelopes for the edge are wrong - coordSequence = new DefaultCoordinateSequence(new Coordinate[1], 1); - if (size >= 2) - { - // resize sequence if needed - coordSequence.resize(size); - - for (int j = 0; j < size; j++) - { - double x = pl.getLon(j); - double y = pl.getLat(j); - Coordinate c = coordSequence.getCoordinate(j); - - if (c == null) - { - c = new Coordinate(x, y); - coordSequence.setCoordinate(j, c); - } - else - { - c.x = x; - c.y = y; - } - } - - LineString ls = geomFactory.createLineString(coordSequence); - - for (int i = 0; i < polys.length; i++) - { - Polygon poly = polys[i]; - if (poly.contains(ls) || ls.crosses(poly)) - { - return false; - } - } - } - else - { - return false; - } - } - return true; - } - - /** - * The CoordinateSequence implementation that Geometries use by default. In - * this implementation, Coordinates returned by #toArray and #get are live -- - * parties that change them are actually changing the - * DefaultCoordinateSequence's underlying data. - * - * @version 1.7 - */ - static class DefaultCoordinateSequence implements CoordinateSequence, Serializable - { - //With contributions from Markus Schaber [schabios@logi-track.com] 2004-03-26 - private static final long serialVersionUID = -915438501601840650L; - private Coordinate[] coordinates; - private int size; - /** - * Constructs a DefaultCoordinateSequence based on the given array (the - * array is not copied). - * - * @param coordinates the coordinate array that will be referenced. - */ - public DefaultCoordinateSequence(Coordinate[] coordinates, int size) { - if (coordinates == null) - { - throw new IllegalArgumentException("Null coordinate"); - } - this.coordinates = coordinates; - this.size = size; - } - - /** - * @see org.locationtech.jts.geom.CoordinateSequence#getDimension() - */ - public int getDimension() { return 3; } - /** - * Get the Coordinate with index i. - * - * @param i - * the index of the coordinate - * @return the requested Coordinate instance - */ - public Coordinate getCoordinate(int i) { - return coordinates[i]; - } - - public void setCoordinate(int i, Coordinate c) { - coordinates[i] = c; - } - - /** - * Get a copy of the Coordinate with index i. - * - * @param i the index of the coordinate - * @return a copy of the requested Coordinate - */ - public Coordinate getCoordinateCopy(int i) { - return new Coordinate(coordinates[i]); - } - /** - * @see org.locationtech.jts.geom.CoordinateSequence#getX(int) - */ - public void getCoordinate(int index, Coordinate coord) { - coord.x = coordinates[index].x; - coord.y = coordinates[index].y; - } - /** - * @see org.locationtech.jts.geom.CoordinateSequence#getX(int) - */ - public double getX(int index) { - return coordinates[index].x; - } - /** - * @see org.locationtech.jts.geom.CoordinateSequence#getY(int) - */ - public double getY(int index) { - return coordinates[index].y; - } - /** - * @see org.locationtech.jts.geom.CoordinateSequence#getOrdinate(int, int) - */ - public double getOrdinate(int index, int ordinateIndex) - { - switch (ordinateIndex) { - case CoordinateSequence.X: return coordinates[index].x; - case CoordinateSequence.Y: return coordinates[index].y; - case CoordinateSequence.Z: return coordinates[index].z; - default: break; - } - return Double.NaN; - } - /** - * @see org.locationtech.jts.geom.CoordinateSequence#setOrdinate(int, int, double) - */ - public void setOrdinate(int index, int ordinateIndex, double value) { - switch (ordinateIndex) { - case CoordinateSequence.X -> coordinates[index].x = value; - case CoordinateSequence.Y -> coordinates[index].y = value; - case CoordinateSequence.Z -> coordinates[index].z = value; - default -> { - } - } - } - /** - * Creates a deep copy of the Object - * - * @return The deep copy - */ - public CoordinateSequence copy() { - Coordinate[] cloneCoordinates = new Coordinate[size]; - for (int i = 0; i < coordinates.length; i++) { - cloneCoordinates[i] = coordinates[i].copy(); - } - return new DefaultCoordinateSequence(cloneCoordinates, size); - } - - @Override - @Deprecated - public Object clone() { - return copy(); - } - - /** - * Returns the size of the coordinate sequence - * - * @return the number of coordinates - */ - public int size() { - return size; - } - - public void resize(int size) - { - if (size > this.size) - { - coordinates = new Coordinate[size]; - } - - this.size = size; - } - - /** - * This method exposes the internal Array of Coordinate Objects - * - * @return the Coordinate[] array. - */ - public Coordinate[] toCoordinateArray() { - return coordinates; - } - public Envelope expandEnvelope(Envelope env) - { - for (int i = 0; i < coordinates.length; i++ ) { - env.expandToInclude(coordinates[i]); - } - return env; - } - /** - * Returns the string Representation of the coordinate array - * - * @return The string - */ - public String toString() { - if (coordinates.length > 0) { - StringBuilder strBuf = new StringBuilder(17 * coordinates.length); - strBuf.append('('); - strBuf.append(coordinates[0]); - for (int i = 1; i < coordinates.length; i++) { - strBuf.append(", "); - strBuf.append(coordinates[i]); - } - strBuf.append(')'); - return strBuf.toString(); - } else { - return "()"; - } - } - } + private Envelope env; + private final Polygon[] polys; + private DefaultCoordinateSequence coordSequence; + private final GeometryFactory geomFactory = new GeometryFactory(); + + /** + * Creates an edges filter which accepts both direction of the specified vehicle. + */ + public AvoidAreasEdgeFilter(Polygon[] polys) { + this.polys = polys; + + if (polys != null && polys.length > 0) { + double minX = Double.MAX_VALUE; + double minY = Double.MAX_VALUE; + double maxX = Double.MIN_VALUE; + double maxY = Double.MIN_VALUE; + + for (int i = 0; i < polys.length; i++) { + Polygon poly = polys[i]; + Envelope internal = poly.getEnvelopeInternal(); + if (internal.getMinX() < minX) + minX = internal.getMinX(); + if (internal.getMinY() < minY) + minY = internal.getMinY(); + if (internal.getMaxX() > maxX) + maxX = internal.getMaxX(); + if (internal.getMaxY() > maxY) + maxY = internal.getMaxY(); + } + + env = new Envelope(minX, maxX, minY, maxY); + + coordSequence = new DefaultCoordinateSequence(new Coordinate[1], 1); + } + } + + @Override + public final boolean accept(EdgeIteratorState iter) { + if (env == null) + return true; + + boolean inEnv = false; + PointList pl = iter.fetchWayGeometry(FetchMode.ALL); + int size = pl.size(); + + double eMinX = Double.MAX_VALUE; + double eMinY = Double.MAX_VALUE; + double eMaxX = Double.MIN_VALUE; + double eMaxY = Double.MIN_VALUE; + + for (int j = 0; j < pl.size(); j++) { + double x = pl.getLon(j); + double y = pl.getLat(j); + if (env.contains(x, y)) { + inEnv = true; + break; + } + + if (x < eMinX) + eMinX = x; + if (y < eMinY) + eMinY = y; + if (x > eMaxX) + eMaxX = x; + if (y > eMaxY) + eMaxY = y; + } + + if (inEnv || !(eMinX > env.getMaxX() || eMaxX < env.getMinX() || eMinY > env.getMaxY() || eMaxY < env.getMinY())) { + // We have to reset the coordinate sequence else for some reason the envelopes for the edge are wrong + coordSequence = new DefaultCoordinateSequence(new Coordinate[1], 1); + if (size >= 2) { + // resize sequence if needed + coordSequence.resize(size); + + for (int j = 0; j < size; j++) { + double x = pl.getLon(j); + double y = pl.getLat(j); + Coordinate c = coordSequence.getCoordinate(j); + + if (c == null) { + c = new Coordinate(x, y); + coordSequence.setCoordinate(j, c); + } else { + c.x = x; + c.y = y; + } + } + + LineString ls = geomFactory.createLineString(coordSequence); + + for (int i = 0; i < polys.length; i++) { + Polygon poly = polys[i]; + if (poly.contains(ls) || ls.crosses(poly)) { + return false; + } + } + } else { + return false; + } + } + return true; + } + + /** + * The CoordinateSequence implementation that Geometries use by default. In + * this implementation, Coordinates returned by #toArray and #get are live -- + * parties that change them are actually changing the + * DefaultCoordinateSequence's underlying data. + * + * @version 1.7 + */ + static class DefaultCoordinateSequence implements CoordinateSequence, Serializable { + //With contributions from Markus Schaber [schabios@logi-track.com] 2004-03-26 + private static final long serialVersionUID = -915438501601840650L; + private Coordinate[] coordinates; + private int size; + + /** + * Constructs a DefaultCoordinateSequence based on the given array (the + * array is not copied). + * + * @param coordinates the coordinate array that will be referenced. + */ + public DefaultCoordinateSequence(Coordinate[] coordinates, int size) { + if (coordinates == null) { + throw new IllegalArgumentException("Null coordinate"); + } + this.coordinates = coordinates; + this.size = size; + } + + /** + * @see org.locationtech.jts.geom.CoordinateSequence#getDimension() + */ + public int getDimension() { + return 3; + } + + /** + * Get the Coordinate with index i. + * + * @param i the index of the coordinate + * @return the requested Coordinate instance + */ + public Coordinate getCoordinate(int i) { + return coordinates[i]; + } + + public void setCoordinate(int i, Coordinate c) { + coordinates[i] = c; + } + + /** + * Get a copy of the Coordinate with index i. + * + * @param i the index of the coordinate + * @return a copy of the requested Coordinate + */ + public Coordinate getCoordinateCopy(int i) { + return new Coordinate(coordinates[i]); + } + + /** + * @see org.locationtech.jts.geom.CoordinateSequence#getX(int) + */ + public void getCoordinate(int index, Coordinate coord) { + coord.x = coordinates[index].x; + coord.y = coordinates[index].y; + } + + /** + * @see org.locationtech.jts.geom.CoordinateSequence#getX(int) + */ + public double getX(int index) { + return coordinates[index].x; + } + + /** + * @see org.locationtech.jts.geom.CoordinateSequence#getY(int) + */ + public double getY(int index) { + return coordinates[index].y; + } + + /** + * @see org.locationtech.jts.geom.CoordinateSequence#getOrdinate(int, int) + */ + public double getOrdinate(int index, int ordinateIndex) { + switch (ordinateIndex) { + case CoordinateSequence.X: + return coordinates[index].x; + case CoordinateSequence.Y: + return coordinates[index].y; + case CoordinateSequence.Z: + return coordinates[index].z; + default: + break; + } + return Double.NaN; + } + + /** + * @see org.locationtech.jts.geom.CoordinateSequence#setOrdinate(int, int, double) + */ + public void setOrdinate(int index, int ordinateIndex, double value) { + switch (ordinateIndex) { + case CoordinateSequence.X -> coordinates[index].x = value; + case CoordinateSequence.Y -> coordinates[index].y = value; + case CoordinateSequence.Z -> coordinates[index].z = value; + default -> { + } + } + } + + /** + * Creates a deep copy of the Object + * + * @return The deep copy + */ + public CoordinateSequence copy() { + Coordinate[] cloneCoordinates = new Coordinate[size]; + for (int i = 0; i < coordinates.length; i++) { + cloneCoordinates[i] = coordinates[i].copy(); + } + return new DefaultCoordinateSequence(cloneCoordinates, size); + } + + @Override + @Deprecated + public Object clone() { + return copy(); + } + + /** + * Returns the size of the coordinate sequence + * + * @return the number of coordinates + */ + public int size() { + return size; + } + + public void resize(int size) { + if (size > this.size) { + coordinates = new Coordinate[size]; + } + + this.size = size; + } + + /** + * This method exposes the internal Array of Coordinate Objects + * + * @return the Coordinate[] array. + */ + public Coordinate[] toCoordinateArray() { + return coordinates; + } + + public Envelope expandEnvelope(Envelope env) { + for (int i = 0; i < coordinates.length; i++) { + env.expandToInclude(coordinates[i]); + } + return env; + } + + /** + * Returns the string Representation of the coordinate array + * + * @return The string + */ + public String toString() { + if (coordinates.length > 0) { + StringBuilder strBuf = new StringBuilder(17 * coordinates.length); + strBuf.append('('); + strBuf.append(coordinates[0]); + for (int i = 1; i < coordinates.length; i++) { + strBuf.append(", "); + strBuf.append(coordinates[i]); + } + strBuf.append(')'); + return strBuf.toString(); + } else { + return "()"; + } + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilter.java index 7362567d1b..8a8b3b9190 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilter.java @@ -40,22 +40,22 @@ public AvoidBordersEdgeFilter(RouteSearchParameters searchParams, GraphHopperSto /** * Initialise the edge filter object based on the type of borders to filter * - * @param searchParams The search parameters passed into the request - * @param extBorders The extended borders graph storage to use + * @param searchParams The search parameters passed into the request + * @param extBorders The extended borders graph storage to use */ private void init(RouteSearchParameters searchParams, BordersGraphStorage extBorders) { // Init the graph storage isStorageBuilt = extBorders != null; - if(isStorageBuilt) { + if (isStorageBuilt) { int[] countriesToAvoid; - if(searchParams.hasAvoidCountries()) + if (searchParams.hasAvoidCountries()) countriesToAvoid = searchParams.getAvoidCountries(); else countriesToAvoid = new int[0]; this.avoidCountries = countriesToAvoid.length > 0; - if(searchParams.hasAvoidBorders()) { + if (searchParams.hasAvoidBorders()) { avoidBorders = searchParams.getAvoidBorders(); } @@ -67,7 +67,7 @@ private void init(RouteSearchParameters searchParams, BordersGraphStorage extBor * Determine whether the edge should be accepted for processing or reject. Depending on whether the request was to * not cross any border or not cross controlled borders determines the type of border to reject. * - * @param iter An iterator to the edges that need to be filtered + * @param iter An iterator to the edges that need to be filtered * @return */ @Override @@ -77,15 +77,15 @@ public final boolean accept(EdgeIteratorState iter) { if (avoidBorders != BordersExtractor.Avoid.NONE) { // We have been told to avoid some form of border - switch(avoidBorders) { + switch (avoidBorders) { case ALL: - if(bordersExtractor.isBorder(iter.getEdge())) { + if (bordersExtractor.isBorder(iter.getEdge())) { // It is a border, and we want to avoid all borders return false; } break; case CONTROLLED: - if(bordersExtractor.isControlledBorder(iter.getEdge())) { + if (bordersExtractor.isControlledBorder(iter.getEdge())) { // We want to only avoid controlled borders return false; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidFeaturesEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidFeaturesEdgeFilter.java index 0b34ab49d7..a613fabf29 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidFeaturesEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidFeaturesEdgeFilter.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.edgefilters; @@ -25,63 +25,62 @@ import org.heigit.ors.routing.pathprocessors.TollwayExtractor; public class AvoidFeaturesEdgeFilter implements EdgeFilter { - private final byte[] buffer; - private final WayCategoryGraphStorage storage; - private TollwayExtractor tollwayExtractor; - private final int avoidFeatureType; - - private static final int NOT_TOLLWAYS = ~AvoidFeatureFlags.TOLLWAYS; - - public AvoidFeaturesEdgeFilter(int profileType, RouteSearchParameters searchParams, GraphHopperStorage graphStorage) throws Exception { - this.buffer = new byte[10]; - - int profileCategory = RoutingProfileCategory.getFromRouteProfile(profileType); - this.avoidFeatureType = searchParams.getAvoidFeatureTypes() & AvoidFeatureFlags.getProfileFlags(profileCategory); - - storage = GraphStorageUtils.getGraphExtension(graphStorage, WayCategoryGraphStorage.class); - if (storage == null) - throw new Exception("ExtendedGraphStorage for avoid features was not found."); - - TollwaysGraphStorage extTollways = GraphStorageUtils.getGraphExtension(graphStorage, TollwaysGraphStorage.class); - if (extTollways != null) - tollwayExtractor = new TollwayExtractor(extTollways, searchParams.getProfileType(), searchParams.getProfileParameters()); - } - - public AvoidFeaturesEdgeFilter(int avoidFeatureType, GraphHopperStorage graphStorage) throws Exception{ - if(avoidFeatureType == AvoidFeatureFlags.TOLLWAYS) - throw new IllegalArgumentException("Invalid constructor for use with feature type: " + AvoidFeatureFlags.TOLLWAYS); - this.buffer = new byte[10]; - - this.avoidFeatureType = avoidFeatureType; - - storage = GraphStorageUtils.getGraphExtension(graphStorage, WayCategoryGraphStorage.class); - if (storage == null) - throw new IllegalStateException("ExtendedGraphStorage for avoid features was not found."); - } - - @Override - public final boolean accept(EdgeIteratorState iter) { - if (avoidFeatureType != 0) { - int edge = iter.getEdge(); - int edgeFeatType = storage.getEdgeValue(edge, buffer); - - if (edgeFeatType != 0) { - int avoidEdgeFeatureType = avoidFeatureType & edgeFeatType; - - if (avoidEdgeFeatureType != 0) { - - if ((avoidEdgeFeatureType & NOT_TOLLWAYS) != 0) { - // restrictions other than tollways are present - return false; - } - else if (tollwayExtractor != null) { - // false when there is a toll for the given profile - return tollwayExtractor.getValue(edge) == 0; - } - - } - } - } - return true; - } + private final byte[] buffer; + private final WayCategoryGraphStorage storage; + private TollwayExtractor tollwayExtractor; + private final int avoidFeatureType; + + private static final int NOT_TOLLWAYS = ~AvoidFeatureFlags.TOLLWAYS; + + public AvoidFeaturesEdgeFilter(int profileType, RouteSearchParameters searchParams, GraphHopperStorage graphStorage) throws Exception { + this.buffer = new byte[10]; + + int profileCategory = RoutingProfileCategory.getFromRouteProfile(profileType); + this.avoidFeatureType = searchParams.getAvoidFeatureTypes() & AvoidFeatureFlags.getProfileFlags(profileCategory); + + storage = GraphStorageUtils.getGraphExtension(graphStorage, WayCategoryGraphStorage.class); + if (storage == null) + throw new Exception("ExtendedGraphStorage for avoid features was not found."); + + TollwaysGraphStorage extTollways = GraphStorageUtils.getGraphExtension(graphStorage, TollwaysGraphStorage.class); + if (extTollways != null) + tollwayExtractor = new TollwayExtractor(extTollways, searchParams.getProfileType(), searchParams.getProfileParameters()); + } + + public AvoidFeaturesEdgeFilter(int avoidFeatureType, GraphHopperStorage graphStorage) throws Exception { + if (avoidFeatureType == AvoidFeatureFlags.TOLLWAYS) + throw new IllegalArgumentException("Invalid constructor for use with feature type: " + AvoidFeatureFlags.TOLLWAYS); + this.buffer = new byte[10]; + + this.avoidFeatureType = avoidFeatureType; + + storage = GraphStorageUtils.getGraphExtension(graphStorage, WayCategoryGraphStorage.class); + if (storage == null) + throw new IllegalStateException("ExtendedGraphStorage for avoid features was not found."); + } + + @Override + public final boolean accept(EdgeIteratorState iter) { + if (avoidFeatureType != 0) { + int edge = iter.getEdge(); + int edgeFeatType = storage.getEdgeValue(edge, buffer); + + if (edgeFeatType != 0) { + int avoidEdgeFeatureType = avoidFeatureType & edgeFeatType; + + if (avoidEdgeFeatureType != 0) { + + if ((avoidEdgeFeatureType & NOT_TOLLWAYS) != 0) { + // restrictions other than tollways are present + return false; + } else if (tollwayExtractor != null) { + // false when there is a toll for the given profile + return tollwayExtractor.getValue(edge) == 0; + } + + } + } + } + return true; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/EdgeFilterSequence.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/EdgeFilterSequence.java index ed8785516a..d8a938a638 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/EdgeFilterSequence.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/EdgeFilterSequence.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.edgefilters; @@ -20,36 +20,36 @@ public class EdgeFilterSequence implements EdgeFilter { - protected ArrayList filters = new ArrayList<>(); - private String name = ""; - - @Override - public boolean accept(EdgeIteratorState eis) { - for (EdgeFilter edgeFilter: filters) { - if (!edgeFilter.accept(eis)) { - return false; - } - } - return true; - } - - public void appendName(String name){ - if (this.name.isEmpty()) - this.name = name; - else - this.name += ("_" + name); - } - - public String getName() { - return name; - } - - public void add(EdgeFilter o) { - filters.add(o); - } - - @Override - public String toString() { - return "EdgeFilter Sequence: " + name + " (" + filters.size() + ")"; - } + protected ArrayList filters = new ArrayList<>(); + private String name = ""; + + @Override + public boolean accept(EdgeIteratorState eis) { + for (EdgeFilter edgeFilter : filters) { + if (!edgeFilter.accept(eis)) { + return false; + } + } + return true; + } + + public void appendName(String name) { + if (this.name.isEmpty()) + this.name = name; + else + this.name += ("_" + name); + } + + public String getName() { + return name; + } + + public void add(EdgeFilter o) { + filters.add(o); + } + + @Override + public String toString() { + return "EdgeFilter Sequence: " + name + " (" + filters.size() + ")"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/HeavyVehicleEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/HeavyVehicleEdgeFilter.java index 8294157c93..e78ee46ab3 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/HeavyVehicleEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/HeavyVehicleEdgeFilter.java @@ -16,6 +16,7 @@ import com.carrotsearch.hppc.IntObjectMap; import com.carrotsearch.hppc.cursors.IntObjectCursor; import com.graphhopper.routing.Dijkstra; +import com.graphhopper.routing.SPTEntry; import com.graphhopper.routing.querygraph.EdgeIteratorStateHelper; import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.routing.util.FlagEncoder; @@ -23,7 +24,6 @@ import com.graphhopper.routing.weighting.FastestWeighting; import com.graphhopper.routing.weighting.Weighting; import com.graphhopper.storage.Graph; -import com.graphhopper.routing.SPTEntry; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.util.EdgeIteratorState; import org.heigit.ors.routing.graphhopper.extensions.HeavyVehicleAttributes; @@ -39,169 +39,166 @@ public class HeavyVehicleEdgeFilter implements DestinationDependentEdgeFilter { - public static class CustomDijkstra extends Dijkstra { - CustomDijkstra(Graph g, Weighting weighting, TraversalMode tMode) { - super(g, weighting, tMode); - initCollections(1000); - } - public IntObjectMap getMap() - { - return fromMap; - } - } - - private final int vehicleType; - private boolean hasHazmat; - private final HeavyVehicleAttributesGraphStorage gsHeavyVehicles; - private final float[] restrictionValues; - private final double[] retValues; - private final Integer[] indexValues; - private final Integer[] indexLocs; - private final int restCount; - private int mode = MODE_CLOSEST_EDGE; - private List destinationEdges; - private final byte[] buffer; - - private static final int MODE_DESTINATION_EDGES = -1; - private static final int MODE_CLOSEST_EDGE = -2; - private static final int MODE_ROUTE = 0; - - public HeavyVehicleEdgeFilter(int vehicleType, VehicleParameters vehicleParams, GraphHopperStorage graphStorage) { - this(vehicleType, vehicleParams, GraphStorageUtils.getGraphExtension(graphStorage, HeavyVehicleAttributesGraphStorage.class)); - } - - public HeavyVehicleEdgeFilter(int vehicleType, VehicleParameters vehicleParams, HeavyVehicleAttributesGraphStorage hgvStorage) { - float[] vehicleAttrs = new float[VehicleDimensionRestrictions.COUNT]; - - if (vehicleParams!=null) { - this.hasHazmat = VehicleLoadCharacteristicsFlags.isSet(vehicleParams.getLoadCharacteristics(), VehicleLoadCharacteristicsFlags.HAZMAT); - - vehicleAttrs[VehicleDimensionRestrictions.MAX_HEIGHT] = (float) vehicleParams.getHeight(); - vehicleAttrs[VehicleDimensionRestrictions.MAX_WIDTH] = (float) vehicleParams.getWidth(); - vehicleAttrs[VehicleDimensionRestrictions.MAX_WEIGHT] = (float) vehicleParams.getWeight(); - vehicleAttrs[VehicleDimensionRestrictions.MAX_LENGTH] = (float) vehicleParams.getLength(); - vehicleAttrs[VehicleDimensionRestrictions.MAX_AXLE_LOAD] = (float) vehicleParams.getAxleload(); - } else { - this.hasHazmat = false; - } - - ArrayList idx = new ArrayList<>(); - ArrayList idxl = new ArrayList<>(); - - for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) { - float value = vehicleAttrs[i]; - if (value > 0) { - idx.add(i); - idxl.add(i); - } - } - - retValues = new double[5]; - - this.restrictionValues = vehicleAttrs; - this.indexValues = idx.toArray(new Integer[0]); - this.indexLocs = idxl.toArray(new Integer[0]); - this.restCount = indexValues.length; - - this.vehicleType = vehicleType; - this.buffer = new byte[2]; - - this.gsHeavyVehicles = hgvStorage; - } - - public void setDestinationEdge(EdgeIteratorState edge, Graph graph, FlagEncoder encoder, TraversalMode tMode) { - if (edge != null) { - int nodeId = edge.getBaseNode(); - if (nodeId != -1) { - mode = MODE_DESTINATION_EDGES; - Weighting weighting = new FastestWeighting(encoder); - CustomDijkstra dijkstraAlg = new CustomDijkstra(graph, weighting, tMode); - EdgeFilter edgeFilter = this; - dijkstraAlg.setEdgeFilter(edgeFilter); - dijkstraAlg.calcPath(nodeId, Integer.MIN_VALUE); - - IntObjectMap destination = dijkstraAlg.getMap(); - - destinationEdges = new ArrayList<>(destination.size()); - for (IntObjectCursor ee : destination) { - if (!destinationEdges.contains(ee.value.edge)) // was originalEdge - destinationEdges.add(ee.value.edge); - } - - if (!destinationEdges.contains(EdgeIteratorStateHelper.getOriginalEdge(edge))) { - int vt = gsHeavyVehicles.getEdgeVehicleType(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - boolean dstFlag = buffer[1]!=0; // ((buffer[1] >> (vehicleType >> 1)) & 1) == 1 - - if (((vt & vehicleType) == vehicleType) && (dstFlag)) - destinationEdges.add(EdgeIteratorStateHelper.getOriginalEdge(edge)); - } - - if (destinationEdges.isEmpty()) - destinationEdges = null; - } - } - mode = MODE_ROUTE; - } - - @Override - public boolean accept(EdgeIteratorState iter) { - int edgeId = EdgeIteratorStateHelper.getOriginalEdge(iter); - - int vt = gsHeavyVehicles.getEdgeVehicleType(edgeId, buffer); - boolean dstFlag = buffer[1] != 0; // ((buffer[1] >> (vehicleType >> 1)) & 1) == 1 - - // if edge has some restrictions - if (vt != HeavyVehicleAttributes.UNKNOWN) { - if (mode == MODE_CLOSEST_EDGE) { - // current vehicle type is not forbidden - boolean edgeRestricted = ((vt & vehicleType) == vehicleType); - if ((edgeRestricted || dstFlag) && buffer[1] != vehicleType) - return false; - } else if (mode == MODE_DESTINATION_EDGES) { - // Here we are looking for all edges that have destination - return dstFlag && ((vt & vehicleType) == vehicleType); - } else { - // Check an edge with destination attribute - if (dstFlag) { - if ((vt & vehicleType) == vehicleType) { - if (destinationEdges != null) { - if (!destinationEdges.contains(edgeId)) - return false; - } - else - return false; - } - else - return false; - } - else if ((vt & vehicleType) == vehicleType) - return false; - } - } else { - if (mode == MODE_DESTINATION_EDGES) { - return false; - } - } - - if (hasHazmat && (vt & HeavyVehicleAttributes.HAZMAT) != 0) { - return false; - } - - if (restCount != 0) { - if (restCount == 1) { - double value = gsHeavyVehicles.getEdgeRestrictionValue(edgeId, indexValues[0]); - return value <= 0 || value >= restrictionValues[indexLocs[0]]; - } else { - if (gsHeavyVehicles.getEdgeRestrictionValues(edgeId, retValues)) { - for(int i=0; i 0.0f && value < restrictionValues[indexLocs[i]]) { - return false; - } - } - } - } - } - return true; - } + public static class CustomDijkstra extends Dijkstra { + CustomDijkstra(Graph g, Weighting weighting, TraversalMode tMode) { + super(g, weighting, tMode); + initCollections(1000); + } + + public IntObjectMap getMap() { + return fromMap; + } + } + + private final int vehicleType; + private final boolean hasHazmat; + private final HeavyVehicleAttributesGraphStorage gsHeavyVehicles; + private final float[] restrictionValues; + private final double[] retValues; + private final Integer[] indexValues; + private final Integer[] indexLocs; + private final int restCount; + private int mode = MODE_CLOSEST_EDGE; + private List destinationEdges; + private final byte[] buffer; + + private static final int MODE_DESTINATION_EDGES = -1; + private static final int MODE_CLOSEST_EDGE = -2; + private static final int MODE_ROUTE = 0; + + public HeavyVehicleEdgeFilter(int vehicleType, VehicleParameters vehicleParams, GraphHopperStorage graphStorage) { + this(vehicleType, vehicleParams, GraphStorageUtils.getGraphExtension(graphStorage, HeavyVehicleAttributesGraphStorage.class)); + } + + public HeavyVehicleEdgeFilter(int vehicleType, VehicleParameters vehicleParams, HeavyVehicleAttributesGraphStorage hgvStorage) { + float[] vehicleAttrs = new float[VehicleDimensionRestrictions.COUNT]; + + if (vehicleParams != null) { + this.hasHazmat = VehicleLoadCharacteristicsFlags.isSet(vehicleParams.getLoadCharacteristics(), VehicleLoadCharacteristicsFlags.HAZMAT); + + vehicleAttrs[VehicleDimensionRestrictions.MAX_HEIGHT] = (float) vehicleParams.getHeight(); + vehicleAttrs[VehicleDimensionRestrictions.MAX_WIDTH] = (float) vehicleParams.getWidth(); + vehicleAttrs[VehicleDimensionRestrictions.MAX_WEIGHT] = (float) vehicleParams.getWeight(); + vehicleAttrs[VehicleDimensionRestrictions.MAX_LENGTH] = (float) vehicleParams.getLength(); + vehicleAttrs[VehicleDimensionRestrictions.MAX_AXLE_LOAD] = (float) vehicleParams.getAxleload(); + } else { + this.hasHazmat = false; + } + + ArrayList idx = new ArrayList<>(); + ArrayList idxl = new ArrayList<>(); + + for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) { + float value = vehicleAttrs[i]; + if (value > 0) { + idx.add(i); + idxl.add(i); + } + } + + retValues = new double[5]; + + this.restrictionValues = vehicleAttrs; + this.indexValues = idx.toArray(new Integer[0]); + this.indexLocs = idxl.toArray(new Integer[0]); + this.restCount = indexValues.length; + + this.vehicleType = vehicleType; + this.buffer = new byte[2]; + + this.gsHeavyVehicles = hgvStorage; + } + + public void setDestinationEdge(EdgeIteratorState edge, Graph graph, FlagEncoder encoder, TraversalMode tMode) { + if (edge != null) { + int nodeId = edge.getBaseNode(); + if (nodeId != -1) { + mode = MODE_DESTINATION_EDGES; + Weighting weighting = new FastestWeighting(encoder); + CustomDijkstra dijkstraAlg = new CustomDijkstra(graph, weighting, tMode); + EdgeFilter edgeFilter = this; + dijkstraAlg.setEdgeFilter(edgeFilter); + dijkstraAlg.calcPath(nodeId, Integer.MIN_VALUE); + + IntObjectMap destination = dijkstraAlg.getMap(); + + destinationEdges = new ArrayList<>(destination.size()); + for (IntObjectCursor ee : destination) { + if (!destinationEdges.contains(ee.value.edge)) // was originalEdge + destinationEdges.add(ee.value.edge); + } + + if (!destinationEdges.contains(EdgeIteratorStateHelper.getOriginalEdge(edge))) { + int vt = gsHeavyVehicles.getEdgeVehicleType(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + boolean dstFlag = buffer[1] != 0; // ((buffer[1] >> (vehicleType >> 1)) & 1) == 1 + + if (((vt & vehicleType) == vehicleType) && (dstFlag)) + destinationEdges.add(EdgeIteratorStateHelper.getOriginalEdge(edge)); + } + + if (destinationEdges.isEmpty()) + destinationEdges = null; + } + } + mode = MODE_ROUTE; + } + + @Override + public boolean accept(EdgeIteratorState iter) { + int edgeId = EdgeIteratorStateHelper.getOriginalEdge(iter); + + int vt = gsHeavyVehicles.getEdgeVehicleType(edgeId, buffer); + boolean dstFlag = buffer[1] != 0; // ((buffer[1] >> (vehicleType >> 1)) & 1) == 1 + + // if edge has some restrictions + if (vt != HeavyVehicleAttributes.UNKNOWN) { + if (mode == MODE_CLOSEST_EDGE) { + // current vehicle type is not forbidden + boolean edgeRestricted = ((vt & vehicleType) == vehicleType); + if ((edgeRestricted || dstFlag) && buffer[1] != vehicleType) + return false; + } else if (mode == MODE_DESTINATION_EDGES) { + // Here we are looking for all edges that have destination + return dstFlag && ((vt & vehicleType) == vehicleType); + } else { + // Check an edge with destination attribute + if (dstFlag) { + if ((vt & vehicleType) == vehicleType) { + if (destinationEdges != null) { + if (!destinationEdges.contains(edgeId)) + return false; + } else + return false; + } else + return false; + } else if ((vt & vehicleType) == vehicleType) + return false; + } + } else { + if (mode == MODE_DESTINATION_EDGES) { + return false; + } + } + + if (hasHazmat && (vt & HeavyVehicleAttributes.HAZMAT) != 0) { + return false; + } + + if (restCount != 0) { + if (restCount == 1) { + double value = gsHeavyVehicles.getEdgeRestrictionValue(edgeId, indexValues[0]); + return value <= 0 || value >= restrictionValues[indexLocs[0]]; + } else { + if (gsHeavyVehicles.getEdgeRestrictionValues(edgeId, retValues)) { + for (int i = 0; i < restCount; i++) { + double value = retValues[indexLocs[i]]; + if (value > 0.0f && value < restrictionValues[indexLocs[i]]) { + return false; + } + } + } + } + } + return true; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/TrafficEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/TrafficEdgeFilter.java index 977035814c..5a1ba920db 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/TrafficEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/TrafficEdgeFilter.java @@ -4,7 +4,6 @@ import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.util.EdgeIteratorState; - import org.heigit.ors.routing.graphhopper.extensions.TrafficRelevantWayType; import org.heigit.ors.routing.graphhopper.extensions.storages.GraphStorageUtils; import org.heigit.ors.routing.graphhopper.extensions.storages.TrafficGraphStorage; @@ -12,7 +11,7 @@ public class TrafficEdgeFilter implements EdgeFilter { private int hereFunctionalClass; - private TrafficGraphStorage trafficGraphStorage; + private final TrafficGraphStorage trafficGraphStorage; public TrafficEdgeFilter(GraphHopperStorage graphStorage) { this.trafficGraphStorage = GraphStorageUtils.getGraphExtension(graphStorage, TrafficGraphStorage.class); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/WheelchairEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/WheelchairEdgeFilter.java index d803b383aa..80845dbc70 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/WheelchairEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/WheelchairEdgeFilter.java @@ -24,9 +24,9 @@ public class WheelchairEdgeFilter implements EdgeFilter { private static final Logger LOGGER = Logger.getLogger(WheelchairEdgeFilter.class.getName()); - private byte[] buffer; - private WheelchairAttributesGraphStorage storage; - private WheelchairAttributes attributes; + private final byte[] buffer; + private final WheelchairAttributesGraphStorage storage; + private final WheelchairAttributes attributes; private WheelchairParameters params; public WheelchairEdgeFilter(WheelchairParameters params, GraphHopperStorage graphStorage) throws Exception { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/AvoidBordersCoreEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/AvoidBordersCoreEdgeFilter.java index 6360efd276..22df9c8fbf 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/AvoidBordersCoreEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/AvoidBordersCoreEdgeFilter.java @@ -29,27 +29,30 @@ public class AvoidBordersCoreEdgeFilter implements EdgeFilter { public AvoidBordersCoreEdgeFilter(GraphHopperStorage graphStorage) { this.storage = GraphStorageUtils.getGraphExtension(graphStorage, BordersGraphStorage.class); } + //Used to specify multiple countries to avoid (For a specific LM set) public AvoidBordersCoreEdgeFilter(GraphHopperStorage graphStorage, int[] avoidCountries) { this.storage = GraphStorageUtils.getGraphExtension(graphStorage, BordersGraphStorage.class); this.avoidCountries = avoidCountries; - if(avoidCountries.length > 0) isAvoidCountries = true; + if (avoidCountries.length > 0) isAvoidCountries = true; } - public int[] getAvoidCountries(){ + public int[] getAvoidCountries() { return avoidCountries; } + /** - *Determine whether or not an edge is to be filtered + * Determine whether or not an edge is to be filtered + * * @param iter iterator pointing to a given edge * @return true iff the edge pointed to by the iterator is not to be filtered */ @Override public final boolean accept(EdgeIteratorState iter) { //If a specific country was given, just check if its one of the country borders - if(iter instanceof RoutingCHEdgeIterator iterator && iterator.isShortcut()) + if (iter instanceof RoutingCHEdgeIterator iterator && iterator.isShortcut()) return true; - if(isAvoidCountries) + if (isAvoidCountries) return !restrictedCountry(iter.getEdge()); //else check if there is ANY border if (storage == null) { @@ -64,8 +67,8 @@ public boolean restrictedCountry(int edgeId) { int startCountry = storage.getEdgeValue(edgeId, BordersGraphStorage.Property.START); int endCountry = storage.getEdgeValue(edgeId, BordersGraphStorage.Property.END); - for(int i=0; i. + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.edgefilters.core; @@ -24,70 +24,69 @@ public class LMEdgeFilterSequence extends EdgeFilterSequence implements EdgeFilter { - /** - * Checks if an LMSet fits the PMap of the query - * An LMSet can be used if it as the same properties as the request, or a subset of the properties. - * Then the landmarks heuristic is admissible, meaning it can only underestimate the actual distance - * If an LMSet has more restrictions that the query, it might overestimate and then the heuristic is wrong - * - * @return true if the lmset can be used to calc the query - * - * */ - public boolean isFilter(PMap pmap){ - //true if the avoidFeaturespart fits the query - RouteSearchParameters routeSearchParameters = pmap.getObject("avoid_features", new RouteSearchParameters()); - boolean avoidFeatures = isAvoidFeature(routeSearchParameters.getAvoidFeatureTypes()); - boolean avoidCountries = isAvoidCountry(pmap.getString("avoid_countries", "")); - return avoidFeatures && avoidCountries; + /** + * Checks if an LMSet fits the PMap of the query + * An LMSet can be used if it as the same properties as the request, or a subset of the properties. + * Then the landmarks heuristic is admissible, meaning it can only underestimate the actual distance + * If an LMSet has more restrictions that the query, it might overestimate and then the heuristic is wrong + * + * @return true if the lmset can be used to calc the query + */ + public boolean isFilter(PMap pmap) { + //true if the avoidFeaturespart fits the query + RouteSearchParameters routeSearchParameters = pmap.getObject("avoid_features", new RouteSearchParameters()); + boolean avoidFeatures = isAvoidFeature(routeSearchParameters.getAvoidFeatureTypes()); + boolean avoidCountries = isAvoidCountry(pmap.getString("avoid_countries", "")); + return avoidFeatures && avoidCountries; - } - /** - * Checks if the avoid countries specified in the LMSet are a subset of the avoid countries requested in the query - * - * @return true if the lmset can be used to calc the query - * - * */ - private boolean isAvoidCountry(String countries){ - ArrayList queryCountries = new ArrayList<>(); - if(!(countries.equals("") || countries.equals("[]"))) { - //Cut away the brackets - countries = countries.substring(1, countries.length() - 1); - String[] countryList = countries.split(", "); - //Make an int arraylist - for (int i = 0; i < countryList.length; i++) { - queryCountries.add(Integer.parseInt(countryList[i])); - } - } - //Check if the avoidBordersFilter has the same countries or a subset - for (EdgeFilter edgeFilter: filters) { - if (edgeFilter instanceof AvoidBordersCoreEdgeFilter coreEdgeFilter){ - //There are no countries queried, but there are some in the lmset - if(queryCountries.isEmpty()) - return false; - return queryCountries.containsAll(Arrays.stream(coreEdgeFilter.getAvoidCountries()).boxed().collect(Collectors.toList())); - } - } + } - return true; - } - /** - * Checks if the avoid features specified in the LMSet are a subset of the avoid features requested in the query - * - * @return true if the lmset can be used to calc the query - * - * */ - private boolean isAvoidFeature(int avoidable){ - for (EdgeFilter edgeFilter: filters) { - //There is only one AvoidFeaturesCoreEdgeFilter per EdgeFilterSequence - if (edgeFilter instanceof AvoidFeaturesCoreEdgeFilter coreEdgeFilter){ - //Some bit magic to find if the storage bits are a subset of the query bits, but not the other way around - int reverseQueryFeatures = Integer.MAX_VALUE ^ avoidable; - int filterFeatures = coreEdgeFilter.getAvoidFeatures(); + /** + * Checks if the avoid countries specified in the LMSet are a subset of the avoid countries requested in the query + * + * @return true if the lmset can be used to calc the query + */ + private boolean isAvoidCountry(String countries) { + ArrayList queryCountries = new ArrayList<>(); + if (!(countries.equals("") || countries.equals("[]"))) { + //Cut away the brackets + countries = countries.substring(1, countries.length() - 1); + String[] countryList = countries.split(", "); + //Make an int arraylist + for (int i = 0; i < countryList.length; i++) { + queryCountries.add(Integer.parseInt(countryList[i])); + } + } + //Check if the avoidBordersFilter has the same countries or a subset + for (EdgeFilter edgeFilter : filters) { + if (edgeFilter instanceof AvoidBordersCoreEdgeFilter coreEdgeFilter) { + //There are no countries queried, but there are some in the lmset + if (queryCountries.isEmpty()) + return false; + return queryCountries.containsAll(Arrays.stream(coreEdgeFilter.getAvoidCountries()).boxed().collect(Collectors.toList())); + } + } + + return true; + } + + /** + * Checks if the avoid features specified in the LMSet are a subset of the avoid features requested in the query + * + * @return true if the lmset can be used to calc the query + */ + private boolean isAvoidFeature(int avoidable) { + for (EdgeFilter edgeFilter : filters) { + //There is only one AvoidFeaturesCoreEdgeFilter per EdgeFilterSequence + if (edgeFilter instanceof AvoidFeaturesCoreEdgeFilter coreEdgeFilter) { + //Some bit magic to find if the storage bits are a subset of the query bits, but not the other way around + int reverseQueryFeatures = Integer.MAX_VALUE ^ avoidable; + int filterFeatures = coreEdgeFilter.getAvoidFeatures(); return (reverseQueryFeatures & filterFeatures) == 0; } - } - return true; - } + } + return true; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/MaximumSpeedCoreEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/MaximumSpeedCoreEdgeFilter.java index c3ff8d830e..0ee1bbb3e4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/MaximumSpeedCoreEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/MaximumSpeedCoreEdgeFilter.java @@ -15,7 +15,6 @@ import com.graphhopper.routing.ev.DecimalEncodedValue; import com.graphhopper.routing.util.EdgeFilter; -import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.util.EdgeIteratorState; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TimeDependentCoreEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TimeDependentCoreEdgeFilter.java index 643f8e74aa..b68cb351b8 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TimeDependentCoreEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TimeDependentCoreEdgeFilter.java @@ -26,45 +26,45 @@ public class TimeDependentCoreEdgeFilter implements EdgeFilter { - private BooleanEncodedValue[] conditionalEncoders; - private static String[] names = {ConditionalEdges.ACCESS, ConditionalEdges.SPEED}; + private final BooleanEncodedValue[] conditionalEncoders; + private static final String[] names = {ConditionalEdges.ACCESS, ConditionalEdges.SPEED}; - public TimeDependentCoreEdgeFilter(GraphHopperStorage graphStorage) { - EncodingManager encodingManager = graphStorage.getEncodingManager(); + public TimeDependentCoreEdgeFilter(GraphHopperStorage graphStorage) { + EncodingManager encodingManager = graphStorage.getEncodingManager(); - List conditionalEncodersList = new ArrayList<>(); + List conditionalEncodersList = new ArrayList<>(); - for (FlagEncoder encoder : encodingManager.fetchEdgeEncoders()) { - for (String name : names) { - String encoderName = EncodingManager.getKey(encoder, name); - if (encodingManager.hasEncodedValue(encoderName)) { - conditionalEncodersList.add(encodingManager.getBooleanEncodedValue(encoderName)); - } - } - } + for (FlagEncoder encoder : encodingManager.fetchEdgeEncoders()) { + for (String name : names) { + String encoderName = EncodingManager.getKey(encoder, name); + if (encodingManager.hasEncodedValue(encoderName)) { + conditionalEncodersList.add(encodingManager.getBooleanEncodedValue(encoderName)); + } + } + } - conditionalEncoders = conditionalEncodersList.toArray(new BooleanEncodedValue[0]); - } + conditionalEncoders = conditionalEncodersList.toArray(new BooleanEncodedValue[0]); + } - public static boolean hasConditionals(EncodingManager encodingManager) { - for (FlagEncoder encoder : encodingManager.fetchEdgeEncoders()) - for (String name : names) { - String encoderName = EncodingManager.getKey(encoder, name); - if (encodingManager.hasEncodedValue(encoderName)) { - return true; - } - } - return false; - } + public static boolean hasConditionals(EncodingManager encodingManager) { + for (FlagEncoder encoder : encodingManager.fetchEdgeEncoders()) + for (String name : names) { + String encoderName = EncodingManager.getKey(encoder, name); + if (encodingManager.hasEncodedValue(encoderName)) { + return true; + } + } + return false; + } - @Override - public final boolean accept(EdgeIteratorState iter) { - for (BooleanEncodedValue conditionalEncoder: conditionalEncoders) { - if (iter.get(conditionalEncoder)) { - return false; - } - } - return true; - } + @Override + public final boolean accept(EdgeIteratorState iter) { + for (BooleanEncodedValue conditionalEncoder : conditionalEncoders) { + if (iter.get(conditionalEncoder)) { + return false; + } + } + return true; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TrafficSpeedCoreEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TrafficSpeedCoreEdgeFilter.java index 7a90d68d98..f304ffe0be 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TrafficSpeedCoreEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/TrafficSpeedCoreEdgeFilter.java @@ -26,7 +26,7 @@ */ public class TrafficSpeedCoreEdgeFilter implements EdgeFilter { - private TrafficGraphStorage trafficGraphStorage; + private final TrafficGraphStorage trafficGraphStorage; public TrafficSpeedCoreEdgeFilter(GraphHopperStorage graphHopperStorage) { trafficGraphStorage = GraphStorageUtils.getGraphExtension(graphHopperStorage, TrafficGraphStorage.class); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/VariableSpeedCoreEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/VariableSpeedCoreEdgeFilter.java index 0ca749fa75..991d74f313 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/VariableSpeedCoreEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/VariableSpeedCoreEdgeFilter.java @@ -23,17 +23,17 @@ public class VariableSpeedCoreEdgeFilter implements EdgeFilter { - private SpeedStorage storage; - private FlagEncoder flagEncoder; - - public VariableSpeedCoreEdgeFilter(GraphHopperStorage graphStorage, FlagEncoder flagEncoder) { - storage = GraphStorageUtils.getGraphExtension(graphStorage, SpeedStorage.class); - this.flagEncoder = flagEncoder; - } - - @Override - public final boolean accept(EdgeIteratorState iter) { - return !storage.hasSpeed(EdgeIteratorStateHelper.getOriginalEdge(iter), iter.getReverse(flagEncoder.getAccessEnc())); - } + private final SpeedStorage storage; + private final FlagEncoder flagEncoder; + + public VariableSpeedCoreEdgeFilter(GraphHopperStorage graphStorage, FlagEncoder flagEncoder) { + storage = GraphStorageUtils.getGraphExtension(graphStorage, SpeedStorage.class); + this.flagEncoder = flagEncoder; + } + + @Override + public final boolean accept(EdgeIteratorState iter) { + return !storage.hasSpeed(EdgeIteratorStateHelper.getOriginalEdge(iter), iter.getReverse(flagEncoder.getAccessEnc())); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/WheelchairCoreEdgeFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/WheelchairCoreEdgeFilter.java index d9ca1a40d8..0b0c21f986 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/WheelchairCoreEdgeFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/core/WheelchairCoreEdgeFilter.java @@ -21,22 +21,22 @@ import org.heigit.ors.routing.graphhopper.extensions.storages.WheelchairAttributesGraphStorage; public final class WheelchairCoreEdgeFilter implements EdgeFilter { - private final byte[] buffer; - private final WheelchairAttributesGraphStorage storage; - private final WheelchairAttributes attributes; + private final byte[] buffer; + private final WheelchairAttributesGraphStorage storage; + private final WheelchairAttributes attributes; - public WheelchairCoreEdgeFilter(GraphHopperStorage graphStorage) { + public WheelchairCoreEdgeFilter(GraphHopperStorage graphStorage) { buffer = new byte[WheelchairAttributesGraphStorage.BYTE_COUNT]; - attributes = new WheelchairAttributes(); - storage = GraphStorageUtils.getGraphExtension(graphStorage, WheelchairAttributesGraphStorage.class); - } + attributes = new WheelchairAttributes(); + storage = GraphStorageUtils.getGraphExtension(graphStorage, WheelchairAttributesGraphStorage.class); + } - @Override - public boolean accept(EdgeIteratorState iter) { + @Override + public boolean accept(EdgeIteratorState iter) { - storage.getEdgeValues(iter.getEdge(), attributes, buffer); + storage.getEdgeValues(iter.getEdge(), attributes, buffer); - return !attributes.hasValues(); + return !attributes.hasValues(); - } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/CarFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/CarFlagEncoder.java index 671465c4e9..682b583efe 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/CarFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/CarFlagEncoder.java @@ -75,10 +75,10 @@ protected void init(DateRangeParser dateRangeParser) { public EncodingManager.Access getAccess(ReaderWay way) { // TODO: Ferries have conditionals, like opening hours or are closed during some time in the year String highwayValue = way.getTag("highway"); - String [] restrictionValues = way.getFirstPriorityTagValues(restrictions); + String[] restrictionValues = way.getFirstPriorityTagValues(restrictions); if (highwayValue == null) { if (way.hasTag("route", ferries)) { - for (String restrictionValue: restrictionValues) { + for (String restrictionValue : restrictionValues) { if (restrictedValues.contains(restrictionValue)) return EncodingManager.Access.CAN_SKIP; if (intendedValues.contains(restrictionValue) || @@ -93,8 +93,8 @@ public EncodingManager.Access getAccess(ReaderWay way) { if ("track".equals(highwayValue)) { String tt = way.getTag("tracktype"); if (tt != null) { - int grade = getTrackGradeLevel(tt); - if (grade > maxTrackGradeLevel) + int grade = getTrackGradeLevel(tt); + if (grade > maxTrackGradeLevel) return EncodingManager.Access.CAN_SKIP; } } @@ -106,7 +106,7 @@ public EncodingManager.Access getAccess(ReaderWay way) { return EncodingManager.Access.CAN_SKIP; // multiple restrictions needs special handling compared to foot and bike, see also motorcycle - for (String restrictionValue: restrictionValues) { + for (String restrictionValue : restrictionValues) { if (!restrictionValue.isEmpty()) { if (restrictedValues.contains(restrictionValue)) return isRestrictedWayConditionallyPermitted(way); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/EmergencyFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/EmergencyFlagEncoder.java index 5e790f064b..9b622c1287 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/EmergencyFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/EmergencyFlagEncoder.java @@ -15,12 +15,12 @@ import com.graphhopper.reader.ReaderWay; import com.graphhopper.routing.util.EncodingManager; -import com.graphhopper.routing.util.parsers.helpers.OSMValueExtractor; -import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import com.graphhopper.routing.util.TransportationMode; +import com.graphhopper.routing.util.parsers.helpers.OSMValueExtractor; import com.graphhopper.storage.IntsRef; import com.graphhopper.util.Helper; import com.graphhopper.util.PMap; +import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import java.util.*; @@ -40,12 +40,14 @@ public class EmergencyFlagEncoder extends VehicleFlagEncoder { protected final HashSet yesValues = new HashSet<>(5); protected final List hgvAccess = new ArrayList<>(5); - public double getMeanSpeed() { return MEAN_SPEED; } + public double getMeanSpeed() { + return MEAN_SPEED; + } public EmergencyFlagEncoder(PMap properties) { this(properties.getInt("speed_bits", 5), - properties.getDouble("speed_factor", 5), - properties.getBool("turn_costs", false) ? 3 : 0); + properties.getDouble("speed_factor", 5), + properties.getBool("turn_costs", false) ? 3 : 0); blockFords(false); } @@ -114,7 +116,7 @@ public EmergencyFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts) badSurfaceSpeedMap.put("mud", 10); badSurfaceSpeedMap.put("unknown", 30); - // limit speed on bad surfaces to 30 km/h + // limit speed on bad surfaces to 30 km/h badSurfaceSpeed = 30; maxPossibleSpeed = 140; @@ -188,53 +190,50 @@ protected double applyMaxSpeed(ReaderWay way, double speed) { } - @Override - public double getMaxSpeed(ReaderWay way) { // runge - String maxspeedTag = way.getTag("maxspeed:hgv"); - if (Helper.isEmpty(maxspeedTag)) - maxspeedTag = way.getTag("maxspeed"); - double maxSpeed = OSMValueExtractor.stringToKmh(maxspeedTag); + @Override + public double getMaxSpeed(ReaderWay way) { // runge + String maxspeedTag = way.getTag("maxspeed:hgv"); + if (Helper.isEmpty(maxspeedTag)) + maxspeedTag = way.getTag("maxspeed"); + double maxSpeed = OSMValueExtractor.stringToKmh(maxspeedTag); String highway = way.getTag(KEY_HIGHWAY); double defaultSpeed = speedLimitHandler.getSpeed(highway); if (defaultSpeed < maxSpeed) // TODO maxSpeed = defaultSpeed; - return maxSpeed; - } + return maxSpeed; + } - @Override + @Override protected double getSpeed(ReaderWay way) { - String highwayValue = way.getTag(KEY_HIGHWAY); - if (!Helper.isEmpty(highwayValue) && way.hasTag(KEY_MOTORROAD, "yes") - && !highwayValue.equals(KEY_MOTORWAY) && !highwayValue.equals(KEY_MOTORWAY_LINK) ) { - highwayValue = KEY_MOTORROAD; - } - Integer speed = speedLimitHandler.getSpeed(highwayValue); - if (speed == null) - throw new IllegalStateException(this + ", no speed found for: " + highwayValue + ", tags: " + way); - - if (highwayValue.equals(KEY_TRACK)) { - String tt = way.getTag("tracktype"); - if (!Helper.isEmpty(tt)) { - Integer tInt = speedLimitHandler.getTrackTypeSpeed(tt); // FIXME - if (tInt != null && tInt != -1) - speed = tInt; - } - } + String highwayValue = way.getTag(KEY_HIGHWAY); + if (!Helper.isEmpty(highwayValue) && way.hasTag(KEY_MOTORROAD, "yes") + && !highwayValue.equals(KEY_MOTORWAY) && !highwayValue.equals(KEY_MOTORWAY_LINK)) { + highwayValue = KEY_MOTORROAD; + } + Integer speed = speedLimitHandler.getSpeed(highwayValue); + if (speed == null) + throw new IllegalStateException(this + ", no speed found for: " + highwayValue + ", tags: " + way); + + if (highwayValue.equals(KEY_TRACK)) { + String tt = way.getTag("tracktype"); + if (!Helper.isEmpty(tt)) { + Integer tInt = speedLimitHandler.getTrackTypeSpeed(tt); // FIXME + if (tInt != null && tInt != -1) + speed = tInt; + } + } return speed; } @Override - public EncodingManager.Access getAccess(ReaderWay way) - { + public EncodingManager.Access getAccess(ReaderWay way) { String highwayValue = way.getTag(KEY_HIGHWAY); - if (highwayValue == null) - { - if (way.hasTag("route", ferries)) - { + if (highwayValue == null) { + if (way.hasTag("route", ferries)) { String motorcarTag = way.getTag("motorcar"); if (motorcarTag == null) motorcarTag = way.getTag("motor_vehicle"); @@ -265,7 +264,7 @@ public EncodingManager.Access getAccess(ReaderWay way) @Override public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.Access access, long relationFlags) { - if (access.canSkip()) + if (access.canSkip()) return edgeFlags; if (!access.isFerry()) { @@ -304,27 +303,26 @@ public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.A /** - * @param weightToPrioMap - * associate a weight with every priority. This sorted map allows - * subclasses to 'insert' more important priorities as well as - * overwrite determined priorities. - */ - protected void collect(ReaderWay way, TreeMap weightToPrioMap) { // Runge - if (way.hasTag("hgv", "designated") || (way.hasTag("access", "designated") && (way.hasTag("goods", "yes") || way.hasTag("hgv", "yes") || way.hasTag("bus", "yes") || way.hasTag(KEY_AGRICULTURAL, "yes") || way.hasTag(KEY_FORESTRY, "yes") ))) - weightToPrioMap.put(100d, PriorityCode.BEST.getValue()); - // Amandus + * @param weightToPrioMap associate a weight with every priority. This sorted map allows + * subclasses to 'insert' more important priorities as well as + * overwrite determined priorities. + */ + protected void collect(ReaderWay way, TreeMap weightToPrioMap) { // Runge + if (way.hasTag("hgv", "designated") || (way.hasTag("access", "designated") && (way.hasTag("goods", "yes") || way.hasTag("hgv", "yes") || way.hasTag("bus", "yes") || way.hasTag(KEY_AGRICULTURAL, "yes") || way.hasTag(KEY_FORESTRY, "yes")))) + weightToPrioMap.put(100d, PriorityCode.BEST.getValue()); + // Amandus else if (way.hasTag(KEY_HIGHWAY, KEY_SERVICE) && way.hasTag(KEY_SERVICE, "emergency_access")) weightToPrioMap.put(100d, PriorityCode.BEST.getValue()); else { // Amandus - String busway = way.getTag("busway");// FIXME || way.getTag("busway:right") || way.getTag("busway:left") + String busway = way.getTag("busway");// FIXME || way.getTag("busway:right") || way.getTag("busway:left") if (!Helper.isEmpty(busway) && "lane".equals(busway)) weightToPrioMap.put(10d, PriorityCode.PREFER.getValue()); String highway = way.getTag(KEY_HIGHWAY); - double maxSpeed = getMaxSpeed(way); + double maxSpeed = getMaxSpeed(way); - if (!Helper.isEmpty(highway)) { + if (!Helper.isEmpty(highway)) { switch (highway) { case KEY_MOTORWAY: case KEY_MOTORWAY_LINK: @@ -363,19 +361,18 @@ else if (way.hasTag(KEY_HIGHWAY, KEY_SERVICE) && way.hasTag(KEY_SERVICE, "emerge weightToPrioMap.put(40d, PriorityCode.AVOID_IF_POSSIBLE.getValue()); break; } - } - else - weightToPrioMap.put(100d, PriorityCode.UNCHANGED.getValue()); - - if (maxSpeed > 0) { - // We assume that the given road segment goes through a settlement. - if (maxSpeed <= 40) - weightToPrioMap.put(110d, PriorityCode.AVOID_IF_POSSIBLE.getValue()); - else if (maxSpeed <= 50) - weightToPrioMap.put(110d, PriorityCode.UNCHANGED.getValue()); - } - } - } + } else + weightToPrioMap.put(100d, PriorityCode.UNCHANGED.getValue()); + + if (maxSpeed > 0) { + // We assume that the given road segment goes through a settlement. + if (maxSpeed <= 40) + weightToPrioMap.put(110d, PriorityCode.AVOID_IF_POSSIBLE.getValue()); + else if (maxSpeed <= 50) + weightToPrioMap.put(110d, PriorityCode.UNCHANGED.getValue()); + } + } + } @Override public boolean equals(Object obj) { @@ -393,8 +390,7 @@ public int hashCode() { } @Override - public String toString() - { + public String toString() { return FlagEncoderNames.EMERGENCY; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderKeys.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderKeys.java index bcb62a3765..033e16905c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderKeys.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderKeys.java @@ -4,5 +4,6 @@ public class FlagEncoderKeys { public static final String PRIORITY_KEY = "priority"; - private FlagEncoderKeys() {} + private FlagEncoderKeys() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderNames.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderNames.java index 7dc4312053..7e2634f159 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderNames.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FlagEncoderNames.java @@ -1,38 +1,39 @@ package org.heigit.ors.routing.graphhopper.extensions.flagencoders; public class FlagEncoderNames { - private static final String ORS_SUFFIX = "_ors"; + private static final String ORS_SUFFIX = "_ors"; - public static final String UNKNOWN = "UNKNOWN"; + public static final String UNKNOWN = "UNKNOWN"; - public static final String CAR_ORS = "car" + ORS_SUFFIX; - public static final String HEAVYVEHICLE = "heavyvehicle"; - public static final String EMERGENCY = "emergency"; - public static final String EVEHICLE = "evehicle"; // NOT IMPLEMENTED - public static final String RUNNING = "running"; // NOT IMPLEMENTED + public static final String CAR_ORS = "car" + ORS_SUFFIX; + public static final String HEAVYVEHICLE = "heavyvehicle"; + public static final String EMERGENCY = "emergency"; + public static final String EVEHICLE = "evehicle"; // NOT IMPLEMENTED + public static final String RUNNING = "running"; // NOT IMPLEMENTED - public static final String WHEELCHAIR = "wheelchair"; + public static final String WHEELCHAIR = "wheelchair"; - public static final String BIKE_ORS = "bike" + ORS_SUFFIX; - public static final String ROADBIKE_ORS = "roadbike" + ORS_SUFFIX; - public static final String MTB_ORS = "mtb" + ORS_SUFFIX; - public static final String BIKE_ELECTRO = "electrobike"; + public static final String BIKE_ORS = "bike" + ORS_SUFFIX; + public static final String ROADBIKE_ORS = "roadbike" + ORS_SUFFIX; + public static final String MTB_ORS = "mtb" + ORS_SUFFIX; + public static final String BIKE_ELECTRO = "electrobike"; - public static final String PEDESTRIAN_ORS = "pedestrian" + ORS_SUFFIX; - public static final String HIKING_ORS = "hiking" + ORS_SUFFIX; + public static final String PEDESTRIAN_ORS = "pedestrian" + ORS_SUFFIX; + public static final String HIKING_ORS = "hiking" + ORS_SUFFIX; - public static final String GH_CAR = "car"; - public static final String GH_CAR4WD = "car4wd"; - public static final String GH_MOTOCYCLE = "motorcycle"; - public static final String GH_FOOT = "foot"; - public static final String GH_HIKE = "hike"; - public static final String GH_RACINGBIKE = "racingbike"; - public static final String GH_MTB = "mtb"; - public static final String GH_BIKE = "bike"; - public static final String GH_BIKE2 = "bike2"; + public static final String GH_CAR = "car"; + public static final String GH_CAR4WD = "car4wd"; + public static final String GH_MOTOCYCLE = "motorcycle"; + public static final String GH_FOOT = "foot"; + public static final String GH_HIKE = "hike"; + public static final String GH_RACINGBIKE = "racingbike"; + public static final String GH_MTB = "mtb"; + public static final String GH_BIKE = "bike"; + public static final String GH_BIKE2 = "bike2"; - private FlagEncoderNames() {} + private FlagEncoderNames() { + } public static String getBaseName(String name) { if (name.endsWith(ORS_SUFFIX)) diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FootFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FootFlagEncoder.java index 45858db6e0..8bd0464b48 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FootFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/FootFlagEncoder.java @@ -226,7 +226,7 @@ public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.A } accessEnc.setBool(false, edgeFlags, true); accessEnc.setBool(true, edgeFlags, true); - if (access.isConditional() && conditionalAccessEncoder!=null) + if (access.isConditional() && conditionalAccessEncoder != null) conditionalAccessEncoder.setBool(false, edgeFlags, true); } else { double ferrySpeed = ferrySpeedCalc.getSpeed(way); @@ -243,8 +243,8 @@ public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.A /** * Method which generates the acceptance flag for ways that are not seen as being highways (such as ferry routes) * - * @param way The way that is to be assessed - * @return The acceptance flag for the way + * @param way The way that is to be assessed + * @return The acceptance flag for the way */ private EncodingManager.Access handleNonHighways(ReaderWay way) { EncodingManager.Access acceptPotentially = EncodingManager.Access.CAN_SKIP; @@ -284,8 +284,8 @@ private EncodingManager.Access handleNonHighways(ReaderWay way) { * Determine if the way is seen as being too difficult based on any sac_scale tags and the information provided in * the setup of the object (suitableSacScales) * - * @param way The way to be assessed - * @return Whether the way is too difficult or not + * @param way The way to be assessed + * @return Whether the way is too difficult or not */ private boolean hasTooDifficultSacScale(ReaderWay way) { String sacScale = way.getTag(OSMTags.Keys.SAC_SCALE); @@ -296,9 +296,9 @@ private boolean hasTooDifficultSacScale(ReaderWay way) { * Assign priorities based on relations and values stored against the way. This is the top level method that calls * other priority assessment methods * - * @param way The way to be assessed - * @param priorityFromRelation The priority obtained from any relations - * @return The overall priority value for the way + * @param way The way to be assessed + * @param priorityFromRelation The priority obtained from any relations + * @return The overall priority value for the way */ protected int handlePriority(ReaderWay way, int priorityFromRelation) { TreeMap weightToPrioMap = new TreeMap<>(); @@ -335,8 +335,8 @@ private void assignPriorities(ReaderWay way, TreeMap weightToPr * Update the weight priority map based on values relating to highway types that are identified as being "safe" or * with low speeds * - * @param way The way containing the tag information - * @param weightToPrioMap The priority weight map that will have the weightings updated + * @param way The way containing the tag information + * @param weightToPrioMap The priority weight map that will have the weightings updated */ void assignSafeHighwayPriority(ReaderWay way, TreeMap weightToPrioMap) { String highway = way.getTag(OSMTags.Keys.HIGHWAY); @@ -355,8 +355,8 @@ void assignSafeHighwayPriority(ReaderWay way, TreeMap weightToP /** * Update the weight priority map based on tunnel information * - * @param way The way containing the tag information - * @param weightToPrioMap The priority weight map that will have the weightings updated + * @param way The way containing the tag information + * @param weightToPrioMap The priority weight map that will have the weightings updated */ void assignTunnelPriority(ReaderWay way, TreeMap weightToPrioMap) { if (way.hasTag(OSMTags.Keys.TUNNEL, intendedValues)) { @@ -370,8 +370,8 @@ void assignTunnelPriority(ReaderWay way, TreeMap weightToPrioMa /** * Update the weight priority map based on values relating to avoiding highways * - * @param way The way containing the tag information - * @param weightToPrioMap The priority weight map that will have the weightings updated + * @param way The way containing the tag information + * @param weightToPrioMap The priority weight map that will have the weightings updated */ private void assignAvoidHighwayPriority(ReaderWay way, TreeMap weightToPrioMap) { String highway = way.getTag(OSMTags.Keys.HIGHWAY); @@ -387,8 +387,8 @@ private void assignAvoidHighwayPriority(ReaderWay way, TreeMap * Mark the way as to be avoided if there is no sidewalk present on highway types identified as needing a sidewalk * to be traversed * - * @param way The way containing the tag information - * @param weightToPrioMap The priority weight map that will have the weightings updated + * @param way The way containing the tag information + * @param weightToPrioMap The priority weight map that will have the weightings updated */ private void assignAvoidUnlessSidewalkPresentPriority(ReaderWay way, TreeMap weightToPrioMap) { String highway = way.getTag(OSMTags.Keys.HIGHWAY); @@ -399,8 +399,8 @@ private void assignAvoidUnlessSidewalkPresentPriority(ReaderWay way, TreeMap weightToPrioMap) { if (way.hasTag(OSMTags.Keys.BICYCLE, "official") || way.hasTag(OSMTags.Keys.BICYCLE, KEY_DESIGNATED)) diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HeavyVehicleFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HeavyVehicleFlagEncoder.java index c05ab3cee7..103d59dcea 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HeavyVehicleFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HeavyVehicleFlagEncoder.java @@ -18,13 +18,13 @@ import com.graphhopper.routing.ev.EncodedValue; import com.graphhopper.routing.ev.UnsignedDecimalEncodedValue; import com.graphhopper.routing.util.EncodingManager; -import com.graphhopper.routing.util.parsers.helpers.OSMValueExtractor; -import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import com.graphhopper.routing.util.TransportationMode; +import com.graphhopper.routing.util.parsers.helpers.OSMValueExtractor; import com.graphhopper.routing.weighting.PriorityWeighting; import com.graphhopper.storage.IntsRef; import com.graphhopper.util.Helper; import com.graphhopper.util.PMap; +import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import java.util.*; @@ -50,8 +50,7 @@ public class HeavyVehicleFlagEncoder extends VehicleFlagEncoder { /** * Should be only instantied via EncodingManager */ - public HeavyVehicleFlagEncoder() - { + public HeavyVehicleFlagEncoder() { this(5, 5, 0); } @@ -121,11 +120,11 @@ public void createEncodedValues(List registerNewEncodedValue, Stri } @Override - public double getMaxSpeed( ReaderWay way ) { + public double getMaxSpeed(ReaderWay way) { double maxSpeed = OSMValueExtractor.stringToKmh(way.getTag("maxspeed:hgv")); double fwdSpeed = OSMValueExtractor.stringToKmh(way.getTag("maxspeed:hgv:forward")); - if (isValidSpeed(fwdSpeed) && (!isValidSpeed(maxSpeed) || fwdSpeed < maxSpeed)) { + if (isValidSpeed(fwdSpeed) && (!isValidSpeed(maxSpeed) || fwdSpeed < maxSpeed)) { maxSpeed = fwdSpeed; } @@ -157,10 +156,10 @@ protected String getHighway(ReaderWay way) { @Override public EncodingManager.Access getAccess(ReaderWay way) { String highwayValue = way.getTag(KEY_HIGHWAY); - String [] restrictionValues = way.getFirstPriorityTagValues(restrictions); + String[] restrictionValues = way.getFirstPriorityTagValues(restrictions); if (highwayValue == null) { if (way.hasTag("route", ferries)) { - for (String restrictionValue: restrictionValues) { + for (String restrictionValue : restrictionValues) { if (restrictedValues.contains(restrictionValue)) return EncodingManager.Access.CAN_SKIP; if (intendedValues.contains(restrictionValue) || @@ -186,7 +185,7 @@ public EncodingManager.Access getAccess(ReaderWay way) { return EncodingManager.Access.CAN_SKIP; // multiple restrictions needs special handling compared to foot and bike, see also motorcycle - for (String restrictionValue: restrictionValues) { + for (String restrictionValue : restrictionValues) { if (!restrictionValue.isEmpty()) { if (restrictedValues.contains(restrictionValue) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return EncodingManager.Access.CAN_SKIP; @@ -212,7 +211,7 @@ public EncodingManager.Access getAccess(ReaderWay way) { double mwv = Double.parseDouble(maxwidth); if (mwv < 2.0) return EncodingManager.Access.CAN_SKIP; - } catch(Exception ex) { + } catch (Exception ex) { // do nothing } } @@ -241,13 +240,12 @@ protected int handlePriority(ReaderWay way) { } /** - * @param weightToPrioMap - * associate a weight with every priority. This sorted map allows - * subclasses to 'insert' more important priorities as well as - * overwrite determined priorities. + * @param weightToPrioMap associate a weight with every priority. This sorted map allows + * subclasses to 'insert' more important priorities as well as + * overwrite determined priorities. */ protected void collect(ReaderWay way, TreeMap weightToPrioMap) { // Runge - if (way.hasTag("hgv", VAL_DESIGNATED) || (way.hasTag("access", VAL_DESIGNATED) && (way.hasTag(VAL_GOODS, "yes") || way.hasTag("hgv", "yes") || way.hasTag("bus", "yes") || way.hasTag(VAL_AGRICULTURAL, "yes") || way.hasTag(VAL_FORESTRY, "yes") ))) + if (way.hasTag("hgv", VAL_DESIGNATED) || (way.hasTag("access", VAL_DESIGNATED) && (way.hasTag(VAL_GOODS, "yes") || way.hasTag("hgv", "yes") || way.hasTag("bus", "yes") || way.hasTag(VAL_AGRICULTURAL, "yes") || way.hasTag(VAL_FORESTRY, "yes")))) weightToPrioMap.put(100d, PriorityCode.BEST.getValue()); else { String highway = way.getTag(KEY_HIGHWAY); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/ORSAbstractFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/ORSAbstractFlagEncoder.java index a528443951..e57a2fb52d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/ORSAbstractFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/ORSAbstractFlagEncoder.java @@ -25,7 +25,8 @@ protected ORSAbstractFlagEncoder(int speedBits, double speedFactor, int maxTurnC public abstract double getMeanSpeed(); - private boolean blockBarriers = false; + private boolean blockBarriers = false; + /** * Should barriers block when no access limits are given? */ diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/SpeedLimitHandler.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/SpeedLimitHandler.java index e542c888cf..88ae4e49f1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/SpeedLimitHandler.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/SpeedLimitHandler.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.flagencoders; @@ -19,85 +19,80 @@ import org.json.JSONArray; import org.json.JSONObject; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; public class SpeedLimitHandler { - private static final Logger LOGGER = Logger.getLogger(SpeedLimitHandler.class.getName()); - - private final Map defaultSpeeds = new HashMap<>(); - private final Map surfaceSpeeds = new HashMap<>(); - private final Map trackTypeSpeeds = new HashMap<>(); - private final Map countryMaxSpeeds = new HashMap<>(); - - public SpeedLimitHandler(String encoderName, Map defaultSpeeds, Map surfaceSpeeds, Map trackTypeSpeeds) { - this.defaultSpeeds.putAll(defaultSpeeds); - this.surfaceSpeeds.putAll(surfaceSpeeds); - this.trackTypeSpeeds.putAll(trackTypeSpeeds); - - encoderName = FlagEncoderNames.getBaseName(encoderName); - String resourcePath = "/resources/services/routing/speed_limits/" + encoderName + ".json"; - - try { - JSONObject json = new JSONObject(FileUtility.readResource(resourcePath)); - - readSpeedValues(json, "default", this.defaultSpeeds); - readSpeedValues(json, "max_speeds", countryMaxSpeeds); - readSpeedValues(json, "surface", this.surfaceSpeeds); - readSpeedValues(json, "tracktype", this.trackTypeSpeeds); - } catch (Exception e) { - LOGGER.error(e); - } - } - - private void readSpeedValues(JSONObject json, String keyName, Map speeds) { - if (json.has(keyName)) { - JSONObject jLimits = json.getJSONObject(keyName); - JSONArray jKeys = jLimits.names(); - for(int i = 0; i < jKeys.length(); i++) { - String key = jKeys.getString(i); - speeds.put(key.toLowerCase(), jLimits.getInt(key)); - } - } - } - + private static final Logger LOGGER = Logger.getLogger(SpeedLimitHandler.class.getName()); + + private final Map defaultSpeeds = new HashMap<>(); + private final Map surfaceSpeeds = new HashMap<>(); + private final Map trackTypeSpeeds = new HashMap<>(); + private final Map countryMaxSpeeds = new HashMap<>(); + + public SpeedLimitHandler(String encoderName, Map defaultSpeeds, Map surfaceSpeeds, Map trackTypeSpeeds) { + this.defaultSpeeds.putAll(defaultSpeeds); + this.surfaceSpeeds.putAll(surfaceSpeeds); + this.trackTypeSpeeds.putAll(trackTypeSpeeds); + + encoderName = FlagEncoderNames.getBaseName(encoderName); + String resourcePath = "/resources/services/routing/speed_limits/" + encoderName + ".json"; + + try { + JSONObject json = new JSONObject(FileUtility.readResource(resourcePath)); + + readSpeedValues(json, "default", this.defaultSpeeds); + readSpeedValues(json, "max_speeds", countryMaxSpeeds); + readSpeedValues(json, "surface", this.surfaceSpeeds); + readSpeedValues(json, "tracktype", this.trackTypeSpeeds); + } catch (Exception e) { + LOGGER.error(e); + } + } + + private void readSpeedValues(JSONObject json, String keyName, Map speeds) { + if (json.has(keyName)) { + JSONObject jLimits = json.getJSONObject(keyName); + JSONArray jKeys = jLimits.names(); + for (int i = 0; i < jKeys.length(); i++) { + String key = jKeys.getString(i); + speeds.put(key.toLowerCase(), jLimits.getInt(key)); + } + } + } + public Integer getMaxSpeed(ReaderWay way) { - // check if maxspeed is explicitly given - if (way.hasTag("maxspeed")) - return -1; - - String key = way.getTag("zone:maxspeed"); - if (key == null) - key = way.getTag("zone:traffic"); - - if (key == null) - return -1; - - Integer res = countryMaxSpeeds.get(key.toLowerCase()); - - return res == null ? -1 : res; + // check if maxspeed is explicitly given + if (way.hasTag("maxspeed")) + return -1; + + String key = way.getTag("zone:maxspeed"); + if (key == null) + key = way.getTag("zone:traffic"); + + if (key == null) + return -1; + + Integer res = countryMaxSpeeds.get(key.toLowerCase()); + + return res == null ? -1 : res; } - + public Integer getTrackTypeSpeed(String tracktype) { - Integer res = trackTypeSpeeds.get(tracktype); - return res == null ? -1 : res; + Integer res = trackTypeSpeeds.get(tracktype); + return res == null ? -1 : res; } - - public Integer getSurfaceSpeed(String surface) - { - Integer res = surfaceSpeeds.get(surface); - return res == null ? -1 : res; + + public Integer getSurfaceSpeed(String surface) { + Integer res = surfaceSpeeds.get(surface); + return res == null ? -1 : res; } - - public Integer getSpeed(String highway) - { - return defaultSpeeds.get(highway); + + public Integer getSpeed(String highway) { + return defaultSpeeds.get(highway); } - - public boolean hasSpeedValue(String highway) - { - return defaultSpeeds.containsKey(highway); + + public boolean hasSpeedValue(String highway) { + return defaultSpeeds.containsKey(highway); } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/VehicleFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/VehicleFlagEncoder.java index 0acfdfe389..827ec721a4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/VehicleFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/VehicleFlagEncoder.java @@ -196,7 +196,7 @@ public void createEncodedValues(List registerNewEncodedValue, Stri @Override public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.Access access) { - return handleWayTags(edgeFlags,way,access,0); + return handleWayTags(edgeFlags, way, access, 0); } public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.Access access, long relationFlags) { @@ -209,8 +209,8 @@ public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.A speed = applyMaxSpeed(way, speed); // TODO: save conditional speeds only if their value is different from the default speed - if (getConditionalSpeedInspector()!=null && getConditionalSpeedInspector().hasConditionalSpeed(way)) - if (getConditionalSpeedInspector().hasLazyEvaluatedConditions() && conditionalSpeedEncoder!=null) { + if (getConditionalSpeedInspector() != null && getConditionalSpeedInspector().hasConditionalSpeed(way)) + if (getConditionalSpeedInspector().hasLazyEvaluatedConditions() && conditionalSpeedEncoder != null) { conditionalSpeedEncoder.setBool(false, edgeFlags, true); } else { // conditional maxspeed overrides unconditional one @@ -222,8 +222,7 @@ public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.A if (way.hasTag(KEY_ESTIMATED_DISTANCE)) { if (way.hasTag(KEY_HIGHWAY, KEY_RESIDENTIAL)) { speed = addResedentialPenalty(speed, way); - } - else if (this.useAcceleration) { + } else if (this.useAcceleration) { double estDist = way.getTag(KEY_ESTIMATED_DISTANCE, Double.MAX_VALUE); speed = adjustSpeedForAcceleration(estDist, speed); } @@ -242,10 +241,10 @@ else if (this.useAcceleration) { // The following line throws exceptions when it tries to parse a value "3; 2" int lanes = Integer.parseInt(way.getTag("lanes")); if (lanes >= 2) - speed = speed < 40 ? speed : 40; + speed = speed < 40 ? speed : 40; else - speed = speed < 35 ? speed : 35; - } catch(Exception ex) { + speed = speed < 35 ? speed : 35; + } catch (Exception ex) { // do nothing } } @@ -263,7 +262,7 @@ else if (this.useAcceleration) { setAccess(access, edgeFlags, true, true); } - if (access.isConditional() && conditionalAccessEncoder!=null) + if (access.isConditional() && conditionalAccessEncoder != null) conditionalAccessEncoder.setBool(false, edgeFlags, true); } else { double ferrySpeed = ferrySpeedCalc.getSpeed(way); @@ -297,7 +296,7 @@ private void setAccess(EncodingManager.Access access, IntsRef edgeFlags, boolean if (bwd) accessEnc.setBool(true, edgeFlags, true); - if (access.isConditional() && conditionalAccessEncoder!=null) { + if (access.isConditional() && conditionalAccessEncoder != null) { if (fwd) conditionalAccessEncoder.setBool(false, edgeFlags, true); if (bwd) @@ -380,8 +379,7 @@ protected double applyMaxSpeed(ReaderWay way, double speed) { protected double getSurfaceSpeed(ReaderWay way, double speed) { // limit speed if bad surface String surface = way.getTag("surface"); - if (surface != null) - { + if (surface != null) { Integer surfaceSpeed = speedLimitHandler.getSurfaceSpeed(surface); if (speed > surfaceSpeed && surfaceSpeed != -1) return surfaceSpeed; @@ -427,19 +425,19 @@ protected int getTrackGradeLevel(String grade) { int maxGrade = 0; try { String[] values = grade.split(";"); - for(String v : values) { - int iv = Integer.parseInt(v.replace("grade","").trim()); + for (String v : values) { + int iv = Integer.parseInt(v.replace("grade", "").trim()); if (iv > maxGrade) maxGrade = iv; } return maxGrade; - } catch(Exception ex) { + } catch (Exception ex) { // do nothing } } - switch(grade) { + switch (grade) { case "grade": case "grade1": return 1; @@ -463,15 +461,15 @@ protected int getTrackGradeLevel(String grade) { return 0; double speed = baseSpeed; - if(way.hasTag(KEY_HIGHWAY, KEY_RESIDENTIAL)) { + if (way.hasTag(KEY_HIGHWAY, KEY_RESIDENTIAL)) { double estDist = way.getTag(KEY_ESTIMATED_DISTANCE, Double.MAX_VALUE); // take into account number of nodes to get an average distance between nodes double interimDistance = estDist; int interimNodes = way.getNodes().size() - 2; - if(interimNodes > 0) { - interimDistance = estDist/(interimNodes+1); + if (interimNodes > 0) { + interimDistance = estDist / (interimNodes + 1); } - if(interimDistance < 100) { + if (interimDistance < 100) { speed = speed * 0.5; } } @@ -502,13 +500,13 @@ protected int getTrackGradeLevel(String grade) { * along the way (assuming starting from 0km/h) and then uses the length to travel and the supposed maximum speed * to determine an average speed for travelling along the whole segment. * - * @param distance How long the segment to travel along is - * @param maximumSpeedInKmph The maximum speed that a vehicle can travel along this segment (usually the speed limit) + * @param distance How long the segment to travel along is + * @param maximumSpeedInKmph The maximum speed that a vehicle can travel along this segment (usually the speed limit) * @return */ public double adjustSpeedForAcceleration(double distance, double maximumSpeedInKmph) { // We only want to perform the adjustment if the road is a slower speed - main roads shouldnt be affected as much due to less junctions and changes in direction - if(maximumSpeedInKmph < ACCELERATION_SPEED_CUTOFF_MAX) { + if (maximumSpeedInKmph < ACCELERATION_SPEED_CUTOFF_MAX) { if (distance <= 0) { return maximumSpeedInKmph; } @@ -516,10 +514,10 @@ public double adjustSpeedForAcceleration(double distance, double maximumSpeedInK // slower roads can be assumed to have slower acceleration... double normalisedSpeed = maximumSpeedInKmph; - if(normalisedSpeed < ACCELERATION_SPEED_CUTOFF_MIN) + if (normalisedSpeed < ACCELERATION_SPEED_CUTOFF_MIN) normalisedSpeed = ACCELERATION_SPEED_CUTOFF_MIN; - normalisedSpeed = (normalisedSpeed -ACCELERATION_SPEED_CUTOFF_MIN) / (ACCELERATION_SPEED_CUTOFF_MAX-ACCELERATION_SPEED_CUTOFF_MIN); + normalisedSpeed = (normalisedSpeed - ACCELERATION_SPEED_CUTOFF_MIN) / (ACCELERATION_SPEED_CUTOFF_MAX - ACCELERATION_SPEED_CUTOFF_MIN); accelerationModifier = Math.pow(0.01, normalisedSpeed); @@ -539,7 +537,7 @@ public double adjustSpeedForAcceleration(double distance, double maximumSpeedInK return convertMpsToKmph(distance / (duration * 2)); } else { double timeAtMaxSpeed = distanceAtMaxSpeed / convertKmphToMps(maximumSpeedInKmph); - double averageSpeedMps = distance / (timeToMaxSpeed*2 + timeAtMaxSpeed); + double averageSpeedMps = distance / (timeToMaxSpeed * 2 + timeAtMaxSpeed); return convertMpsToKmph(averageSpeedMps); } @@ -551,22 +549,22 @@ public double adjustSpeedForAcceleration(double distance, double maximumSpeedInK /** * How many seconds does it take to reach maximum speed based on initial speed and acceleration. * - * @param initialSpeedInKmph How fast the vehicle is travelling at the start of the calculation - * @param maxSpeedInKmph The target speed to be reached - * @return How long it takes to reach the speed in seconds + * @param initialSpeedInKmph How fast the vehicle is travelling at the start of the calculation + * @param maxSpeedInKmph The target speed to be reached + * @return How long it takes to reach the speed in seconds */ private double durationToMaxSpeed(double initialSpeedInKmph, double maxSpeedInKmph) { - return (maxSpeedInKmph - initialSpeedInKmph) / accelerationKmpHpS(); + return (maxSpeedInKmph - initialSpeedInKmph) / accelerationKmpHpS(); } /** * How long in seconds does it take to reach the intended distance based on the initial travelling speed and the * maximum speed that can be travelled. * - * @param initialSpeedInKmph The speed of the vehicle when starting the calculation - * @param maxSpeedInKmph The maximum speed the vehicle can travel at - * @param distanceInM The target distance to be travelled - * @return How long it takes in seconds to reach the target distance + * @param initialSpeedInKmph The speed of the vehicle when starting the calculation + * @param maxSpeedInKmph The maximum speed the vehicle can travel at + * @param distanceInM The target distance to be travelled + * @return How long it takes in seconds to reach the target distance */ private double durationToTravelDistance(double initialSpeedInKmph, double maxSpeedInKmph, double distanceInM) { double secondsTravelled = 0; @@ -574,7 +572,7 @@ private double durationToTravelDistance(double initialSpeedInKmph, double maxSpe double currentSpeed = initialSpeedInKmph; - while(currentSpeed < maxSpeedInKmph && distanceTravelled < distanceInM) { + while (currentSpeed < maxSpeedInKmph && distanceTravelled < distanceInM) { currentSpeed += accelerationKmpHpS(); secondsTravelled += 1; distanceTravelled += convertKmphToMps(currentSpeed); @@ -582,7 +580,7 @@ private double durationToTravelDistance(double initialSpeedInKmph, double maxSpe double distanceRemaining = distanceInM - distanceTravelled; - if(distanceRemaining > 0) { + if (distanceRemaining > 0) { secondsTravelled += (distanceRemaining / convertKmphToMps(maxSpeedInKmph)); } @@ -592,17 +590,17 @@ private double durationToTravelDistance(double initialSpeedInKmph, double maxSpe /** * How far can the vehicle travel in the specified time frame * - * @param initialSpeedInKmph The starting speed of the vehicle - * @param maxSpeedInKmph The maximum travel speed - * @param duration How long is the vehicle travelling for - * @return The distance in metres that the vehicle travels in the specified time + * @param initialSpeedInKmph The starting speed of the vehicle + * @param maxSpeedInKmph The maximum travel speed + * @param duration How long is the vehicle travelling for + * @return The distance in metres that the vehicle travels in the specified time */ private double distanceTravelledInDuration(double initialSpeedInKmph, double maxSpeedInKmph, double duration) { double secondsTravelled = 0; double distanceTravelled = 0; double currentSpeed = initialSpeedInKmph; - while(currentSpeed < maxSpeedInKmph && secondsTravelled < duration) { + while (currentSpeed < maxSpeedInKmph && secondsTravelled < duration) { currentSpeed += accelerationKmpHpS(); secondsTravelled += 1; distanceTravelled += convertKmphToMps(currentSpeed); @@ -610,7 +608,7 @@ private double distanceTravelledInDuration(double initialSpeedInKmph, double max double secondsRemaining = duration - secondsTravelled; - if(secondsRemaining > 0 ) { + if (secondsRemaining > 0) { distanceTravelled += (secondsRemaining * convertKmphToMps(maxSpeedInKmph)); } @@ -620,8 +618,8 @@ private double distanceTravelledInDuration(double initialSpeedInKmph, double max /** * Convert kilometres per hour to metres per second * - * @param speedInKmph The speed to be converted in km per hour - * @return The speed in metres per second + * @param speedInKmph The speed to be converted in km per hour + * @return The speed in metres per second */ private double convertKmphToMps(double speedInKmph) { return (speedInKmph * 1000) / 3600; @@ -630,8 +628,8 @@ private double convertKmphToMps(double speedInKmph) { /** * Convert metres per second to kilometres per hour * - * @param speedInMps The speed in metres per second - * @return The speed in kilometres per hour + * @param speedInMps The speed in metres per second + * @return The speed in kilometres per hour */ private double convertMpsToKmph(double speedInMps) { return (3600 * speedInMps) / 1000; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/WheelchairFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/WheelchairFlagEncoder.java index fe4b7099ee..7d3e8fc31c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/WheelchairFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/WheelchairFlagEncoder.java @@ -53,8 +53,8 @@ public class WheelchairFlagEncoder extends FootFlagEncoder { private double problematicSpeedFactor = 1; private double preferredSpeedFactor = 1; - private OSMAttachedSidewalkProcessor osmAttachedSidewalkProcessor = new OSMAttachedSidewalkProcessor(); - private OSMPedestrianProcessor osmPedestrianProcessor = new OSMPedestrianProcessor(); + private final OSMAttachedSidewalkProcessor osmAttachedSidewalkProcessor = new OSMAttachedSidewalkProcessor(); + private final OSMPedestrianProcessor osmPedestrianProcessor = new OSMPedestrianProcessor(); protected Set acceptedPublicTransport = new HashSet<>(5); @@ -135,9 +135,9 @@ public class WheelchairFlagEncoder extends FootFlagEncoder { private final Set accessibilityRelatedAttributes = new HashSet<>(); - public WheelchairFlagEncoder(PMap configuration) { - this(configuration.getInt("speed_bits", 4), - configuration.getDouble("speed_factor", 1)); + public WheelchairFlagEncoder(PMap configuration) { + this(configuration.getInt("speed_bits", 4), + configuration.getDouble("speed_factor", 1)); problematicSpeedFactor = configuration.getDouble("problematic_speed_factor", 1); preferredSpeedFactor = configuration.getDouble("preferred_speed_factor", 1); @@ -152,7 +152,7 @@ public WheelchairFlagEncoder() { this(4, 1); } - public WheelchairFlagEncoder( int speedBits, double speedFactor ) { + public WheelchairFlagEncoder(int speedBits, double speedFactor) { super(speedBits, speedFactor); // test for the following restriction keys restrictions.add(KEY_WHEELCHAIR); @@ -279,7 +279,7 @@ public WheelchairFlagEncoder( int speedBits, double speedFactor ) { routeMap.put(NATIONAL, PREFER.getValue()); routeMap.put(REGIONAL, PREFER.getValue()); routeMap.put(LOCAL, PREFER.getValue()); - routeMap.put(OTHER , PREFER.getValue()); + routeMap.put(OTHER, PREFER.getValue()); } @Override @@ -289,73 +289,72 @@ public double getMeanSpeed() { /** * Some ways are okay but not separate for pedestrians. - * */ @Override - public EncodingManager.Access getAccess(ReaderWay way ) { - // check access restrictions + public EncodingManager.Access getAccess(ReaderWay way) { + // check access restrictions if (way.hasTag(restrictions, restrictedValues) && !(way.hasTag(restrictions, intendedValues) || way.hasTag(KEY_SIDEWALK, usableSidewalkValues))) { LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("access restrictions", way.getId(), way.getTags().toString())); return EncodingManager.Access.CAN_SKIP; } - String highwayValue = way.getTag(KEY_HIGHWAY); + String highwayValue = way.getTag(KEY_HIGHWAY); if (highwayValue == null) { - // ferries and shuttle_trains + // ferries and shuttle_trains if (way.hasTag(KEY_ROUTE, ferries)) { - // check whether information on wheelchair accessbility is available - if (way.hasTag(KEY_WHEELCHAIR)) { - // wheelchair=yes, designated, official, permissive, limited - if (way.hasTag(KEY_WHEELCHAIR, intendedValues)) { - return EncodingManager.Access.FERRY; - } - // wheelchair=no, restricted, private - if (way.hasTag(KEY_WHEELCHAIR, restrictedValues)) { + // check whether information on wheelchair accessbility is available + if (way.hasTag(KEY_WHEELCHAIR)) { + // wheelchair=yes, designated, official, permissive, limited + if (way.hasTag(KEY_WHEELCHAIR, intendedValues)) { + return EncodingManager.Access.FERRY; + } + // wheelchair=no, restricted, private + if (way.hasTag(KEY_WHEELCHAIR, restrictedValues)) { LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("no wheelchair ferry", way.getId(), way.getTags().toString())); - return EncodingManager.Access.CAN_SKIP; - } + return EncodingManager.Access.CAN_SKIP; + } } - if (way.hasTag("foot")) { - // foot=yes, designated, official, permissive, limited - if (way.hasTag("foot", intendedValues)) { + if (way.hasTag("foot")) { + // foot=yes, designated, official, permissive, limited + if (way.hasTag("foot", intendedValues)) { return EncodingManager.Access.FERRY; - } - // foot=no, restricted, private - if (way.hasTag("foot", restrictedValues)) { + } + // foot=no, restricted, private + if (way.hasTag("foot", restrictedValues)) { LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("no pedestrian ferry", way.getId(), way.getTags().toString())); return EncodingManager.Access.CAN_SKIP; - } - } - return EncodingManager.Access.WAY; + } + } + return EncodingManager.Access.WAY; } // public transport in general // railways (platform, station) if (way.hasTag("public_transport", acceptedPublicTransport) || way.hasTag("railway", acceptedPublicTransport)) { - // check whether information on wheelchair accessbility is available - if (way.hasTag(KEY_WHEELCHAIR)) { - // wheelchair=yes, designated, official, permissive, limited - if (way.hasTag(KEY_WHEELCHAIR, intendedValues)) { - return EncodingManager.Access.WAY; - } - // wheelchair=no, restricted, private - if (way.hasTag(KEY_WHEELCHAIR, restrictedValues)) { + // check whether information on wheelchair accessbility is available + if (way.hasTag(KEY_WHEELCHAIR)) { + // wheelchair=yes, designated, official, permissive, limited + if (way.hasTag(KEY_WHEELCHAIR, intendedValues)) { + return EncodingManager.Access.WAY; + } + // wheelchair=no, restricted, private + if (way.hasTag(KEY_WHEELCHAIR, restrictedValues)) { LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("no wheelchair public transport", way.getId(), way.getTags().toString())); return EncodingManager.Access.CAN_SKIP; - } + } } - if (way.hasTag("foot")) { - // foot=yes, designated, official, permissive, limited - if (way.hasTag("foot", intendedValues)) { - return EncodingManager.Access.WAY; - } - // foot=no, restricted, private - if (way.hasTag("foot", restrictedValues)) { + if (way.hasTag("foot")) { + // foot=yes, designated, official, permissive, limited + if (way.hasTag("foot", intendedValues)) { + return EncodingManager.Access.WAY; + } + // foot=no, restricted, private + if (way.hasTag("foot", restrictedValues)) { LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("no pedestrian public transport", way.getId(), way.getTags().toString())); return EncodingManager.Access.CAN_SKIP; - } - } + } + } return EncodingManager.Access.WAY; } // no highway, no ferry, no railway? --> do not accept way @@ -389,36 +388,36 @@ public EncodingManager.Access getAccess(ReaderWay way ) { return EncodingManager.Access.CAN_SKIP; } - // wheelchair=yes, designated, official, permissive, limited - if (way.hasTag(KEY_WHEELCHAIR, intendedValues)) { - return EncodingManager.Access.WAY; - } - // wheelchair=no, restricted, private - if (way.hasTag(KEY_WHEELCHAIR, restrictedValues)) { + // wheelchair=yes, designated, official, permissive, limited + if (way.hasTag(KEY_WHEELCHAIR, intendedValues)) { + return EncodingManager.Access.WAY; + } + // wheelchair=no, restricted, private + if (way.hasTag(KEY_WHEELCHAIR, restrictedValues)) { LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("wheelchair no, restricted or private", way.getId(), way.getTags().toString())); - return EncodingManager.Access.CAN_SKIP; - } + return EncodingManager.Access.CAN_SKIP; + } - // do not include nonWheelchairAccessibleHighways + // do not include nonWheelchairAccessibleHighways if (nonWheelchairAccessibleHighways.contains(highwayValue)) { - // check for wheelchair accessibility + // check for wheelchair accessibility LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("in nonWheelchairAccessibleHighways list", way.getId(), way.getTags().toString())); - return EncodingManager.Access.CAN_SKIP; + return EncodingManager.Access.CAN_SKIP; } - // foot=yes, designated, official, permissive, limited - if (way.hasTag("foot", intendedValues)) { - return EncodingManager.Access.WAY; - } + // foot=yes, designated, official, permissive, limited + if (way.hasTag("foot", intendedValues)) { + return EncodingManager.Access.WAY; + } - // foot=no, restricted, private - if (way.hasTag("foot", restrictedValues)) { + // foot=no, restricted, private + if (way.hasTag("foot", restrictedValues)) { LOGGER.trace(DEBUG_MSG_SKIPPED.formatted("pedestrian no, restricted or private", way.getId(), way.getTags().toString())); - return EncodingManager.Access.CAN_SKIP; - } + return EncodingManager.Access.CAN_SKIP; + } if (way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { - return EncodingManager.Access.WAY; + return EncodingManager.Access.WAY; } if (way.hasTag(KEY_SIDEWALK, noSidewalkValues) && assumedWheelchairAccessibleHighways.contains(highwayValue)) { @@ -444,9 +443,9 @@ public EncodingManager.Access getAccess(ReaderWay way ) { } if (fullyWheelchairAccessibleHighways.contains(highwayValue) || assumedWheelchairAccessibleHighways.contains(highwayValue) || limitedWheelchairAccessibleHighways.contains(highwayValue)) { - // check whether information on wheelchair accessbility is available and mark for suitability + // check whether information on wheelchair accessbility is available and mark for suitability way.setTag("wheelchair_accessible", true); - return EncodingManager.Access.WAY; + return EncodingManager.Access.WAY; } // anything else @@ -461,48 +460,47 @@ public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.A return edgeFlags; if (!access.isFerry()) { - // TODO: Depending on availability of sidewalk, surface, smoothness, tracktype and incline MEAN_SPEED or SLOW_SPEED should be encoded - // TODO: Maybe also implement AvoidFeaturesWeighting for Wheelchairs - - // ***************************************** Runge - // This is a trick, where we try to underrate the speed for highways that do not have tagged sidewalks. - // TODO: this actually affects travel time estimation (might be a good or negative side effect depending on context) - double speed = MEAN_SPEED; - if (way.hasTag(KEY_HIGHWAY)) - { - - String highway = way.getTag(KEY_HIGHWAY); - if (assumedWheelchairAccessibleHighways.contains(highway) && !way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { + // TODO: Depending on availability of sidewalk, surface, smoothness, tracktype and incline MEAN_SPEED or SLOW_SPEED should be encoded + // TODO: Maybe also implement AvoidFeaturesWeighting for Wheelchairs + + // ***************************************** Runge + // This is a trick, where we try to underrate the speed for highways that do not have tagged sidewalks. + // TODO: this actually affects travel time estimation (might be a good or negative side effect depending on context) + double speed = MEAN_SPEED; + if (way.hasTag(KEY_HIGHWAY)) { + + String highway = way.getTag(KEY_HIGHWAY); + if (assumedWheelchairAccessibleHighways.contains(highway) && !way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { speed *= 0.8d; - } - if (fullyWheelchairAccessibleHighways.contains(highway)) { - if (highway.equalsIgnoreCase(KEY_FOOTWAY) + } + if (fullyWheelchairAccessibleHighways.contains(highway)) { + if (highway.equalsIgnoreCase(KEY_FOOTWAY) || highway.equalsIgnoreCase(KEY_PEDESTRIAN) || highway.equalsIgnoreCase(KEY_LIVING_STREET) || highway.equalsIgnoreCase("residential") ) { - speed *= 1.25d; - if (way.hasTag(KEY_FOOTWAY, KEY_CROSSING) || way.hasTag(KEY_HIGHWAY, KEY_CROSSING)) { - speed *= 2d; // should not exceed 10 in total due to encoding restrictions - } - } - // residential, unclassified - else if (!way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { - speed *= 0.9d; - } - } - if (restrictedWheelchairHighways.contains(highway) && (way.hasTag("foot", intendedValues) || way.hasTag(KEY_WHEELCHAIR, intendedValues))) { - speed *= 1.25d; - if (way.hasTag(KEY_CYCLEWAY, KEY_CROSSING) || way.hasTag(KEY_BRIDLEWAY, KEY_CROSSING) || way.hasTag(KEY_HIGHWAY, KEY_CROSSING)) { - speed *= 2d; // should not exceed 10 in total due to encoding restrictions - } - } - } + speed *= 1.25d; + if (way.hasTag(KEY_FOOTWAY, KEY_CROSSING) || way.hasTag(KEY_HIGHWAY, KEY_CROSSING)) { + speed *= 2d; // should not exceed 10 in total due to encoding restrictions + } + } + // residential, unclassified + else if (!way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { + speed *= 0.9d; + } + } + if (restrictedWheelchairHighways.contains(highway) && (way.hasTag("foot", intendedValues) || way.hasTag(KEY_WHEELCHAIR, intendedValues))) { + speed *= 1.25d; + if (way.hasTag(KEY_CYCLEWAY, KEY_CROSSING) || way.hasTag(KEY_BRIDLEWAY, KEY_CROSSING) || way.hasTag(KEY_HIGHWAY, KEY_CROSSING)) { + speed *= 2d; // should not exceed 10 in total due to encoding restrictions + } + } + } if (way.hasTag(KEY_SURFACE, problematicSurfaces) || way.hasTag(KEY_SMOOTHNESS, problematicSmoothnesses) || way.hasTag(KEY_TRACKTYPE, problematicTracktypes) ) - speed *= problematicSpeedFactor; + speed *= problematicSpeedFactor; if (way.hasTag(KEY_SURFACE, preferredSurfaces) || way.hasTag(KEY_SMOOTHNESS, preferredSmoothnesses) @@ -524,8 +522,7 @@ else if (!way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { Integer priorityFromRelation = routeMap.get(footRouteEnc.getEnum(false, edgeFlags)); priorityWayEncoder.setDecimal(false, edgeFlags, PriorityCode.getFactor(handlePriority(way, priorityFromRelation != null ? priorityFromRelation : 0))); - } - else { + } else { double ferrySpeed = ferrySpeedCalc.getSpeed(way); setSpeed(false, edgeFlags, ferrySpeed); accessEnc.setBool(false, edgeFlags, true); @@ -545,119 +542,114 @@ public long handleNodeTags(ReaderNode node) { long encoded = super.handleNodeTags(node); // We want to be more strict with fords, as only if it is declared as wheelchair accessible do we want to cross it if (isBlockFords() && (node.hasTag(KEY_HIGHWAY, "ford") || node.hasTag("ford")) && !node.hasTag(KEY_WHEELCHAIR, intendedValues)) { - encoded = getEncoderBit(); + encoded = getEncoderBit(); } return encoded; } @Override protected int handlePriority(ReaderWay way, int priorityFromRelation) { - int positiveFeatures = 0; - int negativeFeatures = 0; + int positiveFeatures = 0; + int negativeFeatures = 0; - // http://wiki.openstreetmap.org/wiki/DE:Key:traffic_calming + // http://wiki.openstreetmap.org/wiki/DE:Key:traffic_calming String highwayValue = way.getTag(KEY_HIGHWAY); double maxSpeed = getMaxSpeed(way); if (isValidSpeed(maxSpeed)) { - if (maxSpeed > 50) { - negativeFeatures++; - if (maxSpeed > 60) { - negativeFeatures++; - if (maxSpeed > 80) { - negativeFeatures++; - } - } - } - - if (maxSpeed <= 20) { - positiveFeatures+=1; - } + if (maxSpeed > 50) { + negativeFeatures++; + if (maxSpeed > 60) { + negativeFeatures++; + if (maxSpeed > 80) { + negativeFeatures++; + } + } + } + + if (maxSpeed <= 20) { + positiveFeatures += 1; + } } if (way.hasTag("tunnel", intendedValues)) { - negativeFeatures+=4; + negativeFeatures += 4; } - if (( way.hasTag(KEY_BICYCLE, KEY_DESIGNATED) + if ((way.hasTag(KEY_BICYCLE, KEY_DESIGNATED) || way.hasTag(KEY_BICYCLE, KEY_OFFICIAL) || way.hasTag(KEY_CYCLEWAY, KEY_DESIGNATED) || way.hasTag(KEY_CYCLEWAY, KEY_OFFICIAL) || way.hasTag(KEY_HORSE, KEY_DESIGNATED) || way.hasTag(KEY_HORSE, KEY_OFFICIAL) - ) && !way.hasTag(restrictions, intendedValues)) { - negativeFeatures+=4; + ) && !way.hasTag(restrictions, intendedValues)) { + negativeFeatures += 4; } // put penalty on these ways if no further information is available if (limitedWheelchairAccessibleHighways.contains(highwayValue)) { - boolean hasAccessibilityRelatedAttributes = false; - for (String key : accessibilityRelatedAttributes) { - hasAccessibilityRelatedAttributes |= way.hasTag(key); - } - if (!hasAccessibilityRelatedAttributes) { - negativeFeatures+=2; - } + boolean hasAccessibilityRelatedAttributes = false; + for (String key : accessibilityRelatedAttributes) { + hasAccessibilityRelatedAttributes |= way.hasTag(key); + } + if (!hasAccessibilityRelatedAttributes) { + negativeFeatures += 2; + } } if (assumedWheelchairAccessibleHighways.contains(highwayValue)) { - if (highwayValue.equalsIgnoreCase("trunk") || highwayValue.equalsIgnoreCase("trunk_link")) { - negativeFeatures+=5; - } - else if (highwayValue.equalsIgnoreCase("primary") || highwayValue.equalsIgnoreCase("primary_link")) { - negativeFeatures+=3; - } - else { // secondary, tertiary, road, service - negativeFeatures+=1; - } + if (highwayValue.equalsIgnoreCase("trunk") || highwayValue.equalsIgnoreCase("trunk_link")) { + negativeFeatures += 5; + } else if (highwayValue.equalsIgnoreCase("primary") || highwayValue.equalsIgnoreCase("primary_link")) { + negativeFeatures += 3; + } else { // secondary, tertiary, road, service + negativeFeatures += 1; + } } // do not rate foot features twice boolean isFootEvaluated = false; if (fullyWheelchairAccessibleHighways.contains(highwayValue)) { - if (highwayValue.equalsIgnoreCase(KEY_FOOTWAY) || highwayValue.equalsIgnoreCase(KEY_PEDESTRIAN) || highwayValue.equalsIgnoreCase(KEY_LIVING_STREET)) { - positiveFeatures+=5; - isFootEvaluated = true; - } - else { - // residential, unclassified - negativeFeatures++; - } + if (highwayValue.equalsIgnoreCase(KEY_FOOTWAY) || highwayValue.equalsIgnoreCase(KEY_PEDESTRIAN) || highwayValue.equalsIgnoreCase(KEY_LIVING_STREET)) { + positiveFeatures += 5; + isFootEvaluated = true; + } else { + // residential, unclassified + negativeFeatures++; + } } if (!isFootEvaluated) { - // key=sidewalk - if (way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { - positiveFeatures+=5; + // key=sidewalk + if (way.hasTag(KEY_SIDEWALK, usableSidewalkValues)) { + positiveFeatures += 5; + } + // key=foot + else if (way.hasTag("foot", KEY_DESIGNATED)) { + positiveFeatures += 5; + } else if (way.hasTag("foot", intendedValues) || way.hasTag(KEY_BICYCLE, KEY_DESIGNATED)) { + positiveFeatures += 2; } - // key=foot - else if (way.hasTag("foot", KEY_DESIGNATED)) { - positiveFeatures += 5; - } - else if (way.hasTag("foot", intendedValues) || way.hasTag(KEY_BICYCLE, KEY_DESIGNATED)) { - positiveFeatures += 2; - } } if (!osmAttachedSidewalkProcessor.hasSidewalkInfo(way) && !osmPedestrianProcessor.isPedestrianisedWay(way)) - negativeFeatures+=2; + negativeFeatures += 2; int sum = positiveFeatures - negativeFeatures; if (sum <= -6) return AVOID_AT_ALL_COSTS.getValue(); else if (sum <= -3) return REACH_DEST.getValue(); else if (sum <= -1) return AVOID_IF_POSSIBLE.getValue(); - else if (sum ==0) return UNCHANGED.getValue(); + else if (sum == 0) return UNCHANGED.getValue(); else if (sum <= 2) return PREFER.getValue(); else if (sum <= 5) return VERY_NICE.getValue(); else return BEST.getValue(); } @Override - public String toString() - { + public String toString() { return FlagEncoderNames.WHEELCHAIR; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/CommonBikeFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/CommonBikeFlagEncoder.java index bf86b09bf5..3a1c2ea24c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/CommonBikeFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/CommonBikeFlagEncoder.java @@ -119,7 +119,7 @@ protected void setProperties(PMap properties) { // MARQ24 MOD START protected CommonBikeFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts, boolean considerElevation) { - // MARQ24 MOD END + // MARQ24 MOD END super(speedBits, speedFactor, maxTurnCosts); // strict set, usually vehicle and agricultural/forestry are ignored by cyclists restrictions.addAll(Arrays.asList(KEY_BICYCLE, "vehicle", "access")); @@ -346,8 +346,8 @@ public EncodingManager.Access getAccess(ReaderWay way) { // MARQ24 MOD START // Runge: http://www.openstreetmap.org/way/1700503 || way.hasTag(KEY_BICYCLE_ROAD, "yes") - // MARQ24 MOD END - ){ + // MARQ24 MOD END + ) { return isPermittedWayConditionallyRestricted(way); } @@ -410,7 +410,7 @@ public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.A wayTypeSpeed = applyMaxSpeed(way, wayTypeSpeed); handleSpeed(edgeFlags, way, wayTypeSpeed); handleBikeRelated(edgeFlags, way, priorityFromRelation > UNCHANGED.getValue()); - if (access.isConditional() && conditionalAccessEncoder!=null) + if (access.isConditional() && conditionalAccessEncoder != null) conditionalAccessEncoder.setBool(false, edgeFlags, true); boolean isRoundabout = way.hasTag(KEY_JUNCTION, "roundabout") || way.hasTag(KEY_JUNCTION, "circular"); if (isRoundabout) { @@ -447,13 +447,13 @@ int getSpeed(ReaderWay way) { // MARQ24 - so if this is a pushing section (like path, track or footway) BUT have additional bicycle attributes // then we treat this way as it was tagged as "cycleway"... if (isPushingWay && - ( - (way.hasTag("foot", "yes") && way.hasTag(KEY_SEGREGATED, "yes")) - || way.hasTag(KEY_BICYCLE, "yes") - || way.hasTag(KEY_BICYCLE, KEY_DESIGNATED) - || way.hasTag(KEY_BICYCLE, KEY_OFFICIAL) - ) - && !isSteps + ( + (way.hasTag("foot", "yes") && way.hasTag(KEY_SEGREGATED, "yes")) + || way.hasTag(KEY_BICYCLE, "yes") + || way.hasTag(KEY_BICYCLE, KEY_DESIGNATED) + || way.hasTag(KEY_BICYCLE, KEY_OFFICIAL) + ) + && !isSteps ) { isCyclewayLikeWay = true; highwaySpeed = getHighwaySpeed(KEY_CYCLEWAY); @@ -464,9 +464,9 @@ int getSpeed(ReaderWay way) { SpeedValue surfaceSpeed = surfaceSpeeds.get(s); if (surfaceSpeed != null && (!isPushingWay || isCyclewayLikeWay)) { // ok if no specific highway speed is set we will use the surface speed... - if(highwaySpeed == null){ + if (highwaySpeed == null) { speed = surfaceSpeed.speed; - }else{ + } else { speed = calcHighwaySpeedBasedOnSurface(highwaySpeed, surfaceSpeed); } } @@ -476,9 +476,9 @@ int getSpeed(ReaderWay way) { if (!Helper.isEmpty(tt)) { SpeedValue tracktypeSpeed = trackTypeSpeeds.get(tt); if (tracktypeSpeed != null && (!isPushingWay || isCyclewayLikeWay)) { - if(highwaySpeed == null){ + if (highwaySpeed == null) { speed = tracktypeSpeed.speed; - }else{ + } else { speed = calcHighwaySpeedBasedOnSurface(highwaySpeed, tracktypeSpeed); } } @@ -486,8 +486,8 @@ int getSpeed(ReaderWay way) { } // if the speed have not been set yet... - if (speed == Integer.MIN_VALUE){ - if(highwaySpeed != null) { + if (speed == Integer.MIN_VALUE) { + if (highwaySpeed != null) { if (!way.hasTag(KEY_SERVICE)) { speed = highwaySpeed.speed; } else { @@ -495,22 +495,22 @@ int getSpeed(ReaderWay way) { // considered as min "living street" speed (or slower)... speed = Math.min(highwaySpeeds.get(KEY_LIVING_STREET).speed, highwaySpeed.speed); } - }else { + } else { speed = PUSHING_SECTION_SPEED; } } // MARQ24 MOD START - if(speed <= PUSHING_SECTION_SPEED) { + if (speed <= PUSHING_SECTION_SPEED) { if (!isSteps) { // MARQ24 if we are still on pushing section speed, then we at least double the speed in the case // that the way is 'segregated' (but of course we sill ignore steps)... - // MARQ24 MOD END + // MARQ24 MOD END // Increase speed in case of segregated if (way.hasTag(KEY_SEGREGATED, "yes")) { speed = PUSHING_SECTION_SPEED * 2; } - // MARQ24 MOD START + // MARQ24 MOD START } else { // MARQ24: make sure that steps will always get a very slow speed... speed = PUSHING_SECTION_SPEED / 2; @@ -525,13 +525,13 @@ int getSpeed(ReaderWay way) { The order of speed arguments MAKE a difference !!! When highway & surface SpeedValue have the UpdateType=BOTH then the return value will be always the speed of the last speed argument (surface.speed)!!! */ - public int calcHighwaySpeedBasedOnSurface(SpeedValue highway, SpeedValue surface){ + public int calcHighwaySpeedBasedOnSurface(SpeedValue highway, SpeedValue surface) { if (highway.speed.equals(surface.speed)) { return highway.speed; - } else if(highway.speed > surface.speed) { + } else if (highway.speed > surface.speed) { // highway = 18 (residential) // surface = 4 (gravel) - switch (highway.type){ + switch (highway.type) { case UPGRADE_ONLY: return highway.speed; @@ -547,7 +547,7 @@ public int calcHighwaySpeedBasedOnSurface(SpeedValue highway, SpeedValue surface } else { // highway = 8 (cycleway) // surface = 18 (asphalt) - switch (highway.type){ + switch (highway.type) { case DOWNGRADE_ONLY: return highway.speed; case UPGRADE_ONLY: @@ -634,11 +634,11 @@ void collect(ReaderWay way, double wayTypeSpeed, TreeMap weight String service = way.getTag(KEY_SERVICE); String highway = way.getTag(KEY_HIGHWAY); // MARQ24 MOD START - if(!isRoadBikeEncoder){ - // MARQ24 MOD END + if (!isRoadBikeEncoder) { + // MARQ24 MOD END // MARQ24 MOD START if (way.hasTag(KEY_BICYCLE, KEY_DESIGNATED) || way.hasTag(KEY_BICYCLE, KEY_OFFICIAL) || way.hasTag(KEY_BICYCLE_ROAD, "yes")) { - // MARQ24 MOD END + // MARQ24 MOD END if ("path".equals(highway)) { weightToPrioMap.put(100d, VERY_NICE.getValue()); } else { @@ -646,13 +646,13 @@ void collect(ReaderWay way, double wayTypeSpeed, TreeMap weight } } if (KEY_CYCLEWAY.equals(highway)) { - if (way.hasTag("foot", intendedValues) && !way.hasTag(KEY_SEGREGATED, "yes")){ + if (way.hasTag("foot", intendedValues) && !way.hasTag(KEY_SEGREGATED, "yes")) { weightToPrioMap.put(100d, PREFER.getValue()); } else { weightToPrioMap.put(100d, VERY_NICE.getValue()); } } - // MARQ24 MOD START + // MARQ24 MOD START } // MARQ24 MOD END @@ -675,15 +675,15 @@ void collect(ReaderWay way, double wayTypeSpeed, TreeMap weight || "parking_aisle".equals(service)) { int pushingSectionPrio = AVOID_IF_POSSIBLE.getValue(); // MARQ24 MOD START - if(!isRoadBikeEncoder) { - // MARQ24 MOD END + if (!isRoadBikeEncoder) { + // MARQ24 MOD END if (way.hasTag(KEY_BICYCLE, "use_sidepath") || way.hasTag(KEY_BICYCLE, "yes") || way.hasTag(KEY_BICYCLE, "permissive")) { pushingSectionPrio = PREFER.getValue(); } if (way.hasTag(KEY_BICYCLE, KEY_DESIGNATED) || way.hasTag(KEY_BICYCLE, KEY_OFFICIAL)) { pushingSectionPrio = VERY_NICE.getValue(); } - // MARQ24 MOD START + // MARQ24 MOD START } // MARQ24 MOD END @@ -736,16 +736,16 @@ void handleBikeRelated(IntsRef edgeFlags, ReaderWay way, boolean partOfCycleRela WayType wayType; if (roadValues.contains(highway)) { wayType = WayType.ROAD; - }else { + } else { wayType = WayType.OTHER_SMALL_WAY; } boolean isPushingSection = isPushingSection(way); if (isPushingSection || KEY_STEPS.equals(highway)) { wayType = WayType.PUSHING_SECTION; - } else{ + } else { // boost "none identified" partOfCycleRelation - if(!isRoadBikeEncoder && partOfCycleRelation){ + if (!isRoadBikeEncoder && partOfCycleRelation) { wayType = WayType.CYCLEWAY; } @@ -773,7 +773,7 @@ protected void handleSpeed(IntsRef edgeFlags, ReaderWay way, double speed) { || way.hasTag("bicycle:forward", "no"); //MARQ24 MOD START if (!way.hasTag(KEY_BICYCLE_ROAD, "yes") && (isOneway || way.hasTag(KEY_JUNCTION, "roundabout")) - //MARQ24 MOD END + //MARQ24 MOD END && !way.hasTag(KEY_ONEWAY_BICYCLE, "no") && !way.hasTag("bicycle:backward") && !way.hasTag(KEY_CYCLEWAY, oppositeLanes) @@ -797,6 +797,7 @@ protected void setHighwaySpeed(String highway, int speed) { protected void setHighwaySpeed(String highway, SpeedValue speed) { highwaySpeeds.put(highway, speed); } + SpeedValue getHighwaySpeed(String key) { return highwaySpeeds.get(key); } @@ -804,6 +805,7 @@ SpeedValue getHighwaySpeed(String key) { protected void setTrackTypeSpeed(String tracktype, int speed) { trackTypeSpeeds.put(tracktype, new SpeedValue(speed)); } + protected void setTrackTypeSpeed(String tracktype, SpeedValue speed) { trackTypeSpeeds.put(tracktype, speed); } @@ -811,9 +813,11 @@ protected void setTrackTypeSpeed(String tracktype, SpeedValue speed) { protected void setSurfaceSpeed(String surface, int speed) { surfaceSpeeds.put(surface, new SpeedValue(speed)); } + protected void setSurfaceSpeed(String surface, SpeedValue speed) { surfaceSpeeds.put(surface, speed); } + SpeedValue getSurfaceSpeed(String key) { return surfaceSpeeds.get(key); } @@ -863,18 +867,18 @@ protected enum UpdateType { protected static class SpeedValue { private final Integer speed; - private UpdateType type = UpdateType.BOTH; + private UpdateType type = UpdateType.BOTH; - private SpeedValue(Integer speed){ + private SpeedValue(Integer speed) { this.speed = speed; } - protected SpeedValue(Integer speed, UpdateType type){ + protected SpeedValue(Integer speed, UpdateType type) { this.speed = speed; this.type = type; } - public String toString(){ + public String toString() { return switch (type) { case BOTH -> speed + " [BOTH]"; case UPGRADE_ONLY -> speed + " [UP]"; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/ElectroBikeFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/ElectroBikeFlagEncoder.java index d4fd5e9be4..1d4d77d6a1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/ElectroBikeFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/ElectroBikeFlagEncoder.java @@ -1,35 +1,32 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.flagencoders.bike; import com.graphhopper.util.PMap; import org.heigit.ors.routing.graphhopper.extensions.flagencoders.FlagEncoderNames; -public class ElectroBikeFlagEncoder extends CommonBikeFlagEncoder -{ +public class ElectroBikeFlagEncoder extends CommonBikeFlagEncoder { private static final int MEAN_SPEED = 20; - public ElectroBikeFlagEncoder(PMap properties) - { + public ElectroBikeFlagEncoder(PMap properties) { this((int) properties.getLong("speed_bits", 4) + (properties.getBool("consider_elevation", false) ? 1 : 0), properties.getLong("speed_factor", 2), properties.getBool("turn_costs", false) ? 1 : 0, properties.getBool("consider_elevation", false)); setProperties(properties); } - - public ElectroBikeFlagEncoder( int speedBits, double speedFactor, int maxTurnCosts, boolean considerElevation) - { + + public ElectroBikeFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts, boolean considerElevation) { super(speedBits, speedFactor, maxTurnCosts, considerElevation); preferHighwayTags.add("service"); @@ -50,29 +47,29 @@ public ElectroBikeFlagEncoder( int speedBits, double speedFactor, int maxTurnCos setSurfaceSpeed("cobblestone:flattened", 11); setSurfaceSpeed("sett", 11); setSurfaceSpeed("concrete", 21); - setSurfaceSpeed("concrete:lanes", 18); - setSurfaceSpeed("concrete:plates", 18); - setSurfaceSpeed("paving_stones", 13); - setSurfaceSpeed("paving_stones:30", 13); - setSurfaceSpeed("unpaved", 15); - setSurfaceSpeed("compacted", 17); - setSurfaceSpeed("dirt", 11); - setSurfaceSpeed("earth", 13); - setSurfaceSpeed("fine_gravel", 19); - setSurfaceSpeed("grass", 9); - setSurfaceSpeed("grass_paver", 9); - setSurfaceSpeed("gravel", 13); - setSurfaceSpeed("ground", 13); - setSurfaceSpeed("ice", PUSHING_SECTION_SPEED / 2); - setSurfaceSpeed("metal", 11); - setSurfaceSpeed("mud", 11); - setSurfaceSpeed("pebblestone", 18); - setSurfaceSpeed("salt", 7); - setSurfaceSpeed("sand", 7); - setSurfaceSpeed("wood", 7); + setSurfaceSpeed("concrete:lanes", 18); + setSurfaceSpeed("concrete:plates", 18); + setSurfaceSpeed("paving_stones", 13); + setSurfaceSpeed("paving_stones:30", 13); + setSurfaceSpeed("unpaved", 15); + setSurfaceSpeed("compacted", 17); + setSurfaceSpeed("dirt", 11); + setSurfaceSpeed("earth", 13); + setSurfaceSpeed("fine_gravel", 19); + setSurfaceSpeed("grass", 9); + setSurfaceSpeed("grass_paver", 9); + setSurfaceSpeed("gravel", 13); + setSurfaceSpeed("ground", 13); + setSurfaceSpeed("ice", PUSHING_SECTION_SPEED / 2); + setSurfaceSpeed("metal", 11); + setSurfaceSpeed("mud", 11); + setSurfaceSpeed("pebblestone", 18); + setSurfaceSpeed("salt", 7); + setSurfaceSpeed("sand", 7); + setSurfaceSpeed("wood", 7); setHighwaySpeed("living_street", 9); - setHighwaySpeed("steps", PUSHING_SECTION_SPEED/2); + setHighwaySpeed("steps", PUSHING_SECTION_SPEED / 2); setHighwaySpeed("cycleway", 21); setHighwaySpeed("path", 13); setHighwaySpeed("footway", 7); @@ -91,7 +88,7 @@ public ElectroBikeFlagEncoder( int speedBits, double speedFactor, int maxTurnCos setHighwaySpeed("secondary_link", 21); setHighwaySpeed("tertiary", 21); setHighwaySpeed("tertiary_link", 21); - + addPushingSection("path"); addPushingSection("footway"); addPushingSection("pedestrian"); @@ -114,14 +111,12 @@ public double getMeanSpeed() { } @Override - protected double getDownhillMaxSpeed() - { - return 30; - } - + protected double getDownhillMaxSpeed() { + return 30; + } + @Override - public String toString() - { + public String toString() { return FlagEncoderNames.BIKE_ELECTRO; } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/MountainBikeFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/MountainBikeFlagEncoder.java index cce5ca718a..9292304313 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/MountainBikeFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/MountainBikeFlagEncoder.java @@ -1,14 +1,14 @@ /* * Licensed to GraphHopper GmbH under one or more contributor - * license agreements. See the NOTICE file distributed with this work for + * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. - * - * GraphHopper GmbH licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in + * + * GraphHopper GmbH licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -39,10 +39,10 @@ public class MountainBikeFlagEncoder extends CommonBikeFlagEncoder { public MountainBikeFlagEncoder(PMap properties) { this( - properties.getInt("speed_bits", 4 + (properties.getBool("consider_elevation", false) ? 1 : 0)), - properties.getDouble("speed_factor", 2), - properties.getBool("turn_costs", false) ? 1 : 0, - properties.getBool("consider_elevation", false) + properties.getInt("speed_bits", 4 + (properties.getBool("consider_elevation", false) ? 1 : 0)), + properties.getDouble("speed_factor", 2), + properties.getBool("turn_costs", false) ? 1 : 0, + properties.getBool("consider_elevation", false) ); setProperties(properties); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RegularBikeFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RegularBikeFlagEncoder.java index b4534bce26..1b85f15eea 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RegularBikeFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RegularBikeFlagEncoder.java @@ -1,14 +1,14 @@ /* * Licensed to GraphHopper GmbH under one or more contributor - * license agreements. See the NOTICE file distributed with this work for + * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. - * - * GraphHopper GmbH licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in + * + * GraphHopper GmbH licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,14 +33,14 @@ public class RegularBikeFlagEncoder extends CommonBikeFlagEncoder { public RegularBikeFlagEncoder(PMap properties) { this( - // MARQ24 MOD START - properties.getInt("speed_bits", 4 + (properties.getBool("consider_elevation", false) ? 1 : 0)), - // MARQ24 MOD END - properties.getDouble("speed_factor", 2), - properties.getBool("turn_costs", false) ? 1 : 0 - // MARQ24 MOD START - ,properties.getBool("consider_elevation", false) - // MARQ24 MOD END + // MARQ24 MOD START + properties.getInt("speed_bits", 4 + (properties.getBool("consider_elevation", false) ? 1 : 0)), + // MARQ24 MOD END + properties.getDouble("speed_factor", 2), + properties.getBool("turn_costs", false) ? 1 : 0 + // MARQ24 MOD START + , properties.getBool("consider_elevation", false) + // MARQ24 MOD END ); setProperties(properties); } @@ -78,7 +78,7 @@ boolean isPushingSection(ReaderWay way) { String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); return super.isPushingSection(way) || "track".equals(highway) && trackType != null - // MARQ24 MOD START - by Runge + // MARQ24 MOD START - by Runge && !("grade1".equals(trackType) || "grade2".equals(trackType) || "grade3".equals(trackType)); // MARQ24 MOD END } @@ -92,8 +92,7 @@ public String toString() { // MARQ24 MOD START @Override - protected double getDownhillMaxSpeed() - { + protected double getDownhillMaxSpeed() { return 50; } // MARQ24 MOD END diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RoadBikeFlagEncoder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RoadBikeFlagEncoder.java index bab370dfc6..cb3c102eec 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RoadBikeFlagEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/bike/RoadBikeFlagEncoder.java @@ -54,15 +54,15 @@ public RoadBikeFlagEncoder() { public RoadBikeFlagEncoder(PMap properties) { this( - // MARQ24 MOD START - //(int) properties.getLong("speed_bits", 4), - properties.getInt("speed_bits", 4 + (properties.getBool("consider_elevation", false) ? 1 : 0)), - // MARQ24 MOD END - properties.getDouble("speed_factor", 2), - properties.getBool("turn_costs", false) ? 1 : 0 - // MARQ24 MOD START - ,properties.getBool("consider_elevation", false) - // MARQ24 MOD END + // MARQ24 MOD START + //(int) properties.getLong("speed_bits", 4), + properties.getInt("speed_bits", 4 + (properties.getBool("consider_elevation", false) ? 1 : 0)), + // MARQ24 MOD END + properties.getDouble("speed_factor", 2), + properties.getBool("turn_costs", false) ? 1 : 0 + // MARQ24 MOD START + , properties.getBool("consider_elevation", false) + // MARQ24 MOD END ); setProperties(properties); } @@ -74,7 +74,7 @@ public RoadBikeFlagEncoder(String propertiesStr) { // MARQ24 MOD START public RoadBikeFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts, boolean considerElevation) { super(speedBits, speedFactor, maxTurnCosts, considerElevation); - // MARQ24 MOD END + // MARQ24 MOD END preferHighwayTags.add("road"); preferHighwayTags.add(VAL_SECONDARY); preferHighwayTags.add(VAL_SECONDARY_LINK); @@ -156,39 +156,39 @@ public RoadBikeFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts, preferHighwayTags.add(VAL_UNCLASSIFIED); // adjusted speeds... - setHighwaySpeed("trunk", 20); - setHighwaySpeed("trunk_link", 20); - setHighwaySpeed("primary", 22); - setHighwaySpeed("primary_link", 22); - setHighwaySpeed(VAL_SECONDARY, 24); - setHighwaySpeed(VAL_SECONDARY_LINK, 24); - setHighwaySpeed(VAL_TERTIARY, 26); - setHighwaySpeed(VAL_TERTIARY_LINK, 26); - setHighwaySpeed("road", 20); - setHighwaySpeed(VAL_UNCLASSIFIED, 20); - setHighwaySpeed(VAL_RESIDENTIAL, new SpeedValue(18, UpdateType.DOWNGRADE_ONLY)); + setHighwaySpeed("trunk", 20); + setHighwaySpeed("trunk_link", 20); + setHighwaySpeed("primary", 22); + setHighwaySpeed("primary_link", 22); + setHighwaySpeed(VAL_SECONDARY, 24); + setHighwaySpeed(VAL_SECONDARY_LINK, 24); + setHighwaySpeed(VAL_TERTIARY, 26); + setHighwaySpeed(VAL_TERTIARY_LINK, 26); + setHighwaySpeed("road", 20); + setHighwaySpeed(VAL_UNCLASSIFIED, 20); + setHighwaySpeed(VAL_RESIDENTIAL, new SpeedValue(18, UpdateType.DOWNGRADE_ONLY)); // make sure that we will avoid 'cycleway' & 'service' ways where ever // it is possible... - setHighwaySpeed("cycleway", new SpeedValue(8, UpdateType.DOWNGRADE_ONLY)); - setHighwaySpeed(VAL_SERVICE, new SpeedValue(8, UpdateType.DOWNGRADE_ONLY)); + setHighwaySpeed("cycleway", new SpeedValue(8, UpdateType.DOWNGRADE_ONLY)); + setHighwaySpeed(VAL_SERVICE, new SpeedValue(8, UpdateType.DOWNGRADE_ONLY)); // overwriting also the SurfaceSpeeds... to the "max" of the residential speed - setSurfaceSpeed("paved", new SpeedValue(18, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("asphalt", new SpeedValue(18, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("concrete", new SpeedValue(18, UpdateType.UPGRADE_ONLY)); - - setSurfaceSpeed("concrete:lanes", new SpeedValue(16, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("concrete:plates", new SpeedValue(16, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("paving_stones", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("paving_stones:30", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("cobblestone", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("cobblestone:flattened", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); - setSurfaceSpeed("sett", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("paved", new SpeedValue(18, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("asphalt", new SpeedValue(18, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("concrete", new SpeedValue(18, UpdateType.UPGRADE_ONLY)); + + setSurfaceSpeed("concrete:lanes", new SpeedValue(16, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("concrete:plates", new SpeedValue(16, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("paving_stones", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("paving_stones:30", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("cobblestone", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("cobblestone:flattened", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); + setSurfaceSpeed("sett", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); // overwriting also the trackTypeSpeeds... to the "max" of the residential speed - setTrackTypeSpeed(VAL_GRADE_1, new SpeedValue(18, UpdateType.UPGRADE_ONLY)); - setTrackTypeSpeed("grade2", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); + setTrackTypeSpeed(VAL_GRADE_1, new SpeedValue(18, UpdateType.UPGRADE_ONLY)); + setTrackTypeSpeed("grade2", new SpeedValue(10, UpdateType.UPGRADE_ONLY)); // HSW - asphalt cycleway vs asphalt roundabout // http://localhost:3035/directions?n1=51.965101&n2=8.24595&n3=18&a=51.965555,8.243968,51.964878,8.245057&b=1c&c=0&g1=-1&g2=0&h2=3&k1=en-US&k2=km diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/AbstractGraphBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/AbstractGraphBuilder.java index d93794ef3d..e07dc36340 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/AbstractGraphBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/AbstractGraphBuilder.java @@ -1,24 +1,24 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.graphbuilders; import java.util.Map; public abstract class AbstractGraphBuilder implements GraphBuilder { - protected Map parameters; + protected Map parameters; - public void setParameters(Map parameters) { - this.parameters = parameters; - } + public void setParameters(Map parameters) { + this.parameters = parameters; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/GraphBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/GraphBuilder.java index 52e703bcdb..1dba58dd94 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/GraphBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/GraphBuilder.java @@ -1,38 +1,37 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.graphbuilders; -import java.util.List; -import java.util.Map; - import com.carrotsearch.hppc.LongArrayList; import com.graphhopper.GraphHopper; import com.graphhopper.reader.ReaderWay; import com.graphhopper.storage.IntsRef; import com.graphhopper.util.EdgeIteratorState; - import org.heigit.ors.plugins.Plugin; import org.heigit.ors.routing.graphhopper.extensions.DataReaderContext; +import java.util.List; +import java.util.Map; + public interface GraphBuilder extends Plugin { - void init(GraphHopper graphhopper) throws Exception; - - boolean createEdges(DataReaderContext readerCntx, ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) throws Exception; - - void finish(); - - String getName(); - - void setParameters(Map parameters); + void init(GraphHopper graphhopper) throws Exception; + + boolean createEdges(DataReaderContext readerCntx, ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) throws Exception; + + void finish(); + + String getName(); + + void setParameters(Map parameters); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/InFieldGraphBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/InFieldGraphBuilder.java index 5c4bbe57d9..1f2f300186 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/InFieldGraphBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/graphbuilders/InFieldGraphBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.graphbuilders; @@ -25,237 +25,233 @@ import com.graphhopper.routing.util.TraversalMode; import com.graphhopper.routing.weighting.FastestWeighting; import com.graphhopper.routing.weighting.Weighting; -import com.graphhopper.storage.GraphExtension; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.storage.IntsRef; import com.graphhopper.storage.RAMDirectory; import com.graphhopper.util.DistanceCalc; import com.graphhopper.util.DistanceCalcEarth; import com.graphhopper.util.EdgeIteratorState; -import com.graphhopper.util.Helper; -import org.locationtech.jts.geom.*; import org.heigit.ors.routing.graphhopper.extensions.DataReaderContext; +import org.locationtech.jts.geom.*; import java.util.*; public class InFieldGraphBuilder extends AbstractGraphBuilder { - private final GeometryFactory geometryFactory = new GeometryFactory(); - private final Map intId2idx = new HashMap<>(); - private final Map idx2intId = new HashMap<>(); - private final Map intId2osmId = new HashMap<>(); - private final ArrayList internalTowerNodeIds = new ArrayList<>(); - private Coordinate[] coordinates; - private final Set> edges = new HashSet<>(); - private final ArrayList tmpEdge = new ArrayList<>(); - private List weightings; - private EncodingManager encodingManager; + private final GeometryFactory geometryFactory = new GeometryFactory(); + private final Map intId2idx = new HashMap<>(); + private final Map idx2intId = new HashMap<>(); + private final Map intId2osmId = new HashMap<>(); + private final ArrayList internalTowerNodeIds = new ArrayList<>(); + private Coordinate[] coordinates; + private final Set> edges = new HashSet<>(); + private final ArrayList tmpEdge = new ArrayList<>(); + private List weightings; + private EncodingManager encodingManager; - @Override - public void init(GraphHopper graphhopper) throws Exception { - // create local network taken from - // https://github.com/graphhopper/graphhopper/blob/0.5/core/src/test/java/com/graphhopper/GraphHopperTest.java#L746 - FootFlagEncoder footEncoder = new FootFlagEncoder(); - encodingManager = EncodingManager.create(footEncoder); - weightings = new ArrayList<>(1); - weightings.add(new FastestWeighting(footEncoder)); - } + @Override + public void init(GraphHopper graphhopper) throws Exception { + // create local network taken from + // https://github.com/graphhopper/graphhopper/blob/0.5/core/src/test/java/com/graphhopper/GraphHopperTest.java#L746 + FootFlagEncoder footEncoder = new FootFlagEncoder(); + encodingManager = EncodingManager.create(footEncoder); + weightings = new ArrayList<>(1); + weightings.add(new FastestWeighting(footEncoder)); + } - @Override - public boolean createEdges(DataReaderContext readerCntx, ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) { - if (!hasOpenSpace(way, osmNodeIds)) - return false; + @Override + public boolean createEdges(DataReaderContext readerCntx, ReaderWay way, LongArrayList osmNodeIds, IntsRef wayFlags, List createdEdges) { + if (!hasOpenSpace(way, osmNodeIds)) + return false; - LongIntMap nodeMap = readerCntx.getNodeMap(); - Polygon openSpace = osmPolygon2JTS(readerCntx, osmNodeIds); + LongIntMap nodeMap = readerCntx.getNodeMap(); + Polygon openSpace = osmPolygon2JTS(readerCntx, osmNodeIds); - internalTowerNodeIds.clear(); - intId2osmId.clear(); - idx2intId.clear(); - intId2idx.clear(); + internalTowerNodeIds.clear(); + intId2osmId.clear(); + idx2intId.clear(); + intId2idx.clear(); - // fill list with tower nodes - // fill map "internal ID 2 OSM ID" - for (int j = 0; j < osmNodeIds.size() - 1; j++) { - long osmNodeId = osmNodeIds.get(j); - int internalOSMId = nodeMap.get(osmNodeId); - intId2osmId.put(internalOSMId, osmNodeId); - if (internalOSMId < -2) //towernode - { - internalTowerNodeIds.add(internalOSMId); - } - } + // fill list with tower nodes + // fill map "internal ID 2 OSM ID" + for (int j = 0; j < osmNodeIds.size() - 1; j++) { + long osmNodeId = osmNodeIds.get(j); + int internalOSMId = nodeMap.get(osmNodeId); + intId2osmId.put(internalOSMId, osmNodeId); + if (internalOSMId < -2) //towernode + { + internalTowerNodeIds.add(internalOSMId); + } + } - DistanceCalc distCalc = DistanceCalcEarth.DIST_EARTH; - try (GraphHopperStorage graphStorage = new GraphHopperStorage(new RAMDirectory(), encodingManager, false).create(20)) { - for (int idxMain = 0; idxMain < osmNodeIds.size() - 1; idxMain++) { - long mainOsmId = osmNodeIds.get(idxMain); - int internalMainId = nodeMap.get(mainOsmId); - // coordinates of the first nodes - double latMain = readerCntx.getNodeLatitude(internalMainId); - double lonMain = readerCntx.getNodeLongitude(internalMainId); - // connect the boundary of the open space - int idxNeighbor = idxMain + 1; - long neighborOsmId = osmNodeIds.get(idxNeighbor); - int internalNeighborId = nodeMap.get(neighborOsmId); - double latNeighbor = readerCntx.getNodeLatitude(internalNeighborId); - double lonNeighbor = readerCntx.getNodeLongitude(internalNeighborId); - double distance = distCalc.calcDist(latMain, lonMain, latNeighbor, lonNeighbor); - graphStorage.edge(idxMain, idxNeighbor).setDistance(distance); - // iterate through remaining nodes, - // but not through the direct neighbors - for (int idxPartner = idxMain + 2; idxPartner < osmNodeIds.size() - 1; idxPartner++) { - long partnerOsmId = osmNodeIds.get(idxPartner); - int internalPartnerId = nodeMap.get(partnerOsmId); - // coordinates of second nodes - double latPartner = readerCntx.getNodeLatitude(internalPartnerId); - double lonPartner = readerCntx.getNodeLongitude(internalPartnerId); - // connect nodes - LineString ls = geometryFactory.createLineString(new Coordinate[]{new Coordinate(lonMain, latMain), new Coordinate(lonPartner, latPartner)}); - // check if new edge is within open space - if (ls.within(openSpace)) { - // compute distance between nodes - distance = distCalc.calcDist(latMain, lonMain, latPartner, lonPartner); - // the index number of the nodes in the local network - // necessary, because it does not accept big values - // fill - intId2idx.put(internalMainId, idxMain); - intId2idx.put(internalPartnerId, idxPartner); - // fill - idx2intId.put(idxMain, internalMainId); - idx2intId.put(idxPartner, internalPartnerId); - // add edge to local graph - graphStorage.edge(idxMain, idxPartner).setDistance(distance); - } - } - } + DistanceCalc distCalc = DistanceCalcEarth.DIST_EARTH; + try (GraphHopperStorage graphStorage = new GraphHopperStorage(new RAMDirectory(), encodingManager, false).create(20)) { + for (int idxMain = 0; idxMain < osmNodeIds.size() - 1; idxMain++) { + long mainOsmId = osmNodeIds.get(idxMain); + int internalMainId = nodeMap.get(mainOsmId); + // coordinates of the first nodes + double latMain = readerCntx.getNodeLatitude(internalMainId); + double lonMain = readerCntx.getNodeLongitude(internalMainId); + // connect the boundary of the open space + int idxNeighbor = idxMain + 1; + long neighborOsmId = osmNodeIds.get(idxNeighbor); + int internalNeighborId = nodeMap.get(neighborOsmId); + double latNeighbor = readerCntx.getNodeLatitude(internalNeighborId); + double lonNeighbor = readerCntx.getNodeLongitude(internalNeighborId); + double distance = distCalc.calcDist(latMain, lonMain, latNeighbor, lonNeighbor); + graphStorage.edge(idxMain, idxNeighbor).setDistance(distance); + // iterate through remaining nodes, + // but not through the direct neighbors + for (int idxPartner = idxMain + 2; idxPartner < osmNodeIds.size() - 1; idxPartner++) { + long partnerOsmId = osmNodeIds.get(idxPartner); + int internalPartnerId = nodeMap.get(partnerOsmId); + // coordinates of second nodes + double latPartner = readerCntx.getNodeLatitude(internalPartnerId); + double lonPartner = readerCntx.getNodeLongitude(internalPartnerId); + // connect nodes + LineString ls = geometryFactory.createLineString(new Coordinate[]{new Coordinate(lonMain, latMain), new Coordinate(lonPartner, latPartner)}); + // check if new edge is within open space + if (ls.within(openSpace)) { + // compute distance between nodes + distance = distCalc.calcDist(latMain, lonMain, latPartner, lonPartner); + // the index number of the nodes in the local network + // necessary, because it does not accept big values + // fill + intId2idx.put(internalMainId, idxMain); + intId2idx.put(internalPartnerId, idxPartner); + // fill + idx2intId.put(idxMain, internalMainId); + idx2intId.put(idxPartner, internalPartnerId); + // add edge to local graph + graphStorage.edge(idxMain, idxPartner).setDistance(distance); + } + } + } - // a set with all created edges. - // the nodes which create the edge are stored in a ArrayList. - // it is important that the first node is smaller than the second node. - // TODO maybe a treeset would make the code more elegant - edges.clear(); + // a set with all created edges. + // the nodes which create the edge are stored in a ArrayList. + // it is important that the first node is smaller than the second node. + // TODO maybe a treeset would make the code more elegant + edges.clear(); - // compute routes between all tower nodes using the local graph - for (int i = 0; i < internalTowerNodeIds.size(); i++) { - int internalIdTowerStart = internalTowerNodeIds.get(i); - // check if tower node is in map - // it can miss if no edge is starting from here - if (!intId2idx.containsKey(internalIdTowerStart)) { - continue; - } - int idxTowerStart = intId2idx.get(internalIdTowerStart); - for (int j = i + 1; j < internalTowerNodeIds.size(); j++) { - int internalIdTowerDestination = internalTowerNodeIds.get(j); - // check if tower node is in map - // it can miss if no edge is starting from here - if (!intId2idx.containsKey(internalIdTowerDestination)) { - continue; - } - int idxTowerDest = intId2idx.get(internalIdTowerDestination); - // compute route between tower nodes - try { - Dijkstra dijkstra = new Dijkstra(graphStorage, weightings.get(0), TraversalMode.EDGE_BASED); - Path path = dijkstra.calcPath(idxTowerStart, idxTowerDest); - IntIndexedContainer pathNodes = path.calcNodes(); - // iterate through nodes of routing result - for (int k = 0; k < pathNodes.size() - 1; k++) { - // local index - int idxNodeA = pathNodes.get(k); - int idxNodeB = pathNodes.get(k + 1); - // internal Node IDs - int nodeA = idx2intId.get(idxNodeA); - int nodeB = idx2intId.get(idxNodeB); - // add to nodes to array sorted - int minNode = Integer.min(nodeA, nodeB); - int maxNode = Integer.max(nodeA, nodeB); - tmpEdge.clear(); - tmpEdge.add(minNode); - tmpEdge.add(maxNode); - boolean edgeIsNew = edges.add(tmpEdge); - if (edgeIsNew) { - // it is necessary to get the long node OSM IDs... - long osmNodeA = intId2osmId.get(minNode); - long osmNodeB = intId2osmId.get(maxNode); - addNodePairAsEdgeToGraph(readerCntx, way.getId(), wayFlags, createdEdges, osmNodeA, osmNodeB); - } - } - } catch (Exception ex) { - // do nothing - } - } - } + // compute routes between all tower nodes using the local graph + for (int i = 0; i < internalTowerNodeIds.size(); i++) { + int internalIdTowerStart = internalTowerNodeIds.get(i); + // check if tower node is in map + // it can miss if no edge is starting from here + if (!intId2idx.containsKey(internalIdTowerStart)) { + continue; + } + int idxTowerStart = intId2idx.get(internalIdTowerStart); + for (int j = i + 1; j < internalTowerNodeIds.size(); j++) { + int internalIdTowerDestination = internalTowerNodeIds.get(j); + // check if tower node is in map + // it can miss if no edge is starting from here + if (!intId2idx.containsKey(internalIdTowerDestination)) { + continue; + } + int idxTowerDest = intId2idx.get(internalIdTowerDestination); + // compute route between tower nodes + try { + Dijkstra dijkstra = new Dijkstra(graphStorage, weightings.get(0), TraversalMode.EDGE_BASED); + Path path = dijkstra.calcPath(idxTowerStart, idxTowerDest); + IntIndexedContainer pathNodes = path.calcNodes(); + // iterate through nodes of routing result + for (int k = 0; k < pathNodes.size() - 1; k++) { + // local index + int idxNodeA = pathNodes.get(k); + int idxNodeB = pathNodes.get(k + 1); + // internal Node IDs + int nodeA = idx2intId.get(idxNodeA); + int nodeB = idx2intId.get(idxNodeB); + // add to nodes to array sorted + int minNode = Integer.min(nodeA, nodeB); + int maxNode = Integer.max(nodeA, nodeB); + tmpEdge.clear(); + tmpEdge.add(minNode); + tmpEdge.add(maxNode); + boolean edgeIsNew = edges.add(tmpEdge); + if (edgeIsNew) { + // it is necessary to get the long node OSM IDs... + long osmNodeA = intId2osmId.get(minNode); + long osmNodeB = intId2osmId.get(maxNode); + addNodePairAsEdgeToGraph(readerCntx, way.getId(), wayFlags, createdEdges, osmNodeA, osmNodeB); + } + } + } catch (Exception ex) { + // do nothing + } + } + } - // TODO this loop can maybe be integrated at the part where the boundary edges are handled alread< - // add boundary of open space - for (int i = 0; i < osmNodeIds.size() - 1; i++) { - long osmIdA = osmNodeIds.get(i); - long osmIdB = osmNodeIds.get(i + 1); - int internalIdA = nodeMap.get(osmIdA); - int internalIdB = nodeMap.get(osmIdB); - // add to nodes to array sorted - int minIntId = Integer.min(internalIdA, internalIdB); - int maxIndId = Integer.max(internalIdA, internalIdB); - // create a boundary edge - tmpEdge.clear(); - tmpEdge.add(minIntId); - tmpEdge.add(maxIndId); - // test if already exists - boolean edgeIsNew = edges.add(tmpEdge); - if (edgeIsNew) { - // edge is added to global GraphHopper graph - addNodePairAsEdgeToGraph(readerCntx, way.getId(), wayFlags, createdEdges, osmIdA, osmIdB); - } - } - } - return true; - } + // TODO this loop can maybe be integrated at the part where the boundary edges are handled alread< + // add boundary of open space + for (int i = 0; i < osmNodeIds.size() - 1; i++) { + long osmIdA = osmNodeIds.get(i); + long osmIdB = osmNodeIds.get(i + 1); + int internalIdA = nodeMap.get(osmIdA); + int internalIdB = nodeMap.get(osmIdB); + // add to nodes to array sorted + int minIntId = Integer.min(internalIdA, internalIdB); + int maxIndId = Integer.max(internalIdA, internalIdB); + // create a boundary edge + tmpEdge.clear(); + tmpEdge.add(minIntId); + tmpEdge.add(maxIndId); + // test if already exists + boolean edgeIsNew = edges.add(tmpEdge); + if (edgeIsNew) { + // edge is added to global GraphHopper graph + addNodePairAsEdgeToGraph(readerCntx, way.getId(), wayFlags, createdEdges, osmIdA, osmIdB); + } + } + } + return true; + } - private void addNodePairAsEdgeToGraph(DataReaderContext readerCntx, long wayOsmId, IntsRef wayFlags, List createdEdges, long node1, long node2) { - // list which contains the Nodes of the new Edge - LongArrayList subgraphNodes = new LongArrayList(5); - subgraphNodes.add(node1); - subgraphNodes.add(node2); - createdEdges.addAll(readerCntx.addWay(subgraphNodes, wayFlags, wayOsmId)); - } + private void addNodePairAsEdgeToGraph(DataReaderContext readerCntx, long wayOsmId, IntsRef wayFlags, List createdEdges, long node1, long node2) { + // list which contains the Nodes of the new Edge + LongArrayList subgraphNodes = new LongArrayList(5); + subgraphNodes.add(node1); + subgraphNodes.add(node2); + createdEdges.addAll(readerCntx.addWay(subgraphNodes, wayFlags, wayOsmId)); + } - private Polygon osmPolygon2JTS(DataReaderContext readerCntx, LongArrayList osmNodeIds) { - // collect all coordinates in ArrayList - if (coordinates == null || coordinates.length < osmNodeIds.size()) - coordinates = new Coordinate[osmNodeIds.size()]; + private Polygon osmPolygon2JTS(DataReaderContext readerCntx, LongArrayList osmNodeIds) { + // collect all coordinates in ArrayList + if (coordinates == null || coordinates.length < osmNodeIds.size()) + coordinates = new Coordinate[osmNodeIds.size()]; - for (int i = 0; i < osmNodeIds.size(); i++) - { - long osmNodeId = osmNodeIds.get(i); - int internalID = readerCntx.getNodeMap().get(osmNodeId); - coordinates[i] = new Coordinate(readerCntx.getNodeLongitude(internalID), readerCntx.getNodeLatitude(internalID)); - } + for (int i = 0; i < osmNodeIds.size(); i++) { + long osmNodeId = osmNodeIds.get(i); + int internalID = readerCntx.getNodeMap().get(osmNodeId); + coordinates[i] = new Coordinate(readerCntx.getNodeLongitude(internalID), readerCntx.getNodeLatitude(internalID)); + } - Coordinate[] coords = Arrays.copyOf(coordinates, osmNodeIds.size()); - LinearRing ring = geometryFactory.createLinearRing(coords); - // a JTS polygon consists of a ring and holes - return geometryFactory.createPolygon(ring, null); - } + Coordinate[] coords = Arrays.copyOf(coordinates, osmNodeIds.size()); + LinearRing ring = geometryFactory.createLinearRing(coords); + // a JTS polygon consists of a ring and holes + return geometryFactory.createPolygon(ring, null); + } - @Override - public void finish() { - // do nothing - } + @Override + public void finish() { + // do nothing + } - /* * checks if the OSM way is an open space * - * - * @param way - * @param osmNodeIds - * @return */ - private boolean hasOpenSpace(ReaderWay way, LongArrayList osmNodeIds) - { - long firstNodeId = osmNodeIds.get(0); - long lastNodeId = osmNodeIds.get(osmNodeIds.size() - 1); - return (firstNodeId == lastNodeId) && way.hasTag("area", "yes"); - } + /* * checks if the OSM way is an open space * + * + * @param way + * @param osmNodeIds + * @return */ + private boolean hasOpenSpace(ReaderWay way, LongArrayList osmNodeIds) { + long firstNodeId = osmNodeIds.get(0); + long lastNodeId = osmNodeIds.get(osmNodeIds.size() - 1); + return (firstNodeId == lastNodeId) && way.hasTag("area", "yes"); + } - @Override - public String getName() { - return "InField"; - } + @Override + public String getName() { + return "InField"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchy.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchy.java index c21cced1f3..dff0057f8f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchy.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchy.java @@ -30,23 +30,24 @@ public class CountryBordersHierarchy { /** * Add a boundary polygon to the hierarchy and update the hiearchies extent. + * * @param cp */ public void add(CountryBordersPolygon cp) { this.polygons.add(cp); // Update bounding box double[] bb = cp.getBBox(); - if(bb[0] < minLon) minLon = bb[0]; - if(bb[1] > maxLon) maxLon = bb[1]; - if(bb[2] < minLat) minLat = bb[2]; - if(bb[3] > maxLat) maxLat = bb[3]; + if (bb[0] < minLon) minLon = bb[0]; + if (bb[1] > maxLon) maxLon = bb[1]; + if (bb[2] < minLat) minLat = bb[2]; + if (bb[3] > maxLat) maxLat = bb[3]; } /** * Check if the given coordinate is within the bounding box of this hierarchy. The bounding box is one that * surrounds all of the country polygons that the hierarchy object contains * - * @param c The coordinate to lookup + * @param c The coordinate to lookup * @return */ public boolean inBbox(Coordinate c) { @@ -55,7 +56,7 @@ public boolean inBbox(Coordinate c) { public double[] getBBox() { - return new double[] {minLon, maxLon, minLat, maxLat}; + return new double[]{minLon, maxLon, minLat, maxLat}; } @@ -66,13 +67,13 @@ public List getPolygons() { /** * Loop through the country polygons of this hierarchy and find those that the given coordinate is located within * - * @param c The coordinate to lookup - * @return An array list of the polygon objects that the coordinate is found in + * @param c The coordinate to lookup + * @return An array list of the polygon objects that the coordinate is found in */ public List getContainingPolygons(Coordinate c) { ArrayList containing = new ArrayList<>(); - if(!Double.isNaN(c.x) && !Double.isNaN(c.y) && inBbox(c)) { + if (!Double.isNaN(c.x) && !Double.isNaN(c.y) && inBbox(c)) { for (CountryBordersPolygon cbp : polygons) { if (cbp.inBbox(c)) { containing.add(cbp); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygon.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygon.java index 0b9b7a4634..25ad38b7d3 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygon.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygon.java @@ -13,8 +13,8 @@ */ package org.heigit.ors.routing.graphhopper.extensions.reader.borders; -import org.locationtech.jts.geom.*; import org.apache.log4j.Logger; +import org.locationtech.jts.geom.*; import java.io.InvalidObjectException; @@ -32,17 +32,17 @@ public class CountryBordersPolygon { /** * Construct a CountryBordersPolygon object used for determining if a way crosses a country border * - * @param name The local name of the country - * @param boundary Geometry representing the boundary of the region + * @param name The local name of the country + * @param boundary Geometry representing the boundary of the region * @throws InvalidObjectException */ public CountryBordersPolygon(String name, Geometry boundary) throws InvalidObjectException { this.name = name; GeometryFactory gf = new GeometryFactory(); - if(boundary.getGeometryType().equals("Polygon")) - this.boundary = gf.createMultiPolygon(new Polygon[] {(Polygon) boundary}); - else if(boundary.getGeometryType().equals("MultiPolygon")) + if (boundary.getGeometryType().equals("Polygon")) + this.boundary = gf.createMultiPolygon(new Polygon[]{(Polygon) boundary}); + else if (boundary.getGeometryType().equals("MultiPolygon")) this.boundary = (MultiPolygon) boundary; else { LOGGER.error("Invalid geometry - " + boundary.getGeometryType()); @@ -52,16 +52,16 @@ else if(boundary.getGeometryType().equals("MultiPolygon")) this.area = this.boundary.getArea(); // calculate lat and lon values Geometry bbox = boundary.getEnvelope(); - for(Coordinate c : bbox.getCoordinates()) { - if(c.x < minLon) minLon = c.x; - if(c.x > maxLon) maxLon = c.x; - if(c.y < minLat) minLat = c.y; - if(c.y > maxLat) maxLat = c.y; + for (Coordinate c : bbox.getCoordinates()) { + if (c.x < minLon) minLon = c.x; + if (c.x > maxLon) maxLon = c.x; + if (c.y < minLat) minLat = c.y; + if (c.y > maxLat) maxLat = c.y; } } public double[] getBBox() { - return new double[] {minLon, maxLon, minLat, maxLat}; + return new double[]{minLon, maxLon, minLat, maxLat}; } public boolean shares(MultiPolygon other) { @@ -88,7 +88,7 @@ public boolean inBbox(Coordinate c) { } public boolean inArea(Coordinate c) { - if(!Double.isNaN(c.x) && !Double.isNaN(c.y) && inBbox(c)) { + if (!Double.isNaN(c.x) && !Double.isNaN(c.y) && inBbox(c)) { GeometryFactory gf = new GeometryFactory(); return boundary.contains(gf.createPoint(c)); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReader.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReader.java index 605c5fc910..afd3c6a739 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReader.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReader.java @@ -13,16 +13,16 @@ */ package org.heigit.ors.routing.graphhopper.extensions.reader.borders; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.Geometry; -import org.heigit.ors.geojson.GeometryJSON; -import org.heigit.ors.util.CSVUtility; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.log4j.Logger; +import org.heigit.ors.geojson.GeometryJSON; +import org.heigit.ors.util.CSVUtility; import org.json.JSONArray; import org.json.JSONObject; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.Geometry; import java.io.*; import java.util.*; @@ -66,9 +66,9 @@ public CountryBordersReader() { /** * Create a CountryBordersReader object and read in data for borders, ids and open borders. * - * @param filepath Path to the borders (polygon) data - * @param idsPath Path to a csv file containing numeric identifiers for countries (and english name) - * @param openPath Path to a csv file containing pairs of country names which have open borders + * @param filepath Path to the borders (polygon) data + * @param idsPath Path to a csv file containing numeric identifiers for countries (and english name) + * @param openPath Path to a csv file containing pairs of country names which have open borders */ public CountryBordersReader(String filepath, String idsPath, String openPath) throws IOException { borderFile = filepath; @@ -99,14 +99,14 @@ public CountryBordersReader(String filepath, String idsPath, String openPath) th // for test mocks public void addHierarchy(Long id, CountryBordersHierarchy hierarchy) { - if(!hierarchies.containsKey(id)) { + if (!hierarchies.containsKey(id)) { hierarchies.put(id, hierarchy); } } // for test mocks public void addId(String id, String localName, String englishName, String cca2, String cca3) { - if(!ids.containsKey(localName)) { + if (!ids.containsKey(localName)) { ids.put(localName, new CountryInfo(id, localName, englishName)); isoCodes.put(cca2.trim().toUpperCase(), Integer.parseInt(id)); isoCodes.put(cca3.trim().toUpperCase(), Integer.parseInt(id)); @@ -121,9 +121,9 @@ public void addId(String id, String localName, String englishName, String cca2, * @param country2 */ public void addOpenBorder(String country1, String country2) { - if(openBorders.containsKey(country1)) { + if (openBorders.containsKey(country1)) { // The key exists, so now add the second country if it is not present - if(!openBorders.get(country1).contains(country2)) { + if (!openBorders.get(country1).contains(country2)) { openBorders.get(country1).add(country2); } } else { @@ -132,8 +132,8 @@ public void addOpenBorder(String country1, String country2) { openBorders.put(country1, c2); } - if(openBorders.containsKey(country2)) {// The key exists, so now add the second country if it is not present - if(!openBorders.get(country2).contains(country1)) { + if (openBorders.containsKey(country2)) {// The key exists, so now add the second country if it is not present + if (!openBorders.get(country2).contains(country1)) { openBorders.get(country2).add(country1); } } else { @@ -146,11 +146,11 @@ public void addOpenBorder(String country1, String country2) { /** * Method to read the geometries from a GeoJSON file that represent the boundaries of different countries. Ideally * it should be written using many small objects split into hierarchies. - * + *

    * If the file is a .tar.gz format, it will decompress it and then store the reulting data to be read into the * JSON object. * - * @return A (Geo)JSON object representing the contents of the file + * @return A (Geo)JSON object representing the contents of the file */ private JSONObject readBordersData() throws IOException { String data = ""; @@ -158,7 +158,7 @@ private JSONObject readBordersData() throws IOException { BufferedReader buf = null; TarArchiveInputStream tis = null; try (InputStream is = new FileInputStream(borderFile)) { - if(borderFile.endsWith(".tar.gz")) { + if (borderFile.endsWith(".tar.gz")) { // We are working with a compressed file tis = new TarArchiveInputStream( new GzipCompressorInputStream( @@ -169,8 +169,8 @@ private JSONObject readBordersData() throws IOException { TarArchiveEntry entry; StringBuilder sb = new StringBuilder(); - while((entry = tis.getNextTarEntry()) != null) { - if(!entry.isDirectory()) { + while ((entry = tis.getNextTarEntry()) != null) { + if (!entry.isDirectory()) { byte[] bytes = new byte[(int) entry.getSize()]; while (tis.read(bytes) > 0) sb.append(new String(bytes)); @@ -196,9 +196,9 @@ private JSONObject readBordersData() throws IOException { throw ioe; } finally { try { - if(tis != null) + if (tis != null) tis.close(); - if(buf != null) + if (buf != null) buf.close(); } catch (IOException ioe) { LOGGER.warn("Error closing file reader buffers!"); @@ -222,7 +222,7 @@ private void createGeometries(JSONObject json) { int len = features.length(); - for(int i=0; i countries = new ArrayList<>(); Iterator it = hierarchies.entrySet().iterator(); - while(it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - CountryBordersHierarchy h = pair.getValue(); - if(h.inBbox(c)) { + while (it.hasNext()) { + Map.Entry pair = (Map.Entry) it.next(); + CountryBordersHierarchy h = pair.getValue(); + if (h.inBbox(c)) { // Now need to check the countries List ps = h.getPolygons(); - for(CountryBordersPolygon cp : ps) { - if(cp.inBbox(c) && cp.inArea(c)) { + for (CountryBordersPolygon cp : ps) { + if (cp.inBbox(c) && cp.inArea(c)) { countries.add(cp); } } @@ -291,20 +291,20 @@ public CountryBordersPolygon[] getCountry(Coordinate c) { * returned may not actually surround the point. The method should be used to get a quick approximation as to * whether the country is a candidate for containing the point. * - * @param c The point that you want to know which country is in - * @return An array of CountryBorderPolygons that the point is within the geometry of. + * @param c The point that you want to know which country is in + * @return An array of CountryBorderPolygons that the point is within the geometry of. */ public CountryBordersPolygon[] getCandidateCountry(Coordinate c) { ArrayList countries = new ArrayList<>(); Iterator it = hierarchies.entrySet().iterator(); - while(it.hasNext()) { - Map.Entry pair = (Map.Entry)it.next(); - CountryBordersHierarchy h = pair.getValue(); - if(h.inBbox(c)) { + while (it.hasNext()) { + Map.Entry pair = (Map.Entry) it.next(); + CountryBordersHierarchy h = pair.getValue(); + if (h.inBbox(c)) { // Now need to check the countries List ps = h.getPolygons(); - for(CountryBordersPolygon cp : ps) { - if(cp.inBbox(c)) { + for (CountryBordersPolygon cp : ps) { + if (cp.inBbox(c)) { countries.add(cp); } } @@ -317,14 +317,14 @@ public CountryBordersPolygon[] getCandidateCountry(Coordinate c) { /** * Get the unique identifier of the country (read from a CSV file in the constructor) * - * @param name The local name of the country - * @return The unique identifier + * @param name The local name of the country + * @return The unique identifier */ public String getId(String name) { - if(name.equals(INTERNATIONAL_NAME)) + if (name.equals(INTERNATIONAL_NAME)) return INTERNATIONAL_ID; - if(ids.containsKey(name)) + if (ids.containsKey(name)) return ids.get(name).id; else return ""; @@ -333,14 +333,14 @@ public String getId(String name) { /** * Get the English name of the country (read from the id CSV) * - * @param name The local name of the country - * @return The English name of the country + * @param name The local name of the country + * @return The English name of the country */ public String getEngName(String name) { - if(name.equals(INTERNATIONAL_NAME)) + if (name.equals(INTERNATIONAL_NAME)) return INTERNATIONAL_NAME; - if(ids.containsKey(name)) + if (ids.containsKey(name)) return ids.get(name).nameEng; else return ""; @@ -349,14 +349,14 @@ public String getEngName(String name) { /** * Get whether a border between two specified countries is open or closed * - * @param c1 The first country of the border (English name) - * @param c2 The second country of the border (English name) + * @param c1 The first country of the border (English name) + * @param c2 The second country of the border (English name) * @return */ public boolean isOpen(String c1, String c2) { - if(openBorders.containsKey(c1)) { + if (openBorders.containsKey(c1)) { return openBorders.get(c1).contains(c2); - } else if(openBorders.containsKey(c2)) + } else if (openBorders.containsKey(c2)) return openBorders.get(c2).contains(c1); return false; @@ -367,8 +367,8 @@ public boolean isOpen(String c1, String c2) { * this class. (Usually there should be only one instance for each server instance, and even if not, the * borders data used should be the same) * - * @param code The code to look up - * @return The ID of the country or 0 if not found + * @param code The code to look up + * @return The ID of the country or 0 if not found */ public static int getCountryIdByISOCode(String code) { return currentInstance != null ? currentInstance.isoCodes.getOrDefault(code.toUpperCase(), 0) : 0; @@ -387,8 +387,8 @@ private void readIds() { int countries = 0; int isoCCA2 = 0; int isoCCA3 = 0; - for(List col : data) { - if(col.size() >= 3) { + for (List col : data) { + if (col.size() >= 3) { ids.put(col.get(1), new CountryInfo(col.get(0), col.get(1), col.get(2))); countries++; } @@ -399,11 +399,11 @@ private void readIds() { LOGGER.error("Invalid country ID " + col.get(0)); continue; } - if(col.size() >= 4 && !col.get(3).trim().isEmpty()) { + if (col.size() >= 4 && !col.get(3).trim().isEmpty()) { isoCodes.put(col.get(3).trim().toUpperCase(), intID); isoCCA2++; } - if(col.size() == 5 && !col.get(4).trim().isEmpty()) { + if (col.size() == 5 && !col.get(4).trim().isEmpty()) { isoCodes.put(col.get(4).trim().toUpperCase(), intID); isoCCA3++; } @@ -411,14 +411,14 @@ private void readIds() { LOGGER.info(countries + " country IDs read"); if (isoCCA2 > 0) { if (isoCCA2 < countries) { - LOGGER.warn((countries - isoCCA2)+ " countries have no ISO 3166-1 CCA2 code assigned."); + LOGGER.warn((countries - isoCCA2) + " countries have no ISO 3166-1 CCA2 code assigned."); } else { LOGGER.info("ISO 3166-1 CCA2 codes enabled for all countries"); } } if (isoCCA3 > 0) { if (isoCCA3 < countries) { - LOGGER.warn((countries - isoCCA3)+ " countries have no ISO 3166-1 CCA3 code assigned."); + LOGGER.warn((countries - isoCCA3) + " countries have no ISO 3166-1 CCA3 code assigned."); } else { LOGGER.info("ISO 3166-1 CCA3 codes enabled for all countries"); } @@ -434,10 +434,10 @@ private void readOpenBorders() { List> data = CSVUtility.readFile(openPath); // Loop through and store in the hashmap - for(List col : data) { - if(col.size() == 2) { + for (List col : data) { + if (col.size() == 2) { // See if there is already the start country - if(!openBorders.containsKey(col.get(0))) { + if (!openBorders.containsKey(col.get(0))) { openBorders.put(col.get(0), new ArrayList<>()); } openBorders.get(col.get(0)).add(col.get(1)); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMAttachedSidewalkProcessor.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMAttachedSidewalkProcessor.java index e43e1babeb..92ec5aaa52 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMAttachedSidewalkProcessor.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMAttachedSidewalkProcessor.java @@ -11,7 +11,7 @@ public class OSMAttachedSidewalkProcessor { public static final String VAL_RIGHT = "right"; public static final String VAL_LEFT = "left"; - protected enum Side { LEFT, RIGHT, BOTH, NONE } + protected enum Side {LEFT, RIGHT, BOTH, NONE} public boolean hasSidewalkInfo(ReaderWay way) { return identifySidesWhereSidewalkIsPresent(way) != Side.NONE; @@ -27,8 +27,8 @@ protected Set getSidewalkKeys(ReaderWay way) { Set sidewalkInfoKeys = new HashSet<>(); Set keys = way.getTags().keySet(); - for(String k : keys) { - if(isSidewalkInfoKey(k)) { + for (String k : keys) { + if (isSidewalkInfoKey(k)) { sidewalkInfoKeys.add(k); } } @@ -54,7 +54,7 @@ private boolean isSidewalkInfoKey(String osmTagKey) { * @return */ public ReaderWay attachSidewalkTag(ReaderWay way, Side side) { - switch(side) { + switch (side) { case LEFT: way.setTag(KEY_ORS_SIDEWALK_SIDE, VAL_LEFT); break; @@ -62,7 +62,7 @@ public ReaderWay attachSidewalkTag(ReaderWay way, Side side) { way.setTag(KEY_ORS_SIDEWALK_SIDE, VAL_RIGHT); break; case BOTH: - if(way.hasTag(KEY_ORS_SIDEWALK_SIDE) && way.getTag(KEY_ORS_SIDEWALK_SIDE).equalsIgnoreCase(VAL_LEFT)) { + if (way.hasTag(KEY_ORS_SIDEWALK_SIDE) && way.getTag(KEY_ORS_SIDEWALK_SIDE).equalsIgnoreCase(VAL_LEFT)) { // The left side has been attached previously, so now attach the right side way.setTag(KEY_ORS_SIDEWALK_SIDE, VAL_RIGHT); } else { @@ -71,7 +71,7 @@ public ReaderWay attachSidewalkTag(ReaderWay way, Side side) { } break; case NONE: - if(way.hasTag(KEY_ORS_SIDEWALK_SIDE)) { + if (way.hasTag(KEY_ORS_SIDEWALK_SIDE)) { way.removeTag(KEY_ORS_SIDEWALK_SIDE); } } @@ -86,12 +86,12 @@ public ReaderWay attachSidewalkTag(ReaderWay way, Side side) { * @return */ public Side getPreparedSide(ReaderWay way) { - if(way.hasTag(KEY_ORS_SIDEWALK_SIDE)) { + if (way.hasTag(KEY_ORS_SIDEWALK_SIDE)) { String preparedSide = way.getTag(KEY_ORS_SIDEWALK_SIDE); - if(preparedSide.equalsIgnoreCase(VAL_LEFT)) { + if (preparedSide.equalsIgnoreCase(VAL_LEFT)) { return Side.LEFT; } - if(preparedSide.equalsIgnoreCase(VAL_RIGHT)) { + if (preparedSide.equalsIgnoreCase(VAL_RIGHT)) { return Side.RIGHT; } } @@ -110,7 +110,7 @@ protected Side identifySidesWhereSidewalkIsPresent(ReaderWay osmWay) { boolean sidewalkOnRightSide = false; boolean sidewalkOnBothSides = false; - if(osmWay.hasTag("sidewalk")) { + if (osmWay.hasTag("sidewalk")) { String side = osmWay.getTag("sidewalk"); switch (side) { case VAL_LEFT -> sidewalkOnLeftSide = true; @@ -123,25 +123,25 @@ protected Side identifySidesWhereSidewalkIsPresent(ReaderWay osmWay) { Set sidewalkProperties = getSidewalkKeys(osmWay); - for(String key : sidewalkProperties) { - if(key.startsWith("sidewalk:left") || key.startsWith("footway:left")) sidewalkOnLeftSide = true; - if(key.startsWith("sidewalk:right") || key.startsWith("footway:right")) sidewalkOnRightSide = true; - if(key.startsWith("sidewalk:both") || key.startsWith("footway:both")) sidewalkOnBothSides = true; + for (String key : sidewalkProperties) { + if (key.startsWith("sidewalk:left") || key.startsWith("footway:left")) sidewalkOnLeftSide = true; + if (key.startsWith("sidewalk:right") || key.startsWith("footway:right")) sidewalkOnRightSide = true; + if (key.startsWith("sidewalk:both") || key.startsWith("footway:both")) sidewalkOnBothSides = true; } - if(sidewalkOnLeftSide && sidewalkOnRightSide) { + if (sidewalkOnLeftSide && sidewalkOnRightSide) { sidewalkOnBothSides = true; } - if(sidewalkOnBothSides) { + if (sidewalkOnBothSides) { return Side.BOTH; } - if(sidewalkOnLeftSide) { + if (sidewalkOnLeftSide) { return Side.LEFT; } - if(sidewalkOnRightSide) { + if (sidewalkOnRightSide) { return Side.RIGHT; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMFeatureFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMFeatureFilter.java index ca595dae82..64daf90a82 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMFeatureFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMFeatureFilter.java @@ -16,12 +16,14 @@ public interface OSMFeatureFilter { /** * Should the element that has been assigned to this filter be accepted into the graph + * * @return */ boolean accept(); /** * Prepare the element that has been assigned to the filter for processing + * * @return */ ReaderElement prepareForProcessing(); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMPedestrianProcessor.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMPedestrianProcessor.java index 5d1f3f7e20..b26703a82e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMPedestrianProcessor.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/OSMPedestrianProcessor.java @@ -12,8 +12,9 @@ public class OSMPedestrianProcessor { public OSMPedestrianProcessor() { allowed = new ArrayList<>(); allowed.add("yes"); - allowed.addAll(Arrays.asList("yes", "designated", "permissive", "destination")); + allowed.addAll(Arrays.asList("yes", "designated", "permissive", "destination")); } + /** * Determine if the way is pedestrianised, i.e. that a person should be able to traverse it on foot. * @@ -24,7 +25,7 @@ public boolean isPedestrianisedWay(ReaderWay way) { boolean isPedestrian = false; - if(way.hasTag("highway")) { + if (way.hasTag("highway")) { String highwayType = way.getTag("highway"); switch (highwayType) { case "footway", "living_street", "pedestrian", "path", "track" -> isPedestrian = true; @@ -32,12 +33,12 @@ public boolean isPedestrianisedWay(ReaderWay way) { } } } - if(way.hasTag("public_transport") && way.getTag("public_transport").equals("platform")) + if (way.hasTag("public_transport") && way.getTag("public_transport").equals("platform")) isPedestrian = true; - if(way.hasTag("foot")) { + if (way.hasTag("foot")) { String footTag = way.getTag("foot"); - if(allowed.contains(footTag)) { + if (allowed.contains(footTag)) { isPedestrian = true; } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/PedestrianWay.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/PedestrianWay.java index 643327566b..d825fb0d8f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/PedestrianWay.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/PedestrianWay.java @@ -2,7 +2,7 @@ import com.graphhopper.reader.ReaderWay; -public abstract class PedestrianWay extends Way{ +public abstract class PedestrianWay extends Way { protected PedestrianWay(ReaderWay way) { this.readerWay = way; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/Way.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/Way.java index db97718f64..80dcf70e72 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/Way.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/Way.java @@ -11,6 +11,7 @@ public ReaderWay getReaderWay() { /** * Is the way a pedestrianised way + * * @return */ public boolean isPedestrianised() { @@ -27,5 +28,6 @@ public boolean isPedestrianised() { /** * Prepare the way ready for processing, such as adding side tags */ - public void prepare() {} + public void prepare() { + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWay.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWay.java index 252e644abb..c8bf4aa5f4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWay.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWay.java @@ -3,7 +3,6 @@ import com.graphhopper.reader.ReaderWay; - public class WheelchairSidewalkWay extends PedestrianWay { private final OSMAttachedSidewalkProcessor sidewalkProcessor; private final OSMAttachedSidewalkProcessor.Side side; @@ -19,7 +18,7 @@ public WheelchairSidewalkWay(ReaderWay way) { @Override public boolean hasWayBeenFullyProcessed() { - if(side == OSMAttachedSidewalkProcessor.Side.BOTH && lastPrepared == OSMAttachedSidewalkProcessor.Side.RIGHT) { + if (side == OSMAttachedSidewalkProcessor.Side.BOTH && lastPrepared == OSMAttachedSidewalkProcessor.Side.RIGHT) { return true; } @@ -30,12 +29,12 @@ public boolean hasWayBeenFullyProcessed() { public void prepare() { // Find out if anything has been done yet - if(side == OSMAttachedSidewalkProcessor.Side.BOTH && lastPrepared == OSMAttachedSidewalkProcessor.Side.RIGHT) { + if (side == OSMAttachedSidewalkProcessor.Side.BOTH && lastPrepared == OSMAttachedSidewalkProcessor.Side.RIGHT) { // The right sidewalk is the last to be processed when we are looking at both sides lastPrepared = OSMAttachedSidewalkProcessor.Side.BOTH; } - if(lastPrepared != side) { + if (lastPrepared != side) { this.readerWay = sidewalkProcessor.attachSidewalkTag(this.readerWay, side); lastPrepared = sidewalkProcessor.getPreparedSide(this.readerWay); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairWayFilter.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairWayFilter.java index af7869489d..04f4c20666 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairWayFilter.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairWayFilter.java @@ -17,7 +17,7 @@ public WheelchairWayFilter() { @Override public void assignFeatureForFiltering(ReaderElement element) throws InvalidObjectException { - if(element instanceof ReaderWay way) { + if (element instanceof ReaderWay way) { if (osmAttachedSidewalkProcessor.hasSidewalkInfo(way)) { this.osmWay = new WheelchairSidewalkWay(way); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/HereTrafficReader.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/HereTrafficReader.java index a2b4011782..0534563e9a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/HereTrafficReader.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/HereTrafficReader.java @@ -14,7 +14,6 @@ package org.heigit.ors.routing.graphhopper.extensions.reader.traffic; import com.graphhopper.util.DistanceCalcEarth; -import org.locationtech.jts.geom.MultiLineString; import org.apache.log4j.Logger; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; @@ -24,6 +23,7 @@ import org.geotools.feature.DefaultFeatureCollection; import org.heigit.ors.util.CSVUtility; import org.locationtech.jts.geom.GeometryFactory; +import org.locationtech.jts.geom.MultiLineString; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import org.opengis.feature.Property; @@ -38,9 +38,9 @@ public class HereTrafficReader { private static final Logger LOGGER = Logger.getLogger(HereTrafficReader.class); private boolean isInitialized; - private String streetGeometriesFile; - private String patternsReferenceFile; - private String patternsFile; + private final String streetGeometriesFile; + private final String patternsReferenceFile; + private final String patternsFile; private final TrafficData hereTrafficData = new TrafficData(); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficData.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficData.java index 26b523575c..010255854a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficData.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficData.java @@ -4,8 +4,8 @@ public class TrafficData { - private IntObjectHashMap links; - private IntObjectHashMap patterns; + private final IntObjectHashMap links; + private final IntObjectHashMap patterns; public TrafficData() { this.links = new IntObjectHashMap<>(); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficLink.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficLink.java index cc6a0f7779..1453d62166 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficLink.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficLink.java @@ -16,14 +16,14 @@ public class TrafficLink { private static final Logger LOGGER = Logger.getLogger(TrafficLink.class); - private int linkId; + private final int linkId; private double linkLength; private boolean isTeardrop; private LineString linkGeometry; - private TrafficLinkMetadata trafficLinkMetadata; - private EnumMap trafficPatternIdsFrom; - private EnumMap trafficPatternIdsTo; + private final TrafficLinkMetadata trafficLinkMetadata; + private final EnumMap trafficPatternIdsFrom; + private final EnumMap trafficPatternIdsTo; /** * Construct a TrafficLink object used for processing the link traffic data. @@ -145,17 +145,13 @@ private boolean checkTearDrop(LineString lineString) { } else if (coordinateFirstY > coordinateLastY) { // Last coordinate is Reference if its latitude is lower. return false; - } else if (coordinateFirstX < coordinateLastX) { - // First coordinate is the reference if latitudes are equal but its longitude is lower. - // This represents horizontal lines >------> - return false; - } else if (coordinateFirstX > coordinateLastX) { - // First coordinate is the reference if latitudes are equal but its longitude is lower. - return false; - } else { + } else // First coordinate is the reference if latitudes are equal but its longitude is lower. // Teardrop nodes with same Coords. This shouldn't happen with roads from Here! - return true; - } + if (coordinateFirstX < coordinateLastX) { + // First coordinate is the reference if latitudes are equal but its longitude is lower. + // This represents horizontal lines >------> + return false; + } else return !(coordinateFirstX > coordinateLastX); } public Geometry getToGeometry() { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficPattern.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficPattern.java index 3adb417989..75486d07a8 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficPattern.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/reader/traffic/TrafficPattern.java @@ -1,9 +1,9 @@ package org.heigit.ors.routing.graphhopper.extensions.reader.traffic; public class TrafficPattern { - private int patternId; - private TrafficEnums.PatternResolution resolution; - private short[] values; + private final int patternId; + private final TrafficEnums.PatternResolution resolution; + private final short[] values; public TrafficPattern(int patternId, TrafficEnums.PatternResolution resolution, short[] values) { this.patternId = patternId; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/AveragedMultiTreeSPEntry.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/AveragedMultiTreeSPEntry.java index 160da88f69..c39963dfdd 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/AveragedMultiTreeSPEntry.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/AveragedMultiTreeSPEntry.java @@ -17,55 +17,55 @@ * Shortest Path Tree with multiple fields for containing multiple source information. * The weight is the average of all non-infinite entries for order in priority queue. * Average weight can result in better performance than minimum weight. - * @author Hendrik Leuschner * + * @author Hendrik Leuschner */ public class AveragedMultiTreeSPEntry extends MultiTreeSPEntry { - private double weight = Double.POSITIVE_INFINITY; + private double weight = Double.POSITIVE_INFINITY; - public AveragedMultiTreeSPEntry(int adjNode, int edgeId, double edgeWeight, boolean updated, AveragedMultiTreeSPEntry parent, int numTrees) { - super(adjNode,edgeId, edgeWeight, updated, parent, numTrees); - updateWeights(); - } + public AveragedMultiTreeSPEntry(int adjNode, int edgeId, double edgeWeight, boolean updated, AveragedMultiTreeSPEntry parent, int numTrees) { + super(adjNode, edgeId, edgeWeight, updated, parent, numTrees); + updateWeights(); + } - public void setSubItemOriginalEdgeIds(int newOriginalEdgeId) { - for (int i = 0; i < getSize(); i++) { - getItem(i).setOriginalEdge(newOriginalEdgeId); - } - } + public void setSubItemOriginalEdgeIds(int newOriginalEdgeId) { + for (int i = 0; i < getSize(); i++) { + getItem(i).setOriginalEdge(newOriginalEdgeId); + } + } - @Override - public void updateWeights() { - double averageWeight = 0; - int numNonInfiniteWeights = 0; - for (int i = 0; i < getSize(); i++) { - MultiTreeSPEntryItem item = getItem(i); - double itemWeight = item.getWeight(); - if(itemWeight != Double.POSITIVE_INFINITY) { - averageWeight += itemWeight; - numNonInfiniteWeights++; - } + @Override + public void updateWeights() { + double averageWeight = 0; + int numNonInfiniteWeights = 0; + for (int i = 0; i < getSize(); i++) { + MultiTreeSPEntryItem item = getItem(i); + double itemWeight = item.getWeight(); + if (itemWeight != Double.POSITIVE_INFINITY) { + averageWeight += itemWeight; + numNonInfiniteWeights++; + } - } - if(numNonInfiniteWeights == 0) - weight = Double.POSITIVE_INFINITY; - else - weight = averageWeight / numNonInfiniteWeights; - } + } + if (numNonInfiniteWeights == 0) + weight = Double.POSITIVE_INFINITY; + else + weight = averageWeight / numNonInfiniteWeights; + } - @Override - public int compareTo(MultiTreeSPEntry other) { - AveragedMultiTreeSPEntry o = (AveragedMultiTreeSPEntry) other; - if (weight < o.weight) - return -1; + @Override + public int compareTo(MultiTreeSPEntry other) { + AveragedMultiTreeSPEntry o = (AveragedMultiTreeSPEntry) other; + if (weight < o.weight) + return -1; - // assumption no NaN and no -0 - return weight > o.weight ? 1 : 0; - } + // assumption no NaN and no -0 + return weight > o.weight ? 1 : 0; + } - @Override - public String toString() { - return "adjNode: " + getAdjNode() + ", average weight: " + weight; - } + @Override + public String toString() { + return "adjNode: " + getAdjNode() + ", average weight: " + weight; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorage.java index 13b8865483..7da4dee196 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorage.java @@ -19,156 +19,162 @@ * Graph storage class for the Border Restriction routing */ public class BordersGraphStorage implements GraphExtension { - public enum Property { TYPE, START, END} - /* pointer for no entry */ - protected static final int NO_ENTRY = -1; - private static final int EF_BORDER = 0; // byte location of border type - private static final int EF_START = 2; // byte location of the start country id - private static final int EF_END = 4; // byte location of the end country id - - // border types - public static final short NO_BORDER = 0; - public static final short OPEN_BORDER = 2; - public static final short CONTROLLED_BORDER = 1; - - private DataAccess orsEdges; - private int edgeEntryBytes; - private int edgesCount; // number of edges with custom values - - public BordersGraphStorage() { - - int edgeEntryIndex = 0; - edgeEntryBytes = edgeEntryIndex + 6; // item uses 3 short values which are 2 bytes length each - edgesCount = 0; - } - - /** - * Set values to the edge based on the border type and countries

    - * - * This method takes the internal ID of the edge and adds the information obtained from the Borders CSV file to it - * so that the values can be taken into account when generating a route. - * @param edgeId Internal ID of the graph edge - * @param borderType Level of border crossing (0 - No border, 1 - controlled border, 2 - open border= - * @param start ID of the country that the edge starts in - * @param end ID of the country that the edge ends in - */ - public void setEdgeValue(int edgeId, short borderType, short start, short end) { - edgesCount++; - ensureEdgesIndex(edgeId); - - // add entry - long edgePointer = (long) edgeId * edgeEntryBytes; - - orsEdges.setShort(edgePointer + EF_BORDER, borderType); - orsEdges.setShort(edgePointer + EF_START, start); - orsEdges.setShort(edgePointer + EF_END, end); - } - - private void ensureEdgesIndex(int edgeId) { orsEdges.ensureCapacity(((long) edgeId + 1) * edgeEntryBytes); } - - /** - * Get the specified custom value of the edge that was assigned to it in the setValueEdge method

    - *

    - * The method takes an identifier to the edge and then gets the requested value for the edge from the storage - * - * @param edgeId Internal ID of the edge to get values for - * @param prop The property of the edge to get (TYPE - border type (0,1,2), START - the ID of the country - * the edge starts in, END - the ID of the country the edge ends in. - * @return The value of the requested property - */ - public short getEdgeValue(int edgeId, Property prop) { - long edgePointer = (long) edgeId * edgeEntryBytes; - short border = orsEdges.getShort(edgePointer + EF_BORDER); - short start = orsEdges.getShort(edgePointer + EF_START); - short end = orsEdges.getShort(edgePointer + EF_END); - - return switch (prop) { - case TYPE -> border; - case START -> start; - case END -> end; - default -> 0; - }; - - } - - /** - * initializes the extended storage by giving the base graph - * - * @param graph - * @param dir - */ - @Override - public void init(Graph graph, Directory dir) { - if (edgesCount > 0) - throw new AssertionError("The ORS storage must be initialized only once."); - - this.orsEdges = dir.find("ext_borders"); - } - - /** - * initializes the extended storage to be empty - required for testing purposes as the ext_storage aren't created - * at the time tests are run - */ - public void init() { - if(edgesCount > 0) - throw new AssertionError("The ORS storage must be initialized only once."); - Directory d = new RAMDirectory(); - this.orsEdges = d.find(""); - } - - /** - * @return true if successfully loaded from persistent storage. - */ - @Override - public boolean loadExisting() { - if (!orsEdges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_borders'. corrupt file or directory?"); - - edgeEntryBytes = orsEdges.getHeader(0); - edgesCount = orsEdges.getHeader(4); - return true; - } - - /** - * Creates the underlying storage. First operation if it cannot be loaded. - * - * @param initBytes - */ - @Override - public BordersGraphStorage create(long initBytes) { - orsEdges.create(initBytes * edgeEntryBytes); - return this; - } - - /** - * This method makes sure that the underlying data is written to the storage. Keep in mind that - * a disc normally has an IO cache so that flush() is (less) probably not save against power - * loses. - */ - @Override - public void flush() { - orsEdges.setHeader(0, edgeEntryBytes); - orsEdges.setHeader(4, edgesCount); - orsEdges.flush(); - } - - /** - * This method makes sure that the underlying used resources are released. WARNING: it does NOT - * flush on close! - */ - @Override - public void close() { orsEdges.close(); } - - @Override - public boolean isClosed() { - return false; - } - - /** - * @return the allocated storage size in bytes - */ - @Override - public long getCapacity() { - return orsEdges.getCapacity(); - } + public enum Property {TYPE, START, END} + + /* pointer for no entry */ + protected static final int NO_ENTRY = -1; + private static final int EF_BORDER = 0; // byte location of border type + private static final int EF_START = 2; // byte location of the start country id + private static final int EF_END = 4; // byte location of the end country id + + // border types + public static final short NO_BORDER = 0; + public static final short OPEN_BORDER = 2; + public static final short CONTROLLED_BORDER = 1; + + private DataAccess orsEdges; + private int edgeEntryBytes; + private int edgesCount; // number of edges with custom values + + public BordersGraphStorage() { + + int edgeEntryIndex = 0; + edgeEntryBytes = edgeEntryIndex + 6; // item uses 3 short values which are 2 bytes length each + edgesCount = 0; + } + + /** + * Set values to the edge based on the border type and countries

    + *

    + * This method takes the internal ID of the edge and adds the information obtained from the Borders CSV file to it + * so that the values can be taken into account when generating a route. + * + * @param edgeId Internal ID of the graph edge + * @param borderType Level of border crossing (0 - No border, 1 - controlled border, 2 - open border= + * @param start ID of the country that the edge starts in + * @param end ID of the country that the edge ends in + */ + public void setEdgeValue(int edgeId, short borderType, short start, short end) { + edgesCount++; + ensureEdgesIndex(edgeId); + + // add entry + long edgePointer = (long) edgeId * edgeEntryBytes; + + orsEdges.setShort(edgePointer + EF_BORDER, borderType); + orsEdges.setShort(edgePointer + EF_START, start); + orsEdges.setShort(edgePointer + EF_END, end); + } + + private void ensureEdgesIndex(int edgeId) { + orsEdges.ensureCapacity(((long) edgeId + 1) * edgeEntryBytes); + } + + /** + * Get the specified custom value of the edge that was assigned to it in the setValueEdge method

    + *

    + * The method takes an identifier to the edge and then gets the requested value for the edge from the storage + * + * @param edgeId Internal ID of the edge to get values for + * @param prop The property of the edge to get (TYPE - border type (0,1,2), START - the ID of the country + * the edge starts in, END - the ID of the country the edge ends in. + * @return The value of the requested property + */ + public short getEdgeValue(int edgeId, Property prop) { + long edgePointer = (long) edgeId * edgeEntryBytes; + short border = orsEdges.getShort(edgePointer + EF_BORDER); + short start = orsEdges.getShort(edgePointer + EF_START); + short end = orsEdges.getShort(edgePointer + EF_END); + + return switch (prop) { + case TYPE -> border; + case START -> start; + case END -> end; + default -> 0; + }; + + } + + /** + * initializes the extended storage by giving the base graph + * + * @param graph + * @param dir + */ + @Override + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ORS storage must be initialized only once."); + + this.orsEdges = dir.find("ext_borders"); + } + + /** + * initializes the extended storage to be empty - required for testing purposes as the ext_storage aren't created + * at the time tests are run + */ + public void init() { + if (edgesCount > 0) + throw new AssertionError("The ORS storage must be initialized only once."); + Directory d = new RAMDirectory(); + this.orsEdges = d.find(""); + } + + /** + * @return true if successfully loaded from persistent storage. + */ + @Override + public boolean loadExisting() { + if (!orsEdges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_borders'. corrupt file or directory?"); + + edgeEntryBytes = orsEdges.getHeader(0); + edgesCount = orsEdges.getHeader(4); + return true; + } + + /** + * Creates the underlying storage. First operation if it cannot be loaded. + * + * @param initBytes + */ + @Override + public BordersGraphStorage create(long initBytes) { + orsEdges.create(initBytes * edgeEntryBytes); + return this; + } + + /** + * This method makes sure that the underlying data is written to the storage. Keep in mind that + * a disc normally has an IO cache so that flush() is (less) probably not save against power + * loses. + */ + @Override + public void flush() { + orsEdges.setHeader(0, edgeEntryBytes); + orsEdges.setHeader(4, edgesCount); + orsEdges.flush(); + } + + /** + * This method makes sure that the underlying used resources are released. WARNING: it does NOT + * flush on close! + */ + @Override + public void close() { + orsEdges.close(); + } + + @Override + public boolean isClosed() { + return false; + } + + /** + * @return the allocated storage size in bytes + */ + @Override + public long getCapacity() { + return orsEdges.getCapacity(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/CsvGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/CsvGraphStorage.java index 219b1679e4..49f5cd8a0d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/CsvGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/CsvGraphStorage.java @@ -11,14 +11,14 @@ * You should have received a copy of the GNU Lesser General Public License along with this library; * if not, see . */ -package org.heigit.ors.routing.graphhopper.extensions.storages; + package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.DataAccess; -import com.graphhopper.storage.Directory; -import com.graphhopper.storage.Graph; -import com.graphhopper.storage.GraphExtension; + import com.graphhopper.storage.DataAccess; + import com.graphhopper.storage.Directory; + import com.graphhopper.storage.Graph; + import com.graphhopper.storage.GraphExtension; -import java.util.Arrays; + import java.util.Arrays; public class CsvGraphStorage implements GraphExtension { /* pointer for no entry */ @@ -28,7 +28,7 @@ public class CsvGraphStorage implements GraphExtension { private int edgeEntryBytes; private int edgesCount; // number of edges with custom values private final int numEntries; - private String[] columnNames; + private final String[] columnNames; public CsvGraphStorage(String[] columnNames) { efCsvIndex = 0; @@ -64,7 +64,7 @@ public int getEdgeValue(int edgeId, int columnIndex, byte[] buffer) { public int columnIndex(String columnName) { int index = 0; - for (String name: columnNames) { + for (String name : columnNames) { if (name.equals(columnName)) { return index; } @@ -128,7 +128,9 @@ public void flush() { * flush on close! */ @Override - public void close() { orsEdges.close(); } + public void close() { + orsEdges.close(); + } @Override public boolean isClosed() { @@ -150,6 +152,6 @@ public String[] columnNames() { public int numEntries() { return numEntries; } -} + } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageType.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageType.java index 92d325014b..94a9053597 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageType.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageType.java @@ -16,36 +16,36 @@ import com.graphhopper.util.Helper; public class GraphStorageType { - private static final int VEHICLE_TYPE = 1; - private static final int RESTRICTIONS = 2; - private static final int WAY_CATEGORY = 4; - private static final int WAY_SURFACE_TYPE = 8; - private static final int HILL_INDEX = 16; - - private GraphStorageType() {} - - public static boolean isSet(int type, int value) - { - return (type & value) == value; - } - - public static int getFomString(String value) { - if (Helper.isEmpty(value)) - return 0; - - int res = 0; - String[] values = value.split("\\|"); - for (int i = 0; i < values.length; ++i) { - switch (values[i].toLowerCase()) { - case "vehicletype" -> res |= VEHICLE_TYPE; - case "restrictions" -> res |= RESTRICTIONS; - case "waycategory" -> res |= WAY_CATEGORY; - case "waysurfacetype" -> res |= WAY_SURFACE_TYPE; - case "hillindex" -> res |= HILL_INDEX; - default -> { - } - } - } - return res; - } + private static final int VEHICLE_TYPE = 1; + private static final int RESTRICTIONS = 2; + private static final int WAY_CATEGORY = 4; + private static final int WAY_SURFACE_TYPE = 8; + private static final int HILL_INDEX = 16; + + private GraphStorageType() { + } + + public static boolean isSet(int type, int value) { + return (type & value) == value; + } + + public static int getFomString(String value) { + if (Helper.isEmpty(value)) + return 0; + + int res = 0; + String[] values = value.split("\\|"); + for (int i = 0; i < values.length; ++i) { + switch (values[i].toLowerCase()) { + case "vehicletype" -> res |= VEHICLE_TYPE; + case "restrictions" -> res |= RESTRICTIONS; + case "waycategory" -> res |= WAY_CATEGORY; + case "waysurfacetype" -> res |= WAY_SURFACE_TYPE; + case "hillindex" -> res |= HILL_INDEX; + default -> { + } + } + } + return res; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageUtils.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageUtils.java index 9b14e403bd..d8b52036bf 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageUtils.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GraphStorageUtils.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; @@ -18,16 +18,17 @@ import com.graphhopper.storage.GraphHopperStorage; public class GraphStorageUtils { - private GraphStorageUtils() {} + private GraphStorageUtils() { + } - public static T getGraphExtension(GraphHopperStorage graphStorage, Class type) { - ExtendedStorageSequence ess = graphStorage.getExtensions(); - GraphExtension[] extensions = ess.getExtensions(); - for (GraphExtension e: extensions) { - if (type.isInstance(e)) { - return (T)e; - } - } - return null; - } + public static T getGraphExtension(GraphHopperStorage graphStorage, Class type) { + ExtendedStorageSequence ess = graphStorage.getExtensions(); + GraphExtension[] extensions = ess.getExtensions(); + for (GraphExtension e : extensions) { + if (type.isInstance(e)) { + return (T) e; + } + } + return null; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GreenIndexGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GreenIndexGraphStorage.java index 3241e26ad4..e36224c314 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GreenIndexGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/GreenIndexGraphStorage.java @@ -1,19 +1,22 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; public class GreenIndexGraphStorage implements GraphExtension { /* pointer for no entry */ @@ -104,7 +107,9 @@ public void init(Graph graph, Directory dir) { * flush on close! */ @Override - public void close() { orsEdges.close(); } + public void close() { + orsEdges.close(); + } @Override public long getCapacity() { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HeavyVehicleAttributesGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HeavyVehicleAttributesGraphStorage.java index 19421a2e56..305ddbc271 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HeavyVehicleAttributesGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HeavyVehicleAttributesGraphStorage.java @@ -1,180 +1,183 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.BitUtil; import org.heigit.ors.routing.graphhopper.extensions.VehicleDimensionRestrictions; public class HeavyVehicleAttributesGraphStorage implements GraphExtension { - private static final int EF_RESTRICTION_BYTES = 2; - private static final String MSG_EF_RESTRICTION_IS_NOT_SUPPORTED = "EF_RESTRICTION is not supported."; - - private final int efVehicleType; - private final int efRestrictions; - - private DataAccess orsEdges; - protected int edgeEntryIndex = 0; - protected int edgeEntryBytes; - protected int edgesCount; + private static final int EF_RESTRICTION_BYTES = 2; + private static final String MSG_EF_RESTRICTION_IS_NOT_SUPPORTED = "EF_RESTRICTION is not supported."; - private static final double FACTOR = 100.0; + private final int efVehicleType; + private final int efRestrictions; - public HeavyVehicleAttributesGraphStorage(boolean includeRestrictions) { - efVehicleType = nextBlockEntryIndex(1); + private DataAccess orsEdges; + protected int edgeEntryIndex = 0; + protected int edgeEntryBytes; + protected int edgesCount; - if (includeRestrictions) - // first byte indicates whether any restrictions are given - efRestrictions = nextBlockEntryIndex(VehicleDimensionRestrictions.COUNT * EF_RESTRICTION_BYTES); - else - efRestrictions = -1; - - edgeEntryBytes = edgeEntryIndex; - edgesCount = 0; - } - - public void init(Graph graph, Directory dir) { - if (edgesCount > 0) - throw new AssertionError("The ext_hgv storage must be initialized only once."); - - this.orsEdges = dir.find("ext_hgv"); - } - - private int nextBlockEntryIndex(int size) { - int res = edgeEntryIndex; - edgeEntryIndex += size; - return res; - } - - public void setSegmentSize(int bytes) { - orsEdges.setSegmentSize(bytes); - } - - public HeavyVehicleAttributesGraphStorage create(long initBytes) { - orsEdges.create(initBytes * edgeEntryBytes); - return this; - } - - public void flush() { - orsEdges.setHeader(0, edgeEntryBytes); - orsEdges.setHeader(4, edgesCount); - orsEdges.flush(); - } - - public void close() { - orsEdges.close(); - } - - public int entries() { - return edgesCount; - } - - public boolean loadExisting() { - if (!orsEdges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_hgv'. corrupt file or directory? "); - - edgeEntryBytes = orsEdges.getHeader(0); - edgesCount = orsEdges.getHeader(4); - return true; - } - - private void ensureEdgesIndex(int edgeIndex) { - orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); - } - - public void setEdgeValue(int edgeId, int vehicleType, int heavyVehicleDestination, double[] restrictionValues) { - edgesCount++; - ensureEdgesIndex(edgeId); - - long edgePointer = (long) edgeId * edgeEntryBytes; - - byte [] byteValues = {(byte) vehicleType, (byte) heavyVehicleDestination}; - orsEdges.setBytes(edgePointer + efVehicleType, byteValues, 2); - - if (efRestrictions == -1) - throw new IllegalStateException(MSG_EF_RESTRICTION_IS_NOT_SUPPORTED); - - byte[] buffer = new byte[2]; - for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) { - short shortValue = (short) (restrictionValues[i] * FACTOR); - BitUtil.LITTLE.fromShort(buffer, shortValue); - orsEdges.setBytes(edgePointer + efRestrictions + i * EF_RESTRICTION_BYTES, buffer, 2); - } - } - - public double getEdgeRestrictionValue(int edgeId, int valueIndex) { - long edgeBase = (long) edgeId * edgeEntryBytes; - - if (efRestrictions == -1) - throw new IllegalStateException(MSG_EF_RESTRICTION_IS_NOT_SUPPORTED); - - return getShort(edgeBase + efRestrictions + valueIndex * EF_RESTRICTION_BYTES) / FACTOR; - } - - public boolean getEdgeRestrictionValues(int edgeId, double[] retValues) { - long edgeBase = (long) edgeId * edgeEntryBytes; - - if (efRestrictions == -1) - throw new IllegalStateException(MSG_EF_RESTRICTION_IS_NOT_SUPPORTED); - - for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) - retValues[i] = getShort(edgeBase + efRestrictions + i * EF_RESTRICTION_BYTES) / FACTOR; - - return true; - } - - public int getEdgeVehicleType(int edgeId, byte[] buffer) { - long edgeBase = (long) edgeId * edgeEntryBytes; - orsEdges.getBytes(edgeBase + efVehicleType, buffer, 2); - - int result = buffer[0]; - if (result < 0) - result = (byte)(result & 0xff); - - return result; - } - - public boolean hasEdgeRestriction(int edgeId) { - long edgeBase = (long) edgeId * edgeEntryBytes; - - byte[] buffer = new byte[2]; - orsEdges.getBytes(edgeBase + efVehicleType, buffer, 2); - - if (buffer[0] != 0 || buffer[1] != 0) - return true; - - if (efRestrictions > 0) - for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) - if (getShort(edgeBase + efRestrictions + i * EF_RESTRICTION_BYTES) != 0) - return true; - - return false; - } - - private short getShort(long bytePos) { - byte[] buffer = new byte[2]; - orsEdges.getBytes(bytePos, buffer, 2); - return BitUtil.LITTLE.toShort(buffer); - } - - @Override - public long getCapacity() { - return orsEdges.getCapacity(); - } - - @Override - public boolean isClosed() { - return false; - } + private static final double FACTOR = 100.0; + + public HeavyVehicleAttributesGraphStorage(boolean includeRestrictions) { + efVehicleType = nextBlockEntryIndex(1); + + if (includeRestrictions) + // first byte indicates whether any restrictions are given + efRestrictions = nextBlockEntryIndex(VehicleDimensionRestrictions.COUNT * EF_RESTRICTION_BYTES); + else + efRestrictions = -1; + + edgeEntryBytes = edgeEntryIndex; + edgesCount = 0; + } + + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ext_hgv storage must be initialized only once."); + + this.orsEdges = dir.find("ext_hgv"); + } + + private int nextBlockEntryIndex(int size) { + int res = edgeEntryIndex; + edgeEntryIndex += size; + return res; + } + + public void setSegmentSize(int bytes) { + orsEdges.setSegmentSize(bytes); + } + + public HeavyVehicleAttributesGraphStorage create(long initBytes) { + orsEdges.create(initBytes * edgeEntryBytes); + return this; + } + + public void flush() { + orsEdges.setHeader(0, edgeEntryBytes); + orsEdges.setHeader(4, edgesCount); + orsEdges.flush(); + } + + public void close() { + orsEdges.close(); + } + + public int entries() { + return edgesCount; + } + + public boolean loadExisting() { + if (!orsEdges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_hgv'. corrupt file or directory? "); + + edgeEntryBytes = orsEdges.getHeader(0); + edgesCount = orsEdges.getHeader(4); + return true; + } + + private void ensureEdgesIndex(int edgeIndex) { + orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); + } + + public void setEdgeValue(int edgeId, int vehicleType, int heavyVehicleDestination, double[] restrictionValues) { + edgesCount++; + ensureEdgesIndex(edgeId); + + long edgePointer = (long) edgeId * edgeEntryBytes; + + byte[] byteValues = {(byte) vehicleType, (byte) heavyVehicleDestination}; + orsEdges.setBytes(edgePointer + efVehicleType, byteValues, 2); + + if (efRestrictions == -1) + throw new IllegalStateException(MSG_EF_RESTRICTION_IS_NOT_SUPPORTED); + + byte[] buffer = new byte[2]; + for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) { + short shortValue = (short) (restrictionValues[i] * FACTOR); + BitUtil.LITTLE.fromShort(buffer, shortValue); + orsEdges.setBytes(edgePointer + efRestrictions + i * EF_RESTRICTION_BYTES, buffer, 2); + } + } + + public double getEdgeRestrictionValue(int edgeId, int valueIndex) { + long edgeBase = (long) edgeId * edgeEntryBytes; + + if (efRestrictions == -1) + throw new IllegalStateException(MSG_EF_RESTRICTION_IS_NOT_SUPPORTED); + + return getShort(edgeBase + efRestrictions + (long) valueIndex * EF_RESTRICTION_BYTES) / FACTOR; + } + + public boolean getEdgeRestrictionValues(int edgeId, double[] retValues) { + long edgeBase = (long) edgeId * edgeEntryBytes; + + if (efRestrictions == -1) + throw new IllegalStateException(MSG_EF_RESTRICTION_IS_NOT_SUPPORTED); + + for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) + retValues[i] = getShort(edgeBase + efRestrictions + i * EF_RESTRICTION_BYTES) / FACTOR; + + return true; + } + + public int getEdgeVehicleType(int edgeId, byte[] buffer) { + long edgeBase = (long) edgeId * edgeEntryBytes; + orsEdges.getBytes(edgeBase + efVehicleType, buffer, 2); + + int result = buffer[0]; + if (result < 0) + result = (byte) (result & 0xff); + + return result; + } + + public boolean hasEdgeRestriction(int edgeId) { + long edgeBase = (long) edgeId * edgeEntryBytes; + + byte[] buffer = new byte[2]; + orsEdges.getBytes(edgeBase + efVehicleType, buffer, 2); + + if (buffer[0] != 0 || buffer[1] != 0) + return true; + + if (efRestrictions > 0) + for (int i = 0; i < VehicleDimensionRestrictions.COUNT; i++) + if (getShort(edgeBase + efRestrictions + i * EF_RESTRICTION_BYTES) != 0) + return true; + + return false; + } + + private short getShort(long bytePos) { + byte[] buffer = new byte[2]; + orsEdges.getBytes(bytePos, buffer, 2); + return BitUtil.LITTLE.toShort(buffer); + } + + @Override + public long getCapacity() { + return orsEdges.getCapacity(); + } + + @Override + public boolean isClosed() { + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HillIndexGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HillIndexGraphStorage.java index a79c214878..d930e3364e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HillIndexGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/HillIndexGraphStorage.java @@ -1,135 +1,137 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import java.util.Map; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; -import com.graphhopper.storage.*; +import java.util.Map; public class HillIndexGraphStorage implements GraphExtension { - private final int efHillIndex; - - private DataAccess orsEdges; - protected int edgeEntryIndex = 0; - protected int edgeEntryBytes; - protected int edgesCount; // number of edges with custom values - - private int maxHillIndex = 15; - - private final byte[] byteValues; - - public HillIndexGraphStorage(Map parameters) { - efHillIndex = 0; - - if (parameters.containsKey("maximum_slope")) - maxHillIndex = (int)Double.parseDouble(parameters.get("maximum_slope")); - - edgeEntryBytes = edgeEntryIndex + (maxHillIndex > 15 ? 2 : 1); - edgesCount = 0; - byteValues = new byte[2]; - } - - public void init(Graph graph, Directory dir) { - if (edgesCount > 0) - throw new AssertionError("The ORS storage must be initialized only once."); - - this.orsEdges = dir.find("ext_hillindex"); - } - - public HillIndexGraphStorage create(long initBytes) { - orsEdges.create(initBytes * edgeEntryBytes); - return this; - } - - public void flush() { - orsEdges.setHeader(0, edgeEntryBytes); - orsEdges.setHeader(4, edgesCount); - orsEdges.flush(); - } - - @Override - public long getCapacity() { - return orsEdges.getCapacity(); - } - - public void close() { - orsEdges.close(); - } - - public int entries() { - return edgesCount; - } - - public boolean loadExisting() { - if (!orsEdges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_hillindex'. corrupt file or directory?"); - - edgeEntryBytes = orsEdges.getHeader(0); - edgesCount = orsEdges.getHeader(4); - return true; - } - - private void ensureEdgesIndex(int edgeIndex) { - orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); - } - - private int getHillIndex(int value) - { - return Math.min(value, maxHillIndex); - } - - public void setEdgeValue(int edgeId, int hillIndex, int reverseHillIndex) { - edgesCount++; - ensureEdgesIndex(edgeId); - - if (hillIndex != 0 || reverseHillIndex != 0) { - // add entry - long edgePointer = (long) edgeId * edgeEntryBytes; - if (maxHillIndex <= 15) { - byteValues[0] = (byte)(getHillIndex(hillIndex) << 4 | (0x0F & getHillIndex(reverseHillIndex))); //hillIndex | (reverseHillIndex << 4)) - orsEdges.setBytes(edgePointer + efHillIndex, byteValues, 1); - } else { - byteValues[0] = (byte)getHillIndex(hillIndex); - byteValues[1] = (byte)getHillIndex(reverseHillIndex); - orsEdges.setBytes(edgePointer + efHillIndex, byteValues, 2); - } - } - } - - public int getEdgeValue(int edgeId, boolean reverse, byte[] buffer) { - long edgePointer = (long) edgeId * edgeEntryBytes; - - if (maxHillIndex <= 15) { - orsEdges.getBytes(edgePointer + efHillIndex, buffer, 1); - - int value = buffer[0]; - if (value < 0) - value = 256 + value; - - if (reverse) - return (value >> 4) & 0xF; - else - return value & 0xF; - } else { - orsEdges.getBytes(edgePointer + efHillIndex, buffer, 2); - - return reverse ? buffer[1] : buffer[0]; - } - } - - @Override - public boolean isClosed() { - return false; - } + private final int efHillIndex; + + private DataAccess orsEdges; + protected int edgeEntryIndex = 0; + protected int edgeEntryBytes; + protected int edgesCount; // number of edges with custom values + + private int maxHillIndex = 15; + + private final byte[] byteValues; + + public HillIndexGraphStorage(Map parameters) { + efHillIndex = 0; + + if (parameters.containsKey("maximum_slope")) + maxHillIndex = (int) Double.parseDouble(parameters.get("maximum_slope")); + + edgeEntryBytes = edgeEntryIndex + (maxHillIndex > 15 ? 2 : 1); + edgesCount = 0; + byteValues = new byte[2]; + } + + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ORS storage must be initialized only once."); + + this.orsEdges = dir.find("ext_hillindex"); + } + + public HillIndexGraphStorage create(long initBytes) { + orsEdges.create(initBytes * edgeEntryBytes); + return this; + } + + public void flush() { + orsEdges.setHeader(0, edgeEntryBytes); + orsEdges.setHeader(4, edgesCount); + orsEdges.flush(); + } + + @Override + public long getCapacity() { + return orsEdges.getCapacity(); + } + + public void close() { + orsEdges.close(); + } + + public int entries() { + return edgesCount; + } + + public boolean loadExisting() { + if (!orsEdges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_hillindex'. corrupt file or directory?"); + + edgeEntryBytes = orsEdges.getHeader(0); + edgesCount = orsEdges.getHeader(4); + return true; + } + + private void ensureEdgesIndex(int edgeIndex) { + orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); + } + + private int getHillIndex(int value) { + return Math.min(value, maxHillIndex); + } + + public void setEdgeValue(int edgeId, int hillIndex, int reverseHillIndex) { + edgesCount++; + ensureEdgesIndex(edgeId); + + if (hillIndex != 0 || reverseHillIndex != 0) { + // add entry + long edgePointer = (long) edgeId * edgeEntryBytes; + if (maxHillIndex <= 15) { + byteValues[0] = (byte) (getHillIndex(hillIndex) << 4 | (0x0F & getHillIndex(reverseHillIndex))); //hillIndex | (reverseHillIndex << 4)) + orsEdges.setBytes(edgePointer + efHillIndex, byteValues, 1); + } else { + byteValues[0] = (byte) getHillIndex(hillIndex); + byteValues[1] = (byte) getHillIndex(reverseHillIndex); + orsEdges.setBytes(edgePointer + efHillIndex, byteValues, 2); + } + } + } + + public int getEdgeValue(int edgeId, boolean reverse, byte[] buffer) { + long edgePointer = (long) edgeId * edgeEntryBytes; + + if (maxHillIndex <= 15) { + orsEdges.getBytes(edgePointer + efHillIndex, buffer, 1); + + int value = buffer[0]; + if (value < 0) + value = 256 + value; + + if (reverse) + return (value >> 4) & 0xF; + else + return value & 0xF; + } else { + orsEdges.getBytes(edgePointer + efHillIndex, buffer, 2); + + return reverse ? buffer[1] : buffer[0]; + } + } + + @Override + public boolean isClosed() { + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntry.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntry.java index 75097370f1..076c6fc606 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntry.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntry.java @@ -1,108 +1,107 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; /** * This class is used to create the shortest-path-tree from linked entities. *

    - * */ public class MultiTreeSPEntry implements Comparable { - private int adjNode; - protected int edge; - private boolean visited = false; - private final MultiTreeSPEntryItem[] items; - private double totalWeight = 0.0; - - public MultiTreeSPEntry(int adjNode, int edgeId, double edgeWeight, boolean updated, MultiTreeSPEntry parent, int numTrees) { - this.adjNode = adjNode; - this.edge = edgeId; - this.items = new MultiTreeSPEntryItem[numTrees]; - double entryWeight; - - for (int i = 0; i < numTrees; ++i) { - MultiTreeSPEntryItem item = new MultiTreeSPEntryItem(); - items[i] = item; - - entryWeight = parent == null ? Double.POSITIVE_INFINITY : parent.items[i].getWeight(); - if (entryWeight == Double.POSITIVE_INFINITY && parent != null) - continue; - - item.setWeight(edgeWeight + entryWeight); - item.setParent(parent); - item.setEdge(edgeId); - item.setOriginalEdge(edgeId); - item.setUpdate(updated); - totalWeight += item.getWeight(); - } - } - - public int getAdjNode() { - return adjNode; - } - - public void setAdjNode(int adjNode) { - this.adjNode = adjNode; - } - - public int getEdge() {return edge;} - - public boolean isVisited() { - return visited; - } - - public void setVisited(boolean visited) { - this.visited = visited; - } - - public int getSize() - { - return items.length; - } - - public MultiTreeSPEntryItem getItem(int index) - { - return items[index]; - } - - public void resetUpdate(boolean value) { - for (int i = 0; i < items.length; i++) { - items[i].setUpdate(value); - } - } - - public void updateWeights() { - totalWeight = 0.0; - - for (int i = 0; i < items.length; i++) { - if(items[i].getWeight() == Double.POSITIVE_INFINITY) continue; - totalWeight += items[i].getWeight(); - } - } - - @Override - public int compareTo(MultiTreeSPEntry o) { - if (totalWeight < o.totalWeight) - return -1; - - // assumption no NaN and no -0 - return totalWeight > o.totalWeight ? 1 : 0; - } - - @Override - public String toString() { - return "adjNode: " + adjNode + ", totalWeight: " + totalWeight; // TODO - } + private int adjNode; + protected int edge; + private boolean visited = false; + private final MultiTreeSPEntryItem[] items; + private double totalWeight = 0.0; + + public MultiTreeSPEntry(int adjNode, int edgeId, double edgeWeight, boolean updated, MultiTreeSPEntry parent, int numTrees) { + this.adjNode = adjNode; + this.edge = edgeId; + this.items = new MultiTreeSPEntryItem[numTrees]; + double entryWeight; + + for (int i = 0; i < numTrees; ++i) { + MultiTreeSPEntryItem item = new MultiTreeSPEntryItem(); + items[i] = item; + + entryWeight = parent == null ? Double.POSITIVE_INFINITY : parent.items[i].getWeight(); + if (entryWeight == Double.POSITIVE_INFINITY && parent != null) + continue; + + item.setWeight(edgeWeight + entryWeight); + item.setParent(parent); + item.setEdge(edgeId); + item.setOriginalEdge(edgeId); + item.setUpdate(updated); + totalWeight += item.getWeight(); + } + } + + public int getAdjNode() { + return adjNode; + } + + public void setAdjNode(int adjNode) { + this.adjNode = adjNode; + } + + public int getEdge() { + return edge; + } + + public boolean isVisited() { + return visited; + } + + public void setVisited(boolean visited) { + this.visited = visited; + } + + public int getSize() { + return items.length; + } + + public MultiTreeSPEntryItem getItem(int index) { + return items[index]; + } + + public void resetUpdate(boolean value) { + for (int i = 0; i < items.length; i++) { + items[i].setUpdate(value); + } + } + + public void updateWeights() { + totalWeight = 0.0; + + for (int i = 0; i < items.length; i++) { + if (items[i].getWeight() == Double.POSITIVE_INFINITY) continue; + totalWeight += items[i].getWeight(); + } + } + + @Override + public int compareTo(MultiTreeSPEntry o) { + if (totalWeight < o.totalWeight) + return -1; + + // assumption no NaN and no -0 + return totalWeight > o.totalWeight ? 1 : 0; + } + + @Override + public String toString() { + return "adjNode: " + adjNode + ", totalWeight: " + totalWeight; // TODO + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntryItem.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntryItem.java index 3a69c59061..a9cac08858 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntryItem.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/MultiTreeSPEntryItem.java @@ -1,79 +1,79 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; import com.graphhopper.util.EdgeIterator; public class MultiTreeSPEntryItem { - private int edge = EdgeIterator.NO_EDGE; - private int originalEdge = EdgeIterator.NO_EDGE; - private int incEdge = EdgeIterator.NO_EDGE; - private double weight = Double.POSITIVE_INFINITY; - private boolean update = false; - private MultiTreeSPEntry parent = null; - - public int getEdge() { - return edge; - } - - public void setEdge(int edge) { - this.edge = edge; - } - - public int getOriginalEdge() { - return originalEdge; - } - - public void setOriginalEdge(int originalEdge) { - this.originalEdge = originalEdge; - } - - public int getIncEdge() { - return incEdge; - } - - public void setIncEdge(int incEdge) { - this.incEdge = incEdge; - } - - public double getWeight() { - return weight; - } - - public void setWeight(double weight) { - this.weight = weight; - } - - public boolean isUpdate() { - return update; - } - - public void setUpdate(boolean update) { - this.update = update; - } - - public MultiTreeSPEntry getParent() { - return parent; - } - - public void setParent(MultiTreeSPEntry parent) { - this.parent = parent; - } - - @Override - public String toString() { - return String.valueOf(weight); - } + private int edge = EdgeIterator.NO_EDGE; + private int originalEdge = EdgeIterator.NO_EDGE; + private int incEdge = EdgeIterator.NO_EDGE; + private double weight = Double.POSITIVE_INFINITY; + private boolean update = false; + private MultiTreeSPEntry parent = null; + + public int getEdge() { + return edge; + } + + public void setEdge(int edge) { + this.edge = edge; + } + + public int getOriginalEdge() { + return originalEdge; + } + + public void setOriginalEdge(int originalEdge) { + this.originalEdge = originalEdge; + } + + public int getIncEdge() { + return incEdge; + } + + public void setIncEdge(int incEdge) { + this.incEdge = incEdge; + } + + public double getWeight() { + return weight; + } + + public void setWeight(double weight) { + this.weight = weight; + } + + public boolean isUpdate() { + return update; + } + + public void setUpdate(boolean update) { + this.update = update; + } + + public MultiTreeSPEntry getParent() { + return parent; + } + + public void setParent(MultiTreeSPEntry parent) { + this.parent = parent; + } + + @Override + public String toString() { + return String.valueOf(weight); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/NoiseIndexGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/NoiseIndexGraphStorage.java index 47d73ab591..15839fe313 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/NoiseIndexGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/NoiseIndexGraphStorage.java @@ -1,19 +1,22 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; /** * Created by ZWang on 13/06/2017. @@ -52,7 +55,7 @@ private void ensureEdgesIndex(int edgeId) { } public int getEdgeValue(int edgeId, byte[] buffer) { - + long edgePointer = (long) edgeId * edgeEntryBytes; orsEdges.getBytes(edgePointer + efNoiseindex, buffer, 1); @@ -108,7 +111,9 @@ public void init(Graph graph, Directory dir) { * flush on close! */ @Override - public void close() { orsEdges.close(); } + public void close() { + orsEdges.close(); + } @Override public long getCapacity() { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/OsmIdGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/OsmIdGraphStorage.java index c78fe617ed..64b7a64762 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/OsmIdGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/OsmIdGraphStorage.java @@ -33,7 +33,7 @@ public void init(Graph graph, Directory dir) { * at the time tests are run */ public void init() { - if(edgesCount > 0) + if (edgesCount > 0) throw new AssertionError("The ORS storage must be initialized only once."); Directory d = new RAMDirectory(); this.orsEdges = d.find(""); @@ -65,7 +65,7 @@ public int entries() { public boolean loadExisting() { if (!orsEdges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_osmids'. corrupt file or directory? " ); + throw new IllegalStateException("Unable to load storage 'ext_osmids'. corrupt file or directory? "); edgeEntryBytes = orsEdges.getHeader(0); edgesCount = orsEdges.getHeader(4); @@ -78,8 +78,9 @@ void ensureEdgesIndex(int edgeIndex) { /** * Set the osm id of an edge to the spcified value. - * @param edgeId The internal id of the edge in the graph - * @param osmId The osm idto be assigned ot the edge + * + * @param edgeId The internal id of the edge in the graph + * @param osmId The osm idto be assigned ot the edge */ public void setEdgeValue(int edgeId, long osmId) { edgesCount++; @@ -97,8 +98,9 @@ public void setEdgeValue(int edgeId, long osmId) { /** * Get the OSM id of the edge specified - * @param edgeId The internal graph id of the edge that the OSM way ID is required for - * @return The OSM ID that was stored for the edge (normally the OSM ID of the way the edge was created from) + * + * @param edgeId The internal graph id of the edge that the OSM way ID is required for + * @return The OSM ID that was stored for the edge (normally the OSM ID of the way the edge was created from) */ public long getEdgeValue(int edgeId) { byte[] buffer = new byte[4]; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/ShadowIndexGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/ShadowIndexGraphStorage.java index 3f575f9119..3f309577e1 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/ShadowIndexGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/ShadowIndexGraphStorage.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; @@ -30,7 +30,7 @@ public class ShadowIndexGraphStorage implements GraphExtension { private int edgeEntryBytes; private int edgesCount; // number of edges with custom values - private byte[] byteValues; + private final byte[] byteValues; public ShadowIndexGraphStorage() { EF_shadowIndex = 0; @@ -56,7 +56,7 @@ private void ensureEdgesIndex(int edgeId) { } public int getEdgeValue(int edgeId, byte[] buffer) { - + long edgePointer = (long) edgeId * edgeEntryBytes; orsEdges.getBytes(edgePointer + EF_shadowIndex, buffer, 1); @@ -97,7 +97,7 @@ public boolean loadExisting() { */ @Override public GraphExtension create(long initBytes) { - orsEdges.create((long) initBytes * edgeEntryBytes); + orsEdges.create(initBytes * edgeEntryBytes); return this; } @@ -109,7 +109,7 @@ public GraphExtension create(long initBytes) { @Override public void flush() { orsEdges.setHeader(0, edgeEntryBytes); - orsEdges.setHeader(1 * 4, edgesCount); + orsEdges.setHeader(4, edgesCount); orsEdges.flush(); } @@ -118,7 +118,9 @@ public void flush() { * flush on close! */ @Override - public void close() { orsEdges.close(); } + public void close() { + orsEdges.close(); + } @Override public boolean isClosed() { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/SpeedStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/SpeedStorage.java index c4f6cff074..dfb1083a79 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/SpeedStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/SpeedStorage.java @@ -59,8 +59,8 @@ public void setSpeed(int edgeId, boolean reverse, byte speed) { speedData.setBytes(BYTE_COUNT * edgeId + (reverse ? BYTE_POS_SPEED_REVERSE : BYTE_POS_SPEED), new byte[]{speed}, 1); } - public void setSpeed(int edgeId, boolean reverse, int speed){ - if(speed > Byte.MAX_VALUE || speed < Byte.MIN_VALUE) + public void setSpeed(int edgeId, boolean reverse, int speed) { + if (speed > Byte.MAX_VALUE || speed < Byte.MIN_VALUE) throw new IllegalArgumentException("Speed value " + speed + " out of range: " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE); this.setSpeed(edgeId, reverse, (byte) speed); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TollwaysGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TollwaysGraphStorage.java index 3b7361ac7c..649330b08e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TollwaysGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TollwaysGraphStorage.java @@ -1,124 +1,127 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; public class TollwaysGraphStorage implements GraphExtension { - /* pointer for no entry */ - protected final int efTollways; - - protected DataAccess edges; - protected int edgeEntryIndex = 0; - protected int edgeEntryBytes; - protected int edgesCount; - - public TollwaysGraphStorage() { - efTollways = nextBlockEntryIndex (1); - - edgeEntryBytes = edgeEntryIndex; - edgesCount = 0; - } - - public void init(Graph graph, Directory dir) { - if (edgesCount > 0) - throw new AssertionError("The ext_tolls storage must be initialized only once."); - - this.edges = dir.find("ext_tolls"); - } - - protected final int nextBlockEntryIndex(int size) { - int res = edgeEntryIndex; - edgeEntryIndex += size; - return res; - } - - public void setSegmentSize(int bytes) { - edges.setSegmentSize(bytes); - } - - public TollwaysGraphStorage create(long initBytes) { - edges.create(initBytes * edgeEntryBytes); - return this; - } - - public void flush() { - edges.setHeader(0, edgeEntryBytes); - edges.setHeader(4, edgesCount); - edges.flush(); - } - - public void close() { - edges.close(); - } - - @Override - public long getCapacity() { - return edges.getCapacity(); - } - - public int entries() { - return edgesCount; - } - - public boolean loadExisting() { - if (!edges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_tolls'. corrupt file or directory? "); - - edgeEntryBytes = edges.getHeader(0); - edgesCount = edges.getHeader(4); - return true; - } - - void ensureEdgesIndex(int edgeIndex) { - edges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); - } - - public void setEdgeValue(int edgeId, int value) { - edgesCount++; - ensureEdgesIndex(edgeId); - - byte byteValue = (byte) value; - - edges.setByte((long) edgeId * edgeEntryBytes + efTollways, byteValue); - } - - public int getEdgeValue(int edgeId) { - byte byteValue = edges.getByte((long) edgeId * edgeEntryBytes + efTollways); - return byteValue & 0xFF; - } - - public boolean isRequireNodeField() { - return true; - } - - public boolean isRequireEdgeField() { - // we require the additional field in the graph to point to the first - // entry in the node table - return true; - } - - public int getDefaultNodeFieldValue() { - return -1; - } - - public int getDefaultEdgeFieldValue() { - return -1; - } - - @Override - public boolean isClosed() { - return false; - } + /* pointer for no entry */ + protected final int efTollways; + + protected DataAccess edges; + protected int edgeEntryIndex = 0; + protected int edgeEntryBytes; + protected int edgesCount; + + public TollwaysGraphStorage() { + efTollways = nextBlockEntryIndex(1); + + edgeEntryBytes = edgeEntryIndex; + edgesCount = 0; + } + + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ext_tolls storage must be initialized only once."); + + this.edges = dir.find("ext_tolls"); + } + + protected final int nextBlockEntryIndex(int size) { + int res = edgeEntryIndex; + edgeEntryIndex += size; + return res; + } + + public void setSegmentSize(int bytes) { + edges.setSegmentSize(bytes); + } + + public TollwaysGraphStorage create(long initBytes) { + edges.create(initBytes * edgeEntryBytes); + return this; + } + + public void flush() { + edges.setHeader(0, edgeEntryBytes); + edges.setHeader(4, edgesCount); + edges.flush(); + } + + public void close() { + edges.close(); + } + + @Override + public long getCapacity() { + return edges.getCapacity(); + } + + public int entries() { + return edgesCount; + } + + public boolean loadExisting() { + if (!edges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_tolls'. corrupt file or directory? "); + + edgeEntryBytes = edges.getHeader(0); + edgesCount = edges.getHeader(4); + return true; + } + + void ensureEdgesIndex(int edgeIndex) { + edges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); + } + + public void setEdgeValue(int edgeId, int value) { + edgesCount++; + ensureEdgesIndex(edgeId); + + byte byteValue = (byte) value; + + edges.setByte((long) edgeId * edgeEntryBytes + efTollways, byteValue); + } + + public int getEdgeValue(int edgeId) { + byte byteValue = edges.getByte((long) edgeId * edgeEntryBytes + efTollways); + return byteValue & 0xFF; + } + + public boolean isRequireNodeField() { + return true; + } + + public boolean isRequireEdgeField() { + // we require the additional field in the graph to point to the first + // entry in the node table + return true; + } + + public int getDefaultNodeFieldValue() { + return -1; + } + + public int getDefaultEdgeFieldValue() { + return -1; + } + + @Override + public boolean isClosed() { + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrafficGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrafficGraphStorage.java index 6f64b3838e..c2cc0add9e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrafficGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrafficGraphStorage.java @@ -13,11 +13,7 @@ */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.DataAccess; -import com.graphhopper.storage.Directory; -import com.graphhopper.storage.Graph; -import com.graphhopper.storage.GraphExtension; -import com.graphhopper.storage.RAMDirectory; +import com.graphhopper.storage.*; import com.graphhopper.util.GHUtility; import org.heigit.ors.routing.graphhopper.extensions.reader.traffic.TrafficEnums; @@ -85,9 +81,9 @@ public enum RoadTypes { private int edgesCount; // number of edges with custom values private int maxEdgeId = 0; // highest edge id for which traffic data is available private int patternCount; // number of traffic patterns - private byte[] propertyValue; - private byte[] speedValue; - private byte[] priorityValue; + private final byte[] propertyValue; + private final byte[] speedValue; + private final byte[] priorityValue; public TrafficGraphStorage() { int edgeEntryIndex = 0; @@ -142,7 +138,6 @@ public void setOrsRoadProperties(int edgeId, Property prop, short value) { *

    * This method takes the ID of the traffic edge and adds the weekday specific pattern Id to the lookup. * - * * @param edgeKey Edge key * @param patternId Id of the traffic pattern. * @param weekday Enum value for the weekday the traffic pattern Id refers to. @@ -226,7 +221,7 @@ private void setTrafficSpeed(int patternId, short speedValue, int hour, int minu ensureSpeedPatternLookupIndex(patternId); speedValue = speedValue > 255 ? 255 : speedValue; this.speedValue[0] = (byte) speedValue; - orsSpeedPatternLookup.setBytes(patternPointer + ((hour * 4) + minutePointer), this.speedValue, 1); + orsSpeedPatternLookup.setBytes(patternPointer + ((hour * 4L) + minutePointer), this.speedValue, 1); } /** @@ -267,8 +262,8 @@ public int getOrsRoadProperties(int edgeId, Property prop) { *

    * This method returns the linkID matched on the internal edge ID in both directions if present. * - * @param edgeKey Internal ID of the graph edge. - * @param weekday Enum of Weekday to get the pattern for. + * @param edgeKey Internal ID of the graph edge. + * @param weekday Enum of Weekday to get the pattern for. **/ public int getEdgeIdTrafficPatternLookup(int edgeKey, TrafficEnums.WeekDay weekday) { int edgeId = GHUtility.getEdgeFromEdgeKey(edgeKey); @@ -295,8 +290,8 @@ private boolean invalidEdgeId(int edgeId) { *

    * e.g. This function can be used to retrieve the stored length of the last ors edge <-> traffic edge match. * - * @param edgeId Internal ID of the graph edge. - * @param forward Direction + * @param edgeId Internal ID of the graph edge. + * @param forward Direction **/ private int getEdgeIdTrafficPatternPriority(int edgeId, boolean forward) { long edgePointer = (long) edgeId * edgeLinkLookupEntryBytes; @@ -321,7 +316,7 @@ public int getTrafficSpeed(int patternId, int hour, int minute) { byte[] values = new byte[1]; int minutePointer = generateMinutePointer(minute); long patternPointer = (long) patternId * patternEntryBytes; - orsSpeedPatternLookup.getBytes(patternPointer + ((hour * 4) + minutePointer), values, 1); + orsSpeedPatternLookup.getBytes(patternPointer + ((hour * 4L) + minutePointer), values, 1); return Byte.toUnsignedInt(values[0]); } @@ -350,7 +345,7 @@ private int getMaxTrafficSpeed(int patternId) { * ## TODO's ## * - enhance internal time encoding and harmonize it in the whole ORS backend when more traffic data comes in. * - * @param edgeKey Internal Edge Key + * @param edgeKey Internal Edge Key * @param unixMilliSeconds Time in unix milliseconds. * @return Returns the speed value in kph. If no value is found -1 is returned. */ diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrailDifficultyScaleGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrailDifficultyScaleGraphStorage.java index 1a8c14d91c..5d6a6e084c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrailDifficultyScaleGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/TrailDifficultyScaleGraphStorage.java @@ -1,123 +1,127 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; public class TrailDifficultyScaleGraphStorage implements GraphExtension { - protected final int efDifficultyScale; - - protected DataAccess edges; - protected int edgeEntryIndex = 0; - protected int edgeEntryBytes; - protected int edgesCount; - private final byte[] byteValues; - - public TrailDifficultyScaleGraphStorage() { - efDifficultyScale = nextBlockEntryIndex (2); - - edgeEntryBytes = edgeEntryIndex; - edgesCount = 0; - byteValues = new byte[2]; - } - - public void init(Graph graph, Directory dir) { - if (edgesCount > 0) - throw new AssertionError("The ext_traildifficulty storage must be initialized only once."); - - this.edges = dir.find("ext_traildifficulty"); - } - - protected final int nextBlockEntryIndex(int size) { - int res = edgeEntryIndex; - edgeEntryIndex += size; - return res; - } - - public void setSegmentSize(int bytes) { - edges.setSegmentSize(bytes); - } - - public TrailDifficultyScaleGraphStorage create(long initBytes) { - edges.create(initBytes * edgeEntryBytes); - return this; - } - - @Override - public long getCapacity() { - return edges.getCapacity(); - } - public void flush() { - edges.setHeader(0, edgeEntryBytes); - edges.setHeader(4, edgesCount); - edges.flush(); - } - - public void close() { - edges.close(); - } - - public int entries() { - return edgesCount; - } - - public boolean loadExisting() { - if (!edges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_traildifficulty'. corrupt file or directory? "); - - edgeEntryBytes = edges.getHeader(0); - edgesCount = edges.getHeader(4); - return true; - } - - void ensureEdgesIndex(int edgeIndex) { - edges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); - } - - public void setEdgeValue(int edgeId, int sacScale, int mtbScale, int mtbUphillScale) { - edgesCount++; - ensureEdgesIndex(edgeId); - - long edgePointer = (long) edgeId * edgeEntryBytes; - - byteValues[0] = (byte)sacScale; - byteValues[1] = (byte)(mtbScale << 4 | (0x0F & mtbUphillScale)); - - edges.setBytes(edgePointer + efDifficultyScale, byteValues, 2); - } - - public int getHikingScale(int edgeId, byte[] buffer) { - long edgeBase = (long) edgeId * edgeEntryBytes; - - edges.getBytes(edgeBase + efDifficultyScale, buffer, 1); - - return buffer[0]; - } - - public int getMtbScale(int edgeId, byte[] buffer, boolean uphill) { - long edgeBase = (long) edgeId * edgeEntryBytes; - - edges.getBytes(edgeBase + efDifficultyScale + 1, buffer, 1); - - if (uphill) - return (byte)(buffer[0] & 0x0F); - else - return (byte)((buffer[0] >> 4) & (byte) 0x0F); - } - - @Override - public boolean isClosed() { - return false; - } + protected final int efDifficultyScale; + + protected DataAccess edges; + protected int edgeEntryIndex = 0; + protected int edgeEntryBytes; + protected int edgesCount; + private final byte[] byteValues; + + public TrailDifficultyScaleGraphStorage() { + efDifficultyScale = nextBlockEntryIndex(2); + + edgeEntryBytes = edgeEntryIndex; + edgesCount = 0; + byteValues = new byte[2]; + } + + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ext_traildifficulty storage must be initialized only once."); + + this.edges = dir.find("ext_traildifficulty"); + } + + protected final int nextBlockEntryIndex(int size) { + int res = edgeEntryIndex; + edgeEntryIndex += size; + return res; + } + + public void setSegmentSize(int bytes) { + edges.setSegmentSize(bytes); + } + + public TrailDifficultyScaleGraphStorage create(long initBytes) { + edges.create(initBytes * edgeEntryBytes); + return this; + } + + @Override + public long getCapacity() { + return edges.getCapacity(); + } + + public void flush() { + edges.setHeader(0, edgeEntryBytes); + edges.setHeader(4, edgesCount); + edges.flush(); + } + + public void close() { + edges.close(); + } + + public int entries() { + return edgesCount; + } + + public boolean loadExisting() { + if (!edges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_traildifficulty'. corrupt file or directory? "); + + edgeEntryBytes = edges.getHeader(0); + edgesCount = edges.getHeader(4); + return true; + } + + void ensureEdgesIndex(int edgeIndex) { + edges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); + } + + public void setEdgeValue(int edgeId, int sacScale, int mtbScale, int mtbUphillScale) { + edgesCount++; + ensureEdgesIndex(edgeId); + + long edgePointer = (long) edgeId * edgeEntryBytes; + + byteValues[0] = (byte) sacScale; + byteValues[1] = (byte) (mtbScale << 4 | (0x0F & mtbUphillScale)); + + edges.setBytes(edgePointer + efDifficultyScale, byteValues, 2); + } + + public int getHikingScale(int edgeId, byte[] buffer) { + long edgeBase = (long) edgeId * edgeEntryBytes; + + edges.getBytes(edgeBase + efDifficultyScale, buffer, 1); + + return buffer[0]; + } + + public int getMtbScale(int edgeId, byte[] buffer, boolean uphill) { + long edgeBase = (long) edgeId * edgeEntryBytes; + + edges.getBytes(edgeBase + efDifficultyScale + 1, buffer, 1); + + if (uphill) + return (byte) (buffer[0] & 0x0F); + else + return (byte) ((buffer[0] >> 4) & (byte) 0x0F); + } + + @Override + public boolean isClosed() { + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WarningGraphExtension.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WarningGraphExtension.java index 2423d9ce30..4c400c316c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WarningGraphExtension.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WarningGraphExtension.java @@ -23,15 +23,19 @@ */ public interface WarningGraphExtension { void setIsUsedForWarning(boolean isWarning); + boolean isUsedForWarning(); + String getName(); /** * Method that determines whether a warning should be generated for the graph storage. - * @param extra The {@link RouteExtraInfo} object for the route for this particular extension. It's values - * should be used for determining whether a warning should be made. - * @return Whether there should be a warning generated + * + * @param extra The {@link RouteExtraInfo} object for the route for this particular extension. It's values + * should be used for determining whether a warning should be made. + * @return Whether there should be a warning generated */ boolean generatesWarning(RouteExtraInfo extra); + RouteWarning getWarning(); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WayCategoryGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WayCategoryGraphStorage.java index cb88e04fc3..8f137c7e2f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WayCategoryGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WayCategoryGraphStorage.java @@ -1,107 +1,110 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; public class WayCategoryGraphStorage implements GraphExtension { - /* pointer for no entry */ - protected final int efWaytype; - - protected DataAccess orsEdges; - protected int edgeEntryIndex = 0; - protected int edgeEntryBytes; - protected int edgesCount; // number of edges with custom values - - public WayCategoryGraphStorage() { - efWaytype = 0; - - edgeEntryBytes = edgeEntryIndex + 1; - edgesCount = 0; - } - - public void init(Graph graph, Directory dir) { - if (edgesCount > 0) - throw new AssertionError("The ORS storage must be initialized only once."); - - this.orsEdges = dir.find("ext_waycategory"); - } - - public void setSegmentSize(int bytes) { - orsEdges.setSegmentSize(bytes); - } - - public WayCategoryGraphStorage create(long initBytes) { - orsEdges.create(initBytes * edgeEntryBytes); - return this; - } - - public void flush() { - orsEdges.setHeader(0, edgeEntryBytes); - orsEdges.setHeader(4, edgesCount); - orsEdges.flush(); - } - - public void close() { - orsEdges.close(); - } - - @Override - public long getCapacity() { - return orsEdges.getCapacity(); - } - - public int entries() { - return edgesCount; - } - - public boolean loadExisting() { - if (!orsEdges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_waycategory'. corrupt file or directory? " ); - - edgeEntryBytes = orsEdges.getHeader(0); - edgesCount = orsEdges.getHeader(4); - return true; - } - - void ensureEdgesIndex(int edgeIndex) { - orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); - } - - public void setEdgeValue(int edgeId, int wayType) { - edgesCount++; - ensureEdgesIndex(edgeId); - - // add entry - long edgePointer = (long) edgeId * edgeEntryBytes; - byte byteValue = (byte) wayType; - orsEdges.setByte(edgePointer + efWaytype, byteValue); - } - - public int getEdgeValue(int edgeId, byte[] buffer) { - long edgePointer = (long) edgeId * edgeEntryBytes; - byte byteValue = orsEdges.getByte(edgePointer + efWaytype); - - int result = byteValue; - if (result < 0) - result = result & 0xff; - - return result; - } - - @Override - public boolean isClosed() { - return false; - } + /* pointer for no entry */ + protected final int efWaytype; + + protected DataAccess orsEdges; + protected int edgeEntryIndex = 0; + protected int edgeEntryBytes; + protected int edgesCount; // number of edges with custom values + + public WayCategoryGraphStorage() { + efWaytype = 0; + + edgeEntryBytes = edgeEntryIndex + 1; + edgesCount = 0; + } + + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ORS storage must be initialized only once."); + + this.orsEdges = dir.find("ext_waycategory"); + } + + public void setSegmentSize(int bytes) { + orsEdges.setSegmentSize(bytes); + } + + public WayCategoryGraphStorage create(long initBytes) { + orsEdges.create(initBytes * edgeEntryBytes); + return this; + } + + public void flush() { + orsEdges.setHeader(0, edgeEntryBytes); + orsEdges.setHeader(4, edgesCount); + orsEdges.flush(); + } + + public void close() { + orsEdges.close(); + } + + @Override + public long getCapacity() { + return orsEdges.getCapacity(); + } + + public int entries() { + return edgesCount; + } + + public boolean loadExisting() { + if (!orsEdges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_waycategory'. corrupt file or directory? "); + + edgeEntryBytes = orsEdges.getHeader(0); + edgesCount = orsEdges.getHeader(4); + return true; + } + + void ensureEdgesIndex(int edgeIndex) { + orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); + } + + public void setEdgeValue(int edgeId, int wayType) { + edgesCount++; + ensureEdgesIndex(edgeId); + + // add entry + long edgePointer = (long) edgeId * edgeEntryBytes; + byte byteValue = (byte) wayType; + orsEdges.setByte(edgePointer + efWaytype, byteValue); + } + + public int getEdgeValue(int edgeId, byte[] buffer) { + long edgePointer = (long) edgeId * edgeEntryBytes; + byte byteValue = orsEdges.getByte(edgePointer + efWaytype); + + int result = byteValue; + if (result < 0) + result = result & 0xff; + + return result; + } + + @Override + public boolean isClosed() { + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WaySurfaceTypeGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WaySurfaceTypeGraphStorage.java index fbba50aea5..1eea3659d5 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WaySurfaceTypeGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WaySurfaceTypeGraphStorage.java @@ -1,117 +1,121 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; import org.heigit.ors.routing.util.WaySurfaceDescription; public class WaySurfaceTypeGraphStorage implements GraphExtension { - /* pointer for no entry */ - protected final int efWaytype; - - protected DataAccess orsEdges; - protected int edgeEntryIndex = 0; - protected int edgeEntryBytes; - protected int edgesCount; // number of edges with custom values - - private final byte[] byteValues; - - public WaySurfaceTypeGraphStorage() { - efWaytype = 0; - - edgeEntryBytes = edgeEntryIndex + 1; - edgesCount = 0; - byteValues = new byte[10]; - } - - public void init(Graph graph, Directory dir ) { - if (edgesCount > 0) - throw new AssertionError("The ORS storage must be initialized only once."); - - this.orsEdges = dir.find("ext_waysurface"); - } - - protected final int nextBlockEntryIndex(int size) { - edgeEntryIndex += size; - return edgeEntryIndex; - } - - public void setSegmentSize(int bytes) { - orsEdges.setSegmentSize(bytes); - } - - public WaySurfaceTypeGraphStorage create(long initBytes) { - orsEdges.create(initBytes * edgeEntryBytes); - return this; - } - - public void flush() { - orsEdges.setHeader(0, edgeEntryBytes); - orsEdges.setHeader(4, edgesCount); - orsEdges.flush(); - } - - public void close() { - orsEdges.close(); - } - - @Override - public long getCapacity() { - return orsEdges.getCapacity(); - } - public int entries() { - return edgesCount; - } - - public boolean loadExisting() { - if (!orsEdges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_waysurface'. corrupt file or directory? "); - - edgeEntryBytes = orsEdges.getHeader(0); - edgesCount = orsEdges.getHeader(4); - return true; - } - - void ensureEdgesIndex(int edgeIndex) { - orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); - } - - public void setEdgeValue(int edgeId, WaySurfaceDescription wayDesc) { - edgesCount++; - ensureEdgesIndex(edgeId); - - // add entry - long edgePointer = (long) edgeId * edgeEntryBytes; - byteValues[0] = (byte)((wayDesc.getWayType() << 4) | wayDesc.getSurfaceType() & 0xff); - orsEdges.setBytes(edgePointer + efWaytype, byteValues, 1); - } - - - public WaySurfaceDescription getEdgeValue(int edgeId, byte[] buffer) { - long edgePointer = (long) edgeId * edgeEntryBytes; - orsEdges.getBytes(edgePointer + efWaytype, buffer, 1); - - byte compValue = buffer[0]; - WaySurfaceDescription res = new WaySurfaceDescription(); - res.setWayType((compValue & 0b11110000) >> 4); - res.setSurfaceType(compValue & 0b00001111); - - return res; - } - - @Override - public boolean isClosed() { - return false; - } + /* pointer for no entry */ + protected final int efWaytype; + + protected DataAccess orsEdges; + protected int edgeEntryIndex = 0; + protected int edgeEntryBytes; + protected int edgesCount; // number of edges with custom values + + private final byte[] byteValues; + + public WaySurfaceTypeGraphStorage() { + efWaytype = 0; + + edgeEntryBytes = edgeEntryIndex + 1; + edgesCount = 0; + byteValues = new byte[10]; + } + + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ORS storage must be initialized only once."); + + this.orsEdges = dir.find("ext_waysurface"); + } + + protected final int nextBlockEntryIndex(int size) { + edgeEntryIndex += size; + return edgeEntryIndex; + } + + public void setSegmentSize(int bytes) { + orsEdges.setSegmentSize(bytes); + } + + public WaySurfaceTypeGraphStorage create(long initBytes) { + orsEdges.create(initBytes * edgeEntryBytes); + return this; + } + + public void flush() { + orsEdges.setHeader(0, edgeEntryBytes); + orsEdges.setHeader(4, edgesCount); + orsEdges.flush(); + } + + public void close() { + orsEdges.close(); + } + + @Override + public long getCapacity() { + return orsEdges.getCapacity(); + } + + public int entries() { + return edgesCount; + } + + public boolean loadExisting() { + if (!orsEdges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_waysurface'. corrupt file or directory? "); + + edgeEntryBytes = orsEdges.getHeader(0); + edgesCount = orsEdges.getHeader(4); + return true; + } + + void ensureEdgesIndex(int edgeIndex) { + orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); + } + + public void setEdgeValue(int edgeId, WaySurfaceDescription wayDesc) { + edgesCount++; + ensureEdgesIndex(edgeId); + + // add entry + long edgePointer = (long) edgeId * edgeEntryBytes; + byteValues[0] = (byte) ((wayDesc.getWayType() << 4) | wayDesc.getSurfaceType() & 0xff); + orsEdges.setBytes(edgePointer + efWaytype, byteValues, 1); + } + + + public WaySurfaceDescription getEdgeValue(int edgeId, byte[] buffer) { + long edgePointer = (long) edgeId * edgeEntryBytes; + orsEdges.getBytes(edgePointer + efWaytype, buffer, 1); + + byte compValue = buffer[0]; + WaySurfaceDescription res = new WaySurfaceDescription(); + res.setWayType((compValue & 0b11110000) >> 4); + res.setSurfaceType(compValue & 0b00001111); + + return res; + } + + @Override + public boolean isClosed() { + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WheelchairAttributesGraphStorage.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WheelchairAttributesGraphStorage.java index d84ce8e35f..e115d7abd8 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WheelchairAttributesGraphStorage.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/WheelchairAttributesGraphStorage.java @@ -13,289 +13,292 @@ */ package org.heigit.ors.routing.graphhopper.extensions.storages; -import com.graphhopper.storage.*; +import com.graphhopper.storage.DataAccess; +import com.graphhopper.storage.Directory; +import com.graphhopper.storage.Graph; +import com.graphhopper.storage.GraphExtension; import org.heigit.ors.routing.graphhopper.extensions.WheelchairAttributes; import org.heigit.ors.routing.graphhopper.extensions.flagencoders.EncodedValueOld; public class WheelchairAttributesGraphStorage implements GraphExtension { - protected static final int WIDTH_MAX_VALUE = 300; - protected static final int KERB_MAX_VALUE = 15; - protected static final int INCLINE_MAX_VALUE = 30; - protected static final int TRACK_TYPE_MAX_VALUE = 5; - protected static final int SMOOTHNESS_MAX_VALUE = 8; - protected static final int SURFACE_MAX_VALUE = 30; + protected static final int WIDTH_MAX_VALUE = 300; + protected static final int KERB_MAX_VALUE = 15; + protected static final int INCLINE_MAX_VALUE = 30; + protected static final int TRACK_TYPE_MAX_VALUE = 5; + protected static final int SMOOTHNESS_MAX_VALUE = 8; + protected static final int SURFACE_MAX_VALUE = 30; - /* pointer for no entry */ - protected final int efWheelchairAttributes; + /* pointer for no entry */ + protected final int efWheelchairAttributes; - protected DataAccess orsEdges; - protected int edgeEntryIndex = 0; - protected int edgeEntryBytes; - protected int edgesCount; // number of edges with custom values + protected DataAccess orsEdges; + protected int edgeEntryIndex = 0; + protected int edgeEntryBytes; + protected int edgesCount; // number of edges with custom values - private final byte[] buffer; + private final byte[] buffer; - // bit encoders - private final EncodedValueOld surfaceEncoder; - private final EncodedValueOld smoothnessEncoder; - private final EncodedValueOld trackTypeEncoder; - private final EncodedValueOld sideFlagEncoder; - private final EncodedValueOld kerbHeightEncoder; - private final EncodedValueOld hasKerbHeightEncoder; - private final EncodedValueOld inclineEncoder; - private final EncodedValueOld hasInclineEncoder; - private final EncodedValueOld widthEncoder; - private final EncodedValueOld surfaceQualityKnownEncoder; - private final EncodedValueOld pedestrianisedEncoder; + // bit encoders + private final EncodedValueOld surfaceEncoder; + private final EncodedValueOld smoothnessEncoder; + private final EncodedValueOld trackTypeEncoder; + private final EncodedValueOld sideFlagEncoder; + private final EncodedValueOld kerbHeightEncoder; + private final EncodedValueOld hasKerbHeightEncoder; + private final EncodedValueOld inclineEncoder; + private final EncodedValueOld hasInclineEncoder; + private final EncodedValueOld widthEncoder; + private final EncodedValueOld surfaceQualityKnownEncoder; + private final EncodedValueOld pedestrianisedEncoder; - public static final int BYTE_COUNT = 5; + public static final int BYTE_COUNT = 5; - public WheelchairAttributesGraphStorage() { - buffer = new byte[BYTE_COUNT]; - efWheelchairAttributes = 0; + public WheelchairAttributesGraphStorage() { + buffer = new byte[BYTE_COUNT]; + efWheelchairAttributes = 0; - edgeEntryBytes = edgeEntryIndex + BYTE_COUNT; - edgesCount = 0; + edgeEntryBytes = edgeEntryIndex + BYTE_COUNT; + edgesCount = 0; - int shift = 1; - surfaceEncoder = new EncodedValueOld("surface", shift, 5, 1, 0, SURFACE_MAX_VALUE); - shift += surfaceEncoder.getBits(); + int shift = 1; + surfaceEncoder = new EncodedValueOld("surface", shift, 5, 1, 0, SURFACE_MAX_VALUE); + shift += surfaceEncoder.getBits(); - smoothnessEncoder = new EncodedValueOld("smoothness", shift, 4, 1, 0, SMOOTHNESS_MAX_VALUE); - shift += smoothnessEncoder.getBits(); + smoothnessEncoder = new EncodedValueOld("smoothness", shift, 4, 1, 0, SMOOTHNESS_MAX_VALUE); + shift += smoothnessEncoder.getBits(); - trackTypeEncoder = new EncodedValueOld("tracktype", shift, 3, 1, 0, TRACK_TYPE_MAX_VALUE); - shift += trackTypeEncoder.getBits(); + trackTypeEncoder = new EncodedValueOld("tracktype", shift, 3, 1, 0, TRACK_TYPE_MAX_VALUE); + shift += trackTypeEncoder.getBits(); - inclineEncoder = new EncodedValueOld("incline", shift, 5, 1, 0, INCLINE_MAX_VALUE); - shift += inclineEncoder.getBits(); + inclineEncoder = new EncodedValueOld("incline", shift, 5, 1, 0, INCLINE_MAX_VALUE); + shift += inclineEncoder.getBits(); - kerbHeightEncoder = new EncodedValueOld("kerbHeight", shift, 4, 1, 0, KERB_MAX_VALUE); - shift += kerbHeightEncoder.getBits(); + kerbHeightEncoder = new EncodedValueOld("kerbHeight", shift, 4, 1, 0, KERB_MAX_VALUE); + shift += kerbHeightEncoder.getBits(); - widthEncoder = new EncodedValueOld("width", shift, 5, 10, 0, WIDTH_MAX_VALUE); - shift += widthEncoder.getBits(); + widthEncoder = new EncodedValueOld("width", shift, 5, 10, 0, WIDTH_MAX_VALUE); + shift += widthEncoder.getBits(); - sideFlagEncoder = new EncodedValueOld("side", shift, 2, 1,0,2); - shift += sideFlagEncoder.getBits(); + sideFlagEncoder = new EncodedValueOld("side", shift, 2, 1, 0, 2); + shift += sideFlagEncoder.getBits(); - hasKerbHeightEncoder = new EncodedValueOld("hasKerbHeight", shift, 1, 1, 0, 1); - shift += 1; + hasKerbHeightEncoder = new EncodedValueOld("hasKerbHeight", shift, 1, 1, 0, 1); + shift += 1; - hasInclineEncoder = new EncodedValueOld("hasIncline", shift, 1, 1, 0, 1); - shift += 1; + hasInclineEncoder = new EncodedValueOld("hasIncline", shift, 1, 1, 0, 1); + shift += 1; - surfaceQualityKnownEncoder = new EncodedValueOld("surfaceQualityKnown", shift, 1, 1, 0, 1); - shift += 1; + surfaceQualityKnownEncoder = new EncodedValueOld("surfaceQualityKnown", shift, 1, 1, 0, 1); + shift += 1; - pedestrianisedEncoder = new EncodedValueOld("pedestrianised", shift, 1, 1, 0, 1); + pedestrianisedEncoder = new EncodedValueOld("pedestrianised", shift, 1, 1, 0, 1); - } + } - public void init(Graph graph, Directory dir) { - if (edgesCount > 0) - throw new AssertionError("The ORS storage must be initialized only once."); + public void init(Graph graph, Directory dir) { + if (edgesCount > 0) + throw new AssertionError("The ORS storage must be initialized only once."); - this.orsEdges = dir.find("ext_wheelchair"); - } + this.orsEdges = dir.find("ext_wheelchair"); + } - public WheelchairAttributesGraphStorage create(long initBytes) { - orsEdges.create(initBytes * edgeEntryBytes); - return this; - } + public WheelchairAttributesGraphStorage create(long initBytes) { + orsEdges.create(initBytes * edgeEntryBytes); + return this; + } - public void flush() { - orsEdges.setHeader(0, edgeEntryBytes); - orsEdges.setHeader(4, edgesCount); - orsEdges.flush(); - } - - public void close() { - orsEdges.close(); - } - - @Override - public long getCapacity() { - return orsEdges.getCapacity(); - } + public void flush() { + orsEdges.setHeader(0, edgeEntryBytes); + orsEdges.setHeader(4, edgesCount); + orsEdges.flush(); + } + + public void close() { + orsEdges.close(); + } + + @Override + public long getCapacity() { + return orsEdges.getCapacity(); + } - public int entries() { - return edgesCount; - } + public int entries() { + return edgesCount; + } - public boolean loadExisting() { - if (!orsEdges.loadExisting()) - throw new IllegalStateException("Unable to load storage 'ext_wheelchair'. corrupt file or directory? " ); + public boolean loadExisting() { + if (!orsEdges.loadExisting()) + throw new IllegalStateException("Unable to load storage 'ext_wheelchair'. corrupt file or directory? "); - edgeEntryBytes = orsEdges.getHeader(0); - edgesCount = orsEdges.getHeader(4); - return true; - } + edgeEntryBytes = orsEdges.getHeader(0); + edgesCount = orsEdges.getHeader(4); + return true; + } - void ensureEdgesIndex(int edgeIndex) { - orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); - } - - public void setEdgeValues(int edgeId, WheelchairAttributes attrs) { + void ensureEdgesIndex(int edgeIndex) { + orsEdges.ensureCapacity(((long) edgeIndex + 1) * edgeEntryBytes); + } + + public void setEdgeValues(int edgeId, WheelchairAttributes attrs) { - edgesCount++; - ensureEdgesIndex(edgeId); + edgesCount++; + ensureEdgesIndex(edgeId); - long edgePointer = (long) edgeId * edgeEntryBytes; + long edgePointer = (long) edgeId * edgeEntryBytes; - encodeAttributes(attrs, buffer); + encodeAttributes(attrs, buffer); - orsEdges.setBytes(edgePointer + efWheelchairAttributes, buffer, BYTE_COUNT); + orsEdges.setBytes(edgePointer + efWheelchairAttributes, buffer, BYTE_COUNT); - } + } - private void encodeAttributes(WheelchairAttributes attrs, byte[] buffer) { - /* - * | flag | surface | smoothness | tracktype | incline | kerbHeight | width | side | hasKerbHeight | hasIncline | surfaceQualityKnown | pedestrianised - * lsb-> | 1 bit | 5 bits | 4 bits | 3 bits | 5 bits | 4 bits | 5 bits | 2 bit | 1 bit | 1 bit | 1 bit | 1 bit | 33 bits in total which can fit into 5 bytes - * - * - */ - - if (attrs.hasValues()) { - long encodedValue = 0; - // set first bit to 1 to mark that we have wheelchair specific attributes for this edge - encodedValue |= (1L); - if (attrs.getSurfaceType() > 0) - encodedValue = surfaceEncoder.setValue(encodedValue, attrs.getSurfaceType()); - - if (attrs.getSmoothnessType() > 0) - encodedValue = smoothnessEncoder.setValue(encodedValue, attrs.getSmoothnessType()); - - if (attrs.getTrackType() > 0) - encodedValue = trackTypeEncoder.setValue(encodedValue, attrs.getTrackType()); - - if (attrs.getIncline() > -1) { - encodedValue = hasInclineEncoder.setValue(encodedValue, 1); - encodedValue = inclineEncoder.setValue(encodedValue, attrs.getIncline()); - } - - if (attrs.getSlopedKerbHeight() > 0.0) { - encodedValue = hasKerbHeightEncoder.setValue(encodedValue, 1); - encodedValue = kerbHeightEncoder.setValue(encodedValue, attrs.getSlopedKerbHeight()); - } - - if (attrs.getWidth() > 0.0) - encodedValue = widthEncoder.setValue(encodedValue, attrs.getWidth()); - - switch (attrs.getSide()) { - case LEFT -> encodedValue = sideFlagEncoder.setValue(encodedValue, 1); - case RIGHT -> encodedValue = sideFlagEncoder.setValue(encodedValue, 2); - default -> { - } - } - - if (attrs.isSurfaceQualityKnown()) { - encodedValue = surfaceQualityKnownEncoder.setValue(encodedValue, 1); - } - - if (attrs.isSuitable()) { - encodedValue = pedestrianisedEncoder.setValue(encodedValue, 1); - } - - buffer[4] = (byte) ((encodedValue >> 32) & 0xFF); - buffer[3] = (byte) ((encodedValue >> 24) & 0xFF); - buffer[2] = (byte) ((encodedValue >> 16) & 0xFF); - buffer[1] = (byte) ((encodedValue >> 8) & 0xFF); - buffer[0] = (byte) ((encodedValue) & 0xFF); - } else { - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0; - buffer[3] = 0; - buffer[4] = 0; - } - } - - private void decodeAttributes(WheelchairAttributes attrs, byte[] buffer) { - attrs.reset(); - - if (buffer[0] == 0) - return; - - long encodedValue = (long) buffer[0] & 0xFF; - encodedValue |= (long) (buffer[1] & 0xFF) << 8; - encodedValue |= (long) (buffer[2] & 0xFF) << 16; - encodedValue |= (long) (buffer[3] & 0xFF) << 24; - encodedValue |= (long) (buffer[4] & 0xFF) << 32; - - if ((1 & encodedValue) != 0) { - long iValue = surfaceEncoder.getValue(encodedValue); - if (iValue != 0) - attrs.setSurfaceType((int) iValue); - - iValue = smoothnessEncoder.getValue(encodedValue); - if (iValue != 0) - attrs.setSmoothnessType((int) iValue); - - iValue = trackTypeEncoder.getValue(encodedValue); - if (iValue != 0) - attrs.setTrackType((int) iValue); - - long hasIncline = hasInclineEncoder.getValue(encodedValue); - if (hasIncline > 0) { - iValue = inclineEncoder.getValue(encodedValue); - attrs.setIncline((int) (iValue)); - } - - long hasKerbHeight = hasKerbHeightEncoder.getValue(encodedValue); - if (hasKerbHeight > 0) { - iValue = kerbHeightEncoder.getValue(encodedValue); - attrs.setSlopedKerbHeight((int) (iValue)); - } - - iValue = widthEncoder.getValue(encodedValue); - if (iValue != 0) - attrs.setWidth((int) (iValue)); - - iValue = sideFlagEncoder.getValue(encodedValue); - switch ((int) iValue) { - case 1 -> attrs.setSide(WheelchairAttributes.Side.LEFT); - case 2 -> attrs.setSide(WheelchairAttributes.Side.RIGHT); - default -> attrs.setSide(WheelchairAttributes.Side.UNKNOWN); - } - - iValue = surfaceQualityKnownEncoder.getValue(encodedValue); - attrs.setSurfaceQualityKnown((iValue != 0)); - - iValue = pedestrianisedEncoder.getValue(encodedValue); - attrs.setSuitable((iValue != 0)); - } - } - - public void getEdgeValues(int edgeId, WheelchairAttributes attrs, byte[] buffer) { - long edgePointer = (long) edgeId * (long) edgeEntryBytes; - orsEdges.getBytes(edgePointer + efWheelchairAttributes, buffer, BYTE_COUNT); - decodeAttributes(attrs, buffer); - } - - public boolean isRequireNodeField() { - return false; - } - - public boolean isRequireEdgeField() { - // we require the additional field in the graph to point to the first - // entry in the node table - return true; - } - - public int getDefaultNodeFieldValue() { - throw new UnsupportedOperationException("Not supported by this storage"); - } - - public int getDefaultEdgeFieldValue() { - return -1; - } - - @Override - public boolean isClosed() { - return false; - } + private void encodeAttributes(WheelchairAttributes attrs, byte[] buffer) { + /* + * | flag | surface | smoothness | tracktype | incline | kerbHeight | width | side | hasKerbHeight | hasIncline | surfaceQualityKnown | pedestrianised + * lsb-> | 1 bit | 5 bits | 4 bits | 3 bits | 5 bits | 4 bits | 5 bits | 2 bit | 1 bit | 1 bit | 1 bit | 1 bit | 33 bits in total which can fit into 5 bytes + * + * + */ + + if (attrs.hasValues()) { + long encodedValue = 0; + // set first bit to 1 to mark that we have wheelchair specific attributes for this edge + encodedValue |= (1L); + if (attrs.getSurfaceType() > 0) + encodedValue = surfaceEncoder.setValue(encodedValue, attrs.getSurfaceType()); + + if (attrs.getSmoothnessType() > 0) + encodedValue = smoothnessEncoder.setValue(encodedValue, attrs.getSmoothnessType()); + + if (attrs.getTrackType() > 0) + encodedValue = trackTypeEncoder.setValue(encodedValue, attrs.getTrackType()); + + if (attrs.getIncline() > -1) { + encodedValue = hasInclineEncoder.setValue(encodedValue, 1); + encodedValue = inclineEncoder.setValue(encodedValue, attrs.getIncline()); + } + + if (attrs.getSlopedKerbHeight() > 0.0) { + encodedValue = hasKerbHeightEncoder.setValue(encodedValue, 1); + encodedValue = kerbHeightEncoder.setValue(encodedValue, attrs.getSlopedKerbHeight()); + } + + if (attrs.getWidth() > 0.0) + encodedValue = widthEncoder.setValue(encodedValue, attrs.getWidth()); + + switch (attrs.getSide()) { + case LEFT -> encodedValue = sideFlagEncoder.setValue(encodedValue, 1); + case RIGHT -> encodedValue = sideFlagEncoder.setValue(encodedValue, 2); + default -> { + } + } + + if (attrs.isSurfaceQualityKnown()) { + encodedValue = surfaceQualityKnownEncoder.setValue(encodedValue, 1); + } + + if (attrs.isSuitable()) { + encodedValue = pedestrianisedEncoder.setValue(encodedValue, 1); + } + + buffer[4] = (byte) ((encodedValue >> 32) & 0xFF); + buffer[3] = (byte) ((encodedValue >> 24) & 0xFF); + buffer[2] = (byte) ((encodedValue >> 16) & 0xFF); + buffer[1] = (byte) ((encodedValue >> 8) & 0xFF); + buffer[0] = (byte) ((encodedValue) & 0xFF); + } else { + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + buffer[4] = 0; + } + } + + private void decodeAttributes(WheelchairAttributes attrs, byte[] buffer) { + attrs.reset(); + + if (buffer[0] == 0) + return; + + long encodedValue = (long) buffer[0] & 0xFF; + encodedValue |= (long) (buffer[1] & 0xFF) << 8; + encodedValue |= (long) (buffer[2] & 0xFF) << 16; + encodedValue |= (long) (buffer[3] & 0xFF) << 24; + encodedValue |= (long) (buffer[4] & 0xFF) << 32; + + if ((1 & encodedValue) != 0) { + long iValue = surfaceEncoder.getValue(encodedValue); + if (iValue != 0) + attrs.setSurfaceType((int) iValue); + + iValue = smoothnessEncoder.getValue(encodedValue); + if (iValue != 0) + attrs.setSmoothnessType((int) iValue); + + iValue = trackTypeEncoder.getValue(encodedValue); + if (iValue != 0) + attrs.setTrackType((int) iValue); + + long hasIncline = hasInclineEncoder.getValue(encodedValue); + if (hasIncline > 0) { + iValue = inclineEncoder.getValue(encodedValue); + attrs.setIncline((int) (iValue)); + } + + long hasKerbHeight = hasKerbHeightEncoder.getValue(encodedValue); + if (hasKerbHeight > 0) { + iValue = kerbHeightEncoder.getValue(encodedValue); + attrs.setSlopedKerbHeight((int) (iValue)); + } + + iValue = widthEncoder.getValue(encodedValue); + if (iValue != 0) + attrs.setWidth((int) (iValue)); + + iValue = sideFlagEncoder.getValue(encodedValue); + switch ((int) iValue) { + case 1 -> attrs.setSide(WheelchairAttributes.Side.LEFT); + case 2 -> attrs.setSide(WheelchairAttributes.Side.RIGHT); + default -> attrs.setSide(WheelchairAttributes.Side.UNKNOWN); + } + + iValue = surfaceQualityKnownEncoder.getValue(encodedValue); + attrs.setSurfaceQualityKnown((iValue != 0)); + + iValue = pedestrianisedEncoder.getValue(encodedValue); + attrs.setSuitable((iValue != 0)); + } + } + + public void getEdgeValues(int edgeId, WheelchairAttributes attrs, byte[] buffer) { + long edgePointer = (long) edgeId * (long) edgeEntryBytes; + orsEdges.getBytes(edgePointer + efWheelchairAttributes, buffer, BYTE_COUNT); + decodeAttributes(attrs, buffer); + } + + public boolean isRequireNodeField() { + return false; + } + + public boolean isRequireEdgeField() { + // we require the additional field in the graph to point to the first + // entry in the node table + return true; + } + + public int getDefaultNodeFieldValue() { + throw new UnsupportedOperationException("Not supported by this storage"); + } + + public int getDefaultEdgeFieldValue() { + return -1; + } + + @Override + public boolean isClosed() { + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/AbstractGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/AbstractGraphStorageBuilder.java index cbfff4d1b5..714c6f0510 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/AbstractGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/AbstractGraphStorageBuilder.java @@ -19,23 +19,22 @@ import java.util.Map; -public abstract class AbstractGraphStorageBuilder implements GraphStorageBuilder -{ - protected Map parameters; +public abstract class AbstractGraphStorageBuilder implements GraphStorageBuilder { + protected Map parameters; - public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) { - processWay(way); - } + public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) { + processWay(way); + } - public void processEdge(ReaderWay way, EdgeIteratorState edge, Coordinate[] coords) { - processEdge(way, edge); - } + public void processEdge(ReaderWay way, EdgeIteratorState edge, Coordinate[] coords) { + processEdge(way, edge); + } - public void setParameters(Map parameters) { - this.parameters = parameters; - } + public void setParameters(Map parameters) { + this.parameters = parameters; + } - public void finish(){ - // Do nothing by default - } + public void finish() { + // Do nothing by default + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilder.java index 752c3f2399..e2bbf5747b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilder.java @@ -17,14 +17,14 @@ import com.graphhopper.reader.ReaderWay; import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.GeometryFactory; -import org.locationtech.jts.geom.LineString; import org.apache.log4j.Logger; import org.heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersPolygon; import org.heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersReader; import org.heigit.ors.routing.graphhopper.extensions.storages.BordersGraphStorage; import org.heigit.ors.util.ErrorLoggingUtility; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.GeometryFactory; +import org.locationtech.jts.geom.LineString; import java.util.ArrayList; import java.util.Map; @@ -68,14 +68,14 @@ public GraphExtension init(GraphHopper graphhopper) throws Exception { if (storage != null) throw new Exception("GraphStorageBuilder has been already initialized."); - if(this.cbReader == null) { + if (this.cbReader == null) { // Read the border shapes from the file // First check if parameters are present String bordersFile = ""; String countryIdsFile = ""; String openBordersFile = ""; - if(parameters.containsKey(PARAM_KEY_BOUNDARIES)) + if (parameters.containsKey(PARAM_KEY_BOUNDARIES)) bordersFile = parameters.get(PARAM_KEY_BOUNDARIES); else { ErrorLoggingUtility.logMissingConfigParameter(BordersGraphStorageBuilder.class, PARAM_KEY_BOUNDARIES); @@ -83,12 +83,12 @@ public GraphExtension init(GraphHopper graphhopper) throws Exception { throw new MissingResourceException("A boundary geometry file is needed to use the borders extended storage!", BordersGraphStorage.class.getName(), PARAM_KEY_BOUNDARIES); } - if(parameters.containsKey("ids")) + if (parameters.containsKey("ids")) countryIdsFile = parameters.get("ids"); else ErrorLoggingUtility.logMissingConfigParameter(BordersGraphStorageBuilder.class, "ids"); - if(parameters.containsKey(PARAM_KEY_OPEN_BORDERS)) + if (parameters.containsKey(PARAM_KEY_OPEN_BORDERS)) openBordersFile = parameters.get(PARAM_KEY_OPEN_BORDERS); else ErrorLoggingUtility.logMissingConfigParameter(BordersGraphStorageBuilder.class, PARAM_KEY_OPEN_BORDERS); @@ -105,7 +105,7 @@ public GraphExtension init(GraphHopper graphhopper) throws Exception { /** * COverwrite the current reader with a custom built CountryBordersReader. * - * @param cbr The CountryBordersReader object to be used + * @param cbr The CountryBordersReader object to be used */ public void setBordersBuilder(CountryBordersReader cbr) { this.cbReader = cbr; @@ -124,7 +124,7 @@ public void processWay(ReaderWay way) { * @param coords */ @Override - public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) { + public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) { // Process the way using the geometry provided // if we don't have the reader object, then we can't do anything if (cbReader != null) { @@ -133,47 +133,47 @@ public void processWay(ReaderWay way, Coordinate[] coords, Map 1 && !countries[0].equals(countries[1])) { way.setTag(TAG_KEY_COUNTRY1, countries[0]); way.setTag(TAG_KEY_COUNTRY2, countries[1]); - } else if (countries.length == 1){ + } else if (countries.length == 1) { way.setTag(TAG_KEY_COUNTRY1, countries[0]); way.setTag(TAG_KEY_COUNTRY2, countries[0]); } } } - /** + /** * Method to process the edge and store it in the graph.

    *

    * It checks the way to see if it has start and end country tags (introduced in the processWay method) and then - * determines the type of border crossing (1 for controlled and 2 for open) + * determines the type of border crossing (1 for controlled and 2 for open) * * @param way The OSM way obtained from the OSM reader. This way corresponds to the edge to be processed * @param edge The graph edge to be process */ - @Override - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - // Make sure we actually have the storage initialised - if there were errors accessing the data then this could be the case - if (storage != null) { - // If there is no border crossing then we set the edge value to be 0 - - // First get the start and end countries - if they are equal, then there is no crossing - String startVal = way.getTag(TAG_KEY_COUNTRY1); - String endVal = way.getTag(TAG_KEY_COUNTRY2); - short type = BordersGraphStorage.NO_BORDER; - short start = 0; - short end = 0; - try { - start = Short.parseShort(cbReader.getId(startVal)); - end = Short.parseShort(cbReader.getId(endVal)); - } catch (Exception ignore) { - // do nothing - } finally { - if (start != end) { - type = (cbReader.isOpen(cbReader.getEngName(startVal), cbReader.getEngName(endVal))) ? (short) 2 : (short) 1; - } - storage.setEdgeValue(edge.getEdge(), type, start, end); - } - } - } + @Override + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + // Make sure we actually have the storage initialised - if there were errors accessing the data then this could be the case + if (storage != null) { + // If there is no border crossing then we set the edge value to be 0 + + // First get the start and end countries - if they are equal, then there is no crossing + String startVal = way.getTag(TAG_KEY_COUNTRY1); + String endVal = way.getTag(TAG_KEY_COUNTRY2); + short type = BordersGraphStorage.NO_BORDER; + short start = 0; + short end = 0; + try { + start = Short.parseShort(cbReader.getId(startVal)); + end = Short.parseShort(cbReader.getId(endVal)); + } catch (Exception ignore) { + // do nothing + } finally { + if (start != end) { + type = (cbReader.isOpen(cbReader.getEngName(startVal), cbReader.getEngName(endVal))) ? (short) 2 : (short) 1; + } + storage.setEdgeValue(edge.getEdge(), type, start, end); + } + } + } /** * Method identifying the name of the extension which is used in various building processes @@ -189,9 +189,9 @@ public String getName() { * Method to identify the countries that a way is found in. basically iterates over the country boundaries read from * the file adn then does geometric calculations to identify wheich country each node of the way is in. * - * @param coords Coordinates of the way - * @return An array of strings representing the countries that nodes are found in. If the way is only - * found in one country, then only one name is returned. + * @param coords Coordinates of the way + * @return An array of strings representing the countries that nodes are found in. If the way is only + * found in one country, then only one name is returned. */ public String[] findBorderCrossing(Coordinate[] coords) { @@ -202,11 +202,11 @@ public String[] findBorderCrossing(Coordinate[] coords) { // Go through the points of the linestring and check what country they are in int lsLen = coords.length; - if(lsLen > 1) { - for(int i=0; i 1) { + for (int i = 0; i < lsLen; i++) { // Make sure that it is a valid point Coordinate c = coords[i]; - if(!Double.isNaN(c.x) && !Double.isNaN(c.y)) { + if (!Double.isNaN(c.x) && !Double.isNaN(c.y)) { CountryBordersPolygon[] cnts = cbReader.getCandidateCountry(c); for (CountryBordersPolygon cbp : cnts) { // This check is for the bbox as that is quickest for detecting if there is the possibility of a @@ -218,30 +218,30 @@ public String[] findBorderCrossing(Coordinate[] coords) { // If we ended up with no candidates for the point, then we indicate that at least one point is // in international territory - if(cnts.length == 0) + if (cnts.length == 0) hasInternational = true; } } } // Now get the definite ones that are contained - though this involves another iteration, it will be quicker // than the linestring check in the next stage - if(countries.size() > 1) { + if (countries.size() > 1) { ArrayList temp = new ArrayList<>(); - for(int i=0; i 1) { + if (countriesFound > 1) { overlap = true; } - if(!found) { + if (!found) { hasInternational = true; } } @@ -267,7 +267,7 @@ public String[] findBorderCrossing(Coordinate[] coords) { // Now we have a list of all the countries that the nodes are in - if this is more than one it is likely it is // crossing a border, but not certain as in some disputed areas, countries overlap and so it may not cross any // border. - if(countries.size() > 1 && overlap) { + if (countries.size() > 1 && overlap) { boolean crosses = false; // Construct the linesting LineString ls = gf.createLineString(coords); @@ -282,7 +282,7 @@ public String[] findBorderCrossing(Coordinate[] coords) { } } - if(!crosses) { + if (!crosses) { // We want to indicate that it is in the same country, so to do that we only pass one country back CountryBordersPolygon cp = countries.get(0); countries.clear(); @@ -292,13 +292,13 @@ public String[] findBorderCrossing(Coordinate[] coords) { // Now get the names of the countries ArrayList names = new ArrayList<>(); - for(int i=0; i. + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -17,6 +17,8 @@ import com.graphhopper.reader.ReaderWay; import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; +import org.apache.log4j.Logger; +import org.heigit.ors.routing.graphhopper.extensions.storages.CsvGraphStorage; import java.io.BufferedReader; import java.io.FileReader; @@ -25,13 +27,10 @@ import java.util.HashMap; import java.util.Map; -import org.apache.log4j.Logger; -import org.heigit.ors.routing.graphhopper.extensions.storages.CsvGraphStorage; - public class CsvGraphStorageBuilder extends AbstractGraphStorageBuilder { private static final Logger LOGGER = Logger.getLogger(CsvGraphStorageBuilder.class.getName()); private CsvGraphStorage storage; - private Map id2Value = new HashMap<>(); + private final Map id2Value = new HashMap<>(); private static final int MAX_VALUE = 100; private final byte defaultValue = 0; // TODO: make configurable private String[] columnNames; @@ -63,7 +62,7 @@ private void readFromCSV(String csvFile) throws IOException { Long id = Long.parseLong(idAndTail[0].trim()); Integer[] values = Arrays.stream(idAndTail[1].split(",")) .map(String::trim) - .map(x -> (int)(Float.parseFloat(x) * 100)) + .map(x -> (int) (Float.parseFloat(x) * 100)) .toArray(Integer[]::new); id2Value.put(id, values); } @@ -80,8 +79,8 @@ public void processWay(ReaderWay way) { @Override public void processEdge(ReaderWay way, EdgeIteratorState edge) { - byte[] values = getValues(way.getId()); - storage.setEdgeValue(edge.getEdge(), values); + byte[] values = getValues(way.getId()); + storage.setEdgeValue(edge.getEdge(), values); } private byte[] getValues(long id) { @@ -94,7 +93,7 @@ private byte[] getValues(long id) { Arrays.fill(byteValues, defaultValue); } else { int index = 0; - for (Integer i: gi) { + for (Integer i : gi) { if (i > MAX_VALUE) { throw new AssertionError("Value too large (way id " + id + " at index " + index + "):" + i + " > " + MAX_VALUE); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GraphStorageBuilder.java index 899355e553..6f30a43892 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GraphStorageBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -17,26 +17,25 @@ import com.graphhopper.reader.ReaderWay; import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.plugins.Plugin; -import org.heigit.ors.routing.graphhopper.extensions.ORSGraphHopper; +import org.locationtech.jts.geom.Coordinate; import java.util.Map; public interface GraphStorageBuilder extends Plugin { - GraphExtension init(GraphHopper graphhopper) throws Exception; + GraphExtension init(GraphHopper graphhopper) throws Exception; + + void processWay(ReaderWay way); + + void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags); - void processWay(ReaderWay way); + void processEdge(ReaderWay way, EdgeIteratorState edge); - void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags); - - void processEdge(ReaderWay way, EdgeIteratorState edge); + void processEdge(ReaderWay way, EdgeIteratorState edge, Coordinate[] coords); - void processEdge(ReaderWay way, EdgeIteratorState edge, Coordinate[] coords); + void setParameters(Map parameters); - void setParameters(Map parameters); + String getName(); - String getName(); - - void finish(); + void finish(); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GreenIndexGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GreenIndexGraphStorageBuilder.java index 5c6e6f3e78..77c6d8586e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GreenIndexGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/GreenIndexGraphStorageBuilder.java @@ -70,12 +70,12 @@ private void readGreenIndicesFromCSV(String csvFile) throws IOException { String row; // Jump the header line row = csvBuffer.readLine(); - char separator = row.contains(";") ? ';': ','; + char separator = row.contains(";") ? ';' : ','; String[] rowValues = new String[2]; - while ((row = csvBuffer.readLine()) != null) { + while ((row = csvBuffer.readLine()) != null) { if (!parseCSVrow(row, separator, rowValues)) - continue; + continue; greenIndices.put(Long.parseLong(rowValues[0]), Double.parseDouble(rowValues[1])); } @@ -85,18 +85,18 @@ private void readGreenIndicesFromCSV(String csvFile) throws IOException { } } - private boolean parseCSVrow(String row, char separator, String[] rowValues) { + private boolean parseCSVrow(String row, char separator, String[] rowValues) { if (Helper.isEmpty(row)) - return false; + return false; int pos = row.indexOf(separator); if (pos > 0) { - rowValues[0] = row.substring(0, pos).trim(); - rowValues[1] = row.substring(pos+1).trim(); - // read, check and push "osm_id" and "ungreen_factor" values + rowValues[0] = row.substring(0, pos).trim(); + rowValues[1] = row.substring(pos + 1).trim(); + // read, check and push "osm_id" and "ungreen_factor" values return !Helper.isEmpty(rowValues[0]) && !Helper.isEmpty(rowValues[1]); } - return false; + return false; } @Override diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HeavyVehicleGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HeavyVehicleGraphStorageBuilder.java index 94e7189351..d7863007a3 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HeavyVehicleGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HeavyVehicleGraphStorageBuilder.java @@ -28,237 +28,233 @@ import java.util.regex.Pattern; public class HeavyVehicleGraphStorageBuilder extends AbstractGraphStorageBuilder { - private static final String VAL_DELIVERY = "delivery"; - private boolean includeRestrictions = true; - private HeavyVehicleAttributesGraphStorage storage; - private int hgvType = 0; - private int hgvDestination = 0; - private boolean hasRestrictionValues; - private final double[] restrictionValues = new double[VehicleDimensionRestrictions.COUNT]; - private final List motorVehicleRestrictions = new ArrayList<>(5); - private final Set motorVehicleRestrictedValues = new HashSet<>(5); - private final Set motorVehicleHgvValues = new HashSet<>(6); - - private final Set noValues = new HashSet<>(5); - private final Set yesValues = new HashSet<>(5); - private final Pattern patternDimension; - - public HeavyVehicleGraphStorageBuilder() { - motorVehicleRestrictions.addAll(Arrays.asList("motorcar", "motor_vehicle", "vehicle", "access")); - - motorVehicleRestrictedValues.add("private"); - motorVehicleRestrictedValues.add("no"); - motorVehicleRestrictedValues.add("restricted"); - motorVehicleRestrictedValues.add("military"); - - motorVehicleHgvValues.addAll(Arrays.asList("hgv", "goods", "bus", "agricultural", "forestry", VAL_DELIVERY)); - - noValues.addAll(Arrays.asList("no", "private")); - yesValues.addAll(Arrays.asList("yes", "designated")); - - patternDimension = Pattern.compile("(?:\\s*(\\d+)\\s*(?:feet|ft\\.|ft|'))?(?:(\\d+)\\s*(?:inches|in\\.|in|''|\"))?"); - } - - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new Exception("GraphStorageBuilder has been already initialized."); - - if (parameters != null) { - String value = parameters.get("restrictions"); - if (!Helper.isEmpty(value)) - includeRestrictions = Boolean.parseBoolean(value); - } - - storage = new HeavyVehicleAttributesGraphStorage(includeRestrictions); - - return storage; - } - - public void processWay(ReaderWay way) { - // reset values - hgvType = 0; - hgvDestination = 0; - - if (hasRestrictionValues) { - restrictionValues[0] = 0.0; - restrictionValues[1] = 0.0; - restrictionValues[2] = 0.0; - restrictionValues[3] = 0.0; - restrictionValues[4] = 0.0; - hasRestrictionValues = false; - } - - boolean hasHighway = way.hasTag("highway"); - - if (hasHighway) { - // process motor vehicle restrictions before any more specific vehicle type tags which override the former - - // if there are any generic motor vehicle restrictions restrict all types... - if (way.hasTag(motorVehicleRestrictions, motorVehicleRestrictedValues)) - hgvType = HeavyVehicleAttributes.ANY; - - //...or all but the explicitly listed ones - if (way.hasTag(motorVehicleRestrictions, motorVehicleHgvValues)) { - int flag = 0; - for (String key : motorVehicleRestrictions) { - String [] values = way.getTagValues(key); - for (String val: values) { - if (motorVehicleHgvValues.contains(val)) - flag |= HeavyVehicleAttributes.getFromString(val); - } - } - hgvType = HeavyVehicleAttributes.ANY & ~flag; - } - - Iterator> it = way.getProperties(); - - while (it.hasNext()) { - Map.Entry pairs = it.next(); - String key = pairs.getKey(); - String value = pairs.getValue().toString(); - - /* - * https://wiki.openstreetmap.org/wiki/Restrictions - */ - - int valueIndex = -1; - - switch (key) { - case "maxheight" -> valueIndex = VehicleDimensionRestrictions.MAX_HEIGHT; - case "maxweight", "maxweight:hgv" -> valueIndex = VehicleDimensionRestrictions.MAX_WEIGHT; - case "maxwidth" -> valueIndex = VehicleDimensionRestrictions.MAX_WIDTH; - case "maxlength", "maxlength:hgv" -> valueIndex = VehicleDimensionRestrictions.MAX_LENGTH; - case "maxaxleload" -> valueIndex = VehicleDimensionRestrictions.MAX_AXLE_LOAD; - default -> { - } - } - - // given tag is a weight/dimension restriction - if (valueIndex >= 0 && includeRestrictions && !("none".equals(value) || "default".equals(value))) { - double parsedValue = -1; - - // sanitize decimal separators - if (value.contains(",")) - value = value.replace(',', '.'); - - // weight restrictions - if (valueIndex == VehicleDimensionRestrictions.MAX_WEIGHT || valueIndex == VehicleDimensionRestrictions.MAX_AXLE_LOAD) { - if (value.contains("t")) { - value = value.replace('t', ' '); - } else if (value.contains("lbs")) { - value = value.replace("lbs", " "); - parsedValue = parseDouble(value) / 2204.622; - } - } - - // dimension restrictions - else { - if (value.contains("m")) { - value = value.replace('m', ' '); - } else { - Matcher m = patternDimension.matcher(value); - if (m.matches() && m.lookingAt()) { - double feet = parseDouble(m.group(1)); - double inches = 0; - if (m.groupCount() > 1 && m.group(2) != null) { - inches = parseDouble(m.group(2)); - } - parsedValue = feet * 0.3048 + inches * 0.0254; - } - } - } - - if (parsedValue == -1) - parsedValue = parseDouble(value); - - // it was possible to extract a reasonable value - if (parsedValue > 0) { - restrictionValues[valueIndex] = parsedValue; - hasRestrictionValues = true; - } - } - - if (motorVehicleHgvValues.contains(key)) { - - // TODO: the following implementation does not pick up access:destination - String hgvTag = getHeavyVehicleValue(key, "hgv", value); - String goodsTag = getHeavyVehicleValue(key, "goods", value); - String busTag = getHeavyVehicleValue(key, "bus", value); - String agriculturalTag = getHeavyVehicleValue(key, "agricultural", value); - String forestryTag = getHeavyVehicleValue(key, "forestry", value); - String deliveryTag = getHeavyVehicleValue(key, VAL_DELIVERY, value); - - setFlagsFromTag(goodsTag, HeavyVehicleAttributes.GOODS); - setFlagsFromTag(hgvTag, HeavyVehicleAttributes.HGV); - setFlagsFromTag(busTag, HeavyVehicleAttributes.BUS); - setFlagsFromTag(agriculturalTag, HeavyVehicleAttributes.AGRICULTURE); - setFlagsFromTag(forestryTag, HeavyVehicleAttributes.FORESTRY); - setFlagsFromTag(deliveryTag, HeavyVehicleAttributes.DELIVERY); - - } - else if (key.equals("hazmat") && "no".equals(value)) { - hgvType |= HeavyVehicleAttributes.HAZMAT; - } - } - } - } - - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - storage.setEdgeValue(edge.getEdge(), hgvType, hgvDestination, restrictionValues); - } - - private String getHeavyVehicleValue(String key, String hv, String value) { - if (value.equals(hv)) - return value; - else if (key.equals(hv)) { - if (yesValues.contains(value)) - return "yes"; - else if (noValues.contains(value)) - return "no"; - } - else if (key.equals(hv+":forward") || key.equals(hv+":backward")) - return value; - - return null; - } - - /** - * Toggle the bit corresponding to a given hgv type defined by {@code flag} inside binary restriction masks based on - * the value of {@code tag}. "no" sets the bit in {@code _hgvType}, while "yes" unsets it. - * - * When the value is "destination" (or "delivery" for hgv delivery) values in both {@code _hgvType} and - * {@code _hgvDestination} are set. - * - * @param tag - * a String describing the access restriction - * @param flag - * hgv type as defined in {@code HeavyVehicleAttributes} - */ - private void setFlagsFromTag (String tag, int flag) { - if (tag != null) { - if ("no".equals(tag)) - hgvType |= flag; - else if ("yes".equals(tag)) - hgvType &= ~flag; - else if ("destination".equals(tag) || (flag==HeavyVehicleAttributes.DELIVERY && VAL_DELIVERY.equals(tag))) { - hgvType |= flag; - hgvDestination |= flag; - } - } - } - - private double parseDouble(String str) { - double d; - try { - d = Double.parseDouble(str); - } catch(NumberFormatException e) { - d = 0.0; - } - return d; - } - - @Override - public String getName() { - return "HeavyVehicle"; - } + private static final String VAL_DELIVERY = "delivery"; + private boolean includeRestrictions = true; + private HeavyVehicleAttributesGraphStorage storage; + private int hgvType = 0; + private int hgvDestination = 0; + private boolean hasRestrictionValues; + private final double[] restrictionValues = new double[VehicleDimensionRestrictions.COUNT]; + private final List motorVehicleRestrictions = new ArrayList<>(5); + private final Set motorVehicleRestrictedValues = new HashSet<>(5); + private final Set motorVehicleHgvValues = new HashSet<>(6); + + private final Set noValues = new HashSet<>(5); + private final Set yesValues = new HashSet<>(5); + private final Pattern patternDimension; + + public HeavyVehicleGraphStorageBuilder() { + motorVehicleRestrictions.addAll(Arrays.asList("motorcar", "motor_vehicle", "vehicle", "access")); + + motorVehicleRestrictedValues.add("private"); + motorVehicleRestrictedValues.add("no"); + motorVehicleRestrictedValues.add("restricted"); + motorVehicleRestrictedValues.add("military"); + + motorVehicleHgvValues.addAll(Arrays.asList("hgv", "goods", "bus", "agricultural", "forestry", VAL_DELIVERY)); + + noValues.addAll(Arrays.asList("no", "private")); + yesValues.addAll(Arrays.asList("yes", "designated")); + + patternDimension = Pattern.compile("(?:\\s*(\\d+)\\s*(?:feet|ft\\.|ft|'))?(?:(\\d+)\\s*(?:inches|in\\.|in|''|\"))?"); + } + + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new Exception("GraphStorageBuilder has been already initialized."); + + if (parameters != null) { + String value = parameters.get("restrictions"); + if (!Helper.isEmpty(value)) + includeRestrictions = Boolean.parseBoolean(value); + } + + storage = new HeavyVehicleAttributesGraphStorage(includeRestrictions); + + return storage; + } + + public void processWay(ReaderWay way) { + // reset values + hgvType = 0; + hgvDestination = 0; + + if (hasRestrictionValues) { + restrictionValues[0] = 0.0; + restrictionValues[1] = 0.0; + restrictionValues[2] = 0.0; + restrictionValues[3] = 0.0; + restrictionValues[4] = 0.0; + hasRestrictionValues = false; + } + + boolean hasHighway = way.hasTag("highway"); + + if (hasHighway) { + // process motor vehicle restrictions before any more specific vehicle type tags which override the former + + // if there are any generic motor vehicle restrictions restrict all types... + if (way.hasTag(motorVehicleRestrictions, motorVehicleRestrictedValues)) + hgvType = HeavyVehicleAttributes.ANY; + + //...or all but the explicitly listed ones + if (way.hasTag(motorVehicleRestrictions, motorVehicleHgvValues)) { + int flag = 0; + for (String key : motorVehicleRestrictions) { + String[] values = way.getTagValues(key); + for (String val : values) { + if (motorVehicleHgvValues.contains(val)) + flag |= HeavyVehicleAttributes.getFromString(val); + } + } + hgvType = HeavyVehicleAttributes.ANY & ~flag; + } + + Iterator> it = way.getProperties(); + + while (it.hasNext()) { + Map.Entry pairs = it.next(); + String key = pairs.getKey(); + String value = pairs.getValue().toString(); + + /* + * https://wiki.openstreetmap.org/wiki/Restrictions + */ + + int valueIndex = -1; + + switch (key) { + case "maxheight" -> valueIndex = VehicleDimensionRestrictions.MAX_HEIGHT; + case "maxweight", "maxweight:hgv" -> valueIndex = VehicleDimensionRestrictions.MAX_WEIGHT; + case "maxwidth" -> valueIndex = VehicleDimensionRestrictions.MAX_WIDTH; + case "maxlength", "maxlength:hgv" -> valueIndex = VehicleDimensionRestrictions.MAX_LENGTH; + case "maxaxleload" -> valueIndex = VehicleDimensionRestrictions.MAX_AXLE_LOAD; + default -> { + } + } + + // given tag is a weight/dimension restriction + if (valueIndex >= 0 && includeRestrictions && !("none".equals(value) || "default".equals(value))) { + double parsedValue = -1; + + // sanitize decimal separators + if (value.contains(",")) + value = value.replace(',', '.'); + + // weight restrictions + if (valueIndex == VehicleDimensionRestrictions.MAX_WEIGHT || valueIndex == VehicleDimensionRestrictions.MAX_AXLE_LOAD) { + if (value.contains("t")) { + value = value.replace('t', ' '); + } else if (value.contains("lbs")) { + value = value.replace("lbs", " "); + parsedValue = parseDouble(value) / 2204.622; + } + } + + // dimension restrictions + else { + if (value.contains("m")) { + value = value.replace('m', ' '); + } else { + Matcher m = patternDimension.matcher(value); + if (m.matches() && m.lookingAt()) { + double feet = parseDouble(m.group(1)); + double inches = 0; + if (m.groupCount() > 1 && m.group(2) != null) { + inches = parseDouble(m.group(2)); + } + parsedValue = feet * 0.3048 + inches * 0.0254; + } + } + } + + if (parsedValue == -1) + parsedValue = parseDouble(value); + + // it was possible to extract a reasonable value + if (parsedValue > 0) { + restrictionValues[valueIndex] = parsedValue; + hasRestrictionValues = true; + } + } + + if (motorVehicleHgvValues.contains(key)) { + + // TODO: the following implementation does not pick up access:destination + String hgvTag = getHeavyVehicleValue(key, "hgv", value); + String goodsTag = getHeavyVehicleValue(key, "goods", value); + String busTag = getHeavyVehicleValue(key, "bus", value); + String agriculturalTag = getHeavyVehicleValue(key, "agricultural", value); + String forestryTag = getHeavyVehicleValue(key, "forestry", value); + String deliveryTag = getHeavyVehicleValue(key, VAL_DELIVERY, value); + + setFlagsFromTag(goodsTag, HeavyVehicleAttributes.GOODS); + setFlagsFromTag(hgvTag, HeavyVehicleAttributes.HGV); + setFlagsFromTag(busTag, HeavyVehicleAttributes.BUS); + setFlagsFromTag(agriculturalTag, HeavyVehicleAttributes.AGRICULTURE); + setFlagsFromTag(forestryTag, HeavyVehicleAttributes.FORESTRY); + setFlagsFromTag(deliveryTag, HeavyVehicleAttributes.DELIVERY); + + } else if (key.equals("hazmat") && "no".equals(value)) { + hgvType |= HeavyVehicleAttributes.HAZMAT; + } + } + } + } + + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + storage.setEdgeValue(edge.getEdge(), hgvType, hgvDestination, restrictionValues); + } + + private String getHeavyVehicleValue(String key, String hv, String value) { + if (value.equals(hv)) + return value; + else if (key.equals(hv)) { + if (yesValues.contains(value)) + return "yes"; + else if (noValues.contains(value)) + return "no"; + } else if (key.equals(hv + ":forward") || key.equals(hv + ":backward")) + return value; + + return null; + } + + /** + * Toggle the bit corresponding to a given hgv type defined by {@code flag} inside binary restriction masks based on + * the value of {@code tag}. "no" sets the bit in {@code _hgvType}, while "yes" unsets it. + *

    + * When the value is "destination" (or "delivery" for hgv delivery) values in both {@code _hgvType} and + * {@code _hgvDestination} are set. + * + * @param tag a String describing the access restriction + * @param flag hgv type as defined in {@code HeavyVehicleAttributes} + */ + private void setFlagsFromTag(String tag, int flag) { + if (tag != null) { + if ("no".equals(tag)) + hgvType |= flag; + else if ("yes".equals(tag)) + hgvType &= ~flag; + else if ("destination".equals(tag) || (flag == HeavyVehicleAttributes.DELIVERY && VAL_DELIVERY.equals(tag))) { + hgvType |= flag; + hgvDestination |= flag; + } + } + } + + private double parseDouble(String str) { + double d; + try { + d = Double.parseDouble(str); + } catch (NumberFormatException e) { + d = 0.0; + } + return d; + } + + @Override + public String getName() { + return "HeavyVehicle"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HereTrafficGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HereTrafficGraphStorageBuilder.java index 6e29ff8662..58dd974c09 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HereTrafficGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HereTrafficGraphStorageBuilder.java @@ -22,18 +22,11 @@ import com.graphhopper.reader.ReaderWay; import com.graphhopper.routing.querygraph.VirtualEdgeIteratorState; import com.graphhopper.storage.GraphExtension; -import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.FetchMode; import me.tongfei.progressbar.DelegatingProgressBarConsumer; -import me.tongfei.progressbar.ProgressBarBuilder; -import org.heigit.ors.mapmatching.GhMapMatcher; -import org.heigit.ors.mapmatching.MapMatcher; -import org.heigit.ors.routing.graphhopper.extensions.edgefilters.TrafficEdgeFilter; -import org.locationtech.jts.geom.GeometryFactory; -import org.locationtech.jts.io.ParseException; -import org.locationtech.jts.io.WKTReader; import me.tongfei.progressbar.ProgressBar; +import me.tongfei.progressbar.ProgressBarBuilder; import org.apache.log4j.Logger; import org.geotools.data.DataUtilities; import org.geotools.feature.DefaultFeatureCollection; @@ -41,18 +34,20 @@ import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.geojson.geom.GeometryJSON; +import org.heigit.ors.mapmatching.GhMapMatcher; +import org.heigit.ors.mapmatching.MapMatcher; import org.heigit.ors.mapmatching.RouteSegmentInfo; import org.heigit.ors.routing.graphhopper.extensions.ORSGraphHopper; import org.heigit.ors.routing.graphhopper.extensions.TrafficRelevantWayType; -import org.heigit.ors.routing.graphhopper.extensions.reader.traffic.HereTrafficReader; -import org.heigit.ors.routing.graphhopper.extensions.reader.traffic.TrafficData; -import org.heigit.ors.routing.graphhopper.extensions.reader.traffic.TrafficEnums; -import org.heigit.ors.routing.graphhopper.extensions.reader.traffic.TrafficLink; -import org.heigit.ors.routing.graphhopper.extensions.reader.traffic.TrafficPattern; +import org.heigit.ors.routing.graphhopper.extensions.edgefilters.TrafficEdgeFilter; +import org.heigit.ors.routing.graphhopper.extensions.reader.traffic.*; import org.heigit.ors.routing.graphhopper.extensions.storages.TrafficGraphStorage; import org.heigit.ors.util.ErrorLoggingUtility; import org.locationtech.jts.geom.Geometry; +import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; +import org.locationtech.jts.io.ParseException; +import org.locationtech.jts.io.WKTReader; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; @@ -60,12 +55,7 @@ import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.Iterator; -import java.util.Map; -import java.util.MissingResourceException; +import java.util.*; public class HereTrafficGraphStorageBuilder extends AbstractGraphStorageBuilder { static final Logger LOGGER = Logger.getLogger(HereTrafficGraphStorageBuilder.class.getName()); @@ -95,8 +85,8 @@ public class HereTrafficGraphStorageBuilder extends AbstractGraphStorageBuilder private GraphHopper gh; private MapMatcher mMapMatcher; private TrafficEdgeFilter trafficEdgeFilter; - private IntHashSet matchedHereLinks = new IntHashSet(); - private ArrayList matchedOSMLinks = new ArrayList<>(); + private final IntHashSet matchedHereLinks = new IntHashSet(); + private final ArrayList matchedOSMLinks = new ArrayList<>(); /** * Initialize the Here Traffic graph extension

    @@ -392,10 +382,10 @@ private void processSegment(GraphHopper gh, Map t } public RouteSegmentInfo[] getMatchedSegmentsInternal(Geometry geometry, - double originalTrafficLinkLength, - int trafficLinkFunctionalClass, - boolean bothDirections, - int matchingRadius) { + double originalTrafficLinkLength, + int trafficLinkFunctionalClass, + boolean bothDirections, + int matchingRadius) { if (trafficEdgeFilter == null) { trafficEdgeFilter = new TrafficEdgeFilter(gh.getGraphHopperStorage()); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HillIndexGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HillIndexGraphStorageBuilder.java index 7dfb4f8473..9ed938cd50 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HillIndexGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/HillIndexGraphStorageBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -23,41 +23,41 @@ import org.heigit.ors.routing.util.HillIndexCalculator; public class HillIndexGraphStorageBuilder extends AbstractGraphStorageBuilder { - private HillIndexGraphStorage storage; - private HillIndexCalculator hillIndexCalc; - - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new Exception("GraphStorageBuilder has been already initialized."); - if (graphhopper.hasElevation()) { - storage = new HillIndexGraphStorage(parameters); - hillIndexCalc = new HillIndexCalculator(); - - return storage; - } - throw new Exception("HillIndexGraphStorageBuilder cannot be initialized since elevation is deactivated for this profile."); - } - - public void processWay(ReaderWay way) { - // do nothing - } - - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - boolean revert = edge.getBaseNode() > edge.getAdjNode(); - - PointList points = edge.fetchWayGeometry(FetchMode.ALL); - - byte hillIndex = hillIndexCalc.getHillIndex(points, false); - byte reverseHillIndex = hillIndexCalc.getHillIndex(points, true); - - if (revert) - storage.setEdgeValue(edge.getEdge(), reverseHillIndex, hillIndex); - else - storage.setEdgeValue(edge.getEdge(), hillIndex, reverseHillIndex); - } - - @Override - public String getName() { - return "HillIndex"; - } + private HillIndexGraphStorage storage; + private HillIndexCalculator hillIndexCalc; + + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new Exception("GraphStorageBuilder has been already initialized."); + if (graphhopper.hasElevation()) { + storage = new HillIndexGraphStorage(parameters); + hillIndexCalc = new HillIndexCalculator(); + + return storage; + } + throw new Exception("HillIndexGraphStorageBuilder cannot be initialized since elevation is deactivated for this profile."); + } + + public void processWay(ReaderWay way) { + // do nothing + } + + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + boolean revert = edge.getBaseNode() > edge.getAdjNode(); + + PointList points = edge.fetchWayGeometry(FetchMode.ALL); + + byte hillIndex = hillIndexCalc.getHillIndex(points, false); + byte reverseHillIndex = hillIndexCalc.getHillIndex(points, true); + + if (revert) + storage.setEdgeValue(edge.getEdge(), reverseHillIndex, hillIndex); + else + storage.setEdgeValue(edge.getEdge(), hillIndex, reverseHillIndex); + } + + @Override + public String getName() { + return "HillIndex"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/NoiseIndexGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/NoiseIndexGraphStorageBuilder.java index d343f54bcd..d6f7085390 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/NoiseIndexGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/NoiseIndexGraphStorageBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -18,6 +18,8 @@ import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.Helper; +import org.apache.log4j.Logger; +import org.heigit.ors.routing.graphhopper.extensions.storages.NoiseIndexGraphStorage; import java.io.BufferedReader; import java.io.FileReader; @@ -25,9 +27,6 @@ import java.util.HashMap; import java.util.Map; -import org.apache.log4j.Logger; -import org.heigit.ors.routing.graphhopper.extensions.storages.NoiseIndexGraphStorage; - /** * Created by ZWang on 13/06/2017. */ @@ -58,9 +57,9 @@ private void readNoiseIndicesFromCSV(String csvFile) throws IOException { String row = csvBuffer.readLine(); String[] rowValues = new String[2]; while ((row = csvBuffer.readLine()) != null) { - if (!parseCSVrow(row, rowValues)) - continue; - + if (!parseCSVrow(row, rowValues)) + continue; + osmId2noiseLevel.put(Long.parseLong(rowValues[0]), Integer.parseInt(rowValues[1])); } } catch (IOException openFileEx) { @@ -69,15 +68,15 @@ private void readNoiseIndicesFromCSV(String csvFile) throws IOException { } } - private boolean parseCSVrow(String row, String[] rowValues) { + private boolean parseCSVrow(String row, String[] rowValues) { if (Helper.isEmpty(row)) - return false; - + return false; + int pos = row.indexOf(','); if (pos > 0) { - rowValues[0] = row.substring(0, pos).trim(); - rowValues[1] = row.substring(pos + 1).trim(); - // read, check and push "osm_id" and "noise level" values + rowValues[0] = row.substring(0, pos).trim(); + rowValues[1] = row.substring(pos + 1).trim(); + // read, check and push "osm_id" and "noise level" values return !Helper.isEmpty(rowValues[0]) && !Helper.isEmpty(rowValues[1]); } return false; @@ -90,8 +89,8 @@ public void processWay(ReaderWay way) { @Override public void processEdge(ReaderWay way, EdgeIteratorState edge) { - byte noiseLevel = getNoiseLevel(way.getId()); - storage.setEdgeValue(edge.getEdge(), noiseLevel); + byte noiseLevel = getNoiseLevel(way.getId()); + storage.setEdgeValue(edge.getEdge(), noiseLevel); } private byte getNoiseLevel(long id) { @@ -102,8 +101,8 @@ private byte getNoiseLevel(long id) { if (gi == null) return (byte) (0); if (gi > MAX_LEVEL) - throw new AssertionError("The noise level of osm way, id = "+ id + " is " + gi +", which is larger than than max level!"); - + throw new AssertionError("The noise level of osm way, id = " + id + " is " + gi + ", which is larger than than max level!"); + return (byte) (gi.intValue()); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/OsmIdGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/OsmIdGraphStorageBuilder.java index c22f51ba7d..fa224ba1fe 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/OsmIdGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/OsmIdGraphStorageBuilder.java @@ -25,8 +25,8 @@ public void processWay(ReaderWay way) { /** * Process the graph edge - In the OSMId graph storage this stores the osm id (the way id) against the edge * - * @param way The full way read from the parser - * @param edge The EdgeIteratorState representing the edge to be processed + * @param way The full way read from the parser + * @param edge The EdgeIteratorState representing the edge to be processed */ public void processEdge(ReaderWay way, EdgeIteratorState edge) { osmIdGraphStorage.setEdgeValue(edge.getEdge(), way.getId()); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/RoadAccessRestrictionsGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/RoadAccessRestrictionsGraphStorageBuilder.java index 4e8b5d514b..7e074fb308 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/RoadAccessRestrictionsGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/RoadAccessRestrictionsGraphStorageBuilder.java @@ -21,10 +21,10 @@ import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.routing.RoutingProfileType; import org.heigit.ors.routing.graphhopper.extensions.AccessRestrictionType; import org.heigit.ors.routing.graphhopper.extensions.storages.RoadAccessRestrictionsGraphStorage; +import org.locationtech.jts.geom.Coordinate; import java.util.*; @@ -70,9 +70,10 @@ public RoadAccessRestrictionsGraphStorageBuilder() { /** * Initialise the road access restrictions graph storage builder for a profile and set the profile type to be that * specified. - * @param graphhopper The graphhopper instance being used (not used) - * @param profileType The id of the profile type that the RoadAccessRestrictions are for - * @return The RoadAccessRestrictionStorage object created as part of the initialisation + * + * @param graphhopper The graphhopper instance being used (not used) + * @param profileType The id of the profile type that the RoadAccessRestrictions are for + * @return The RoadAccessRestrictionStorage object created as part of the initialisation * @throws Exception */ public GraphExtension init(GraphHopper graphhopper, int profileType) throws Exception { @@ -91,8 +92,9 @@ public GraphExtension init(GraphHopper graphhopper, int profileType) throws Exce /** * Initialise the road access restrictions graph storage builder for a profile - * @param graphhopper The graphhopper instance being used - * @return The RoadAccessRestrictionStorage object created as part of the initialisation + * + * @param graphhopper The graphhopper instance being used + * @return The RoadAccessRestrictionStorage object created as part of the initialisation * @throws Exception */ public GraphExtension init(GraphHopper graphhopper) throws Exception { @@ -127,19 +129,20 @@ public void processWay(ReaderWay way) { * Process the road access restrictions of a way feature ready for processing into edges. It checks to see if there * are restrictions present in the form of tags (e.g. access=private) and then stores the information accordingly. * It first checks if there have already been restrictions recorded and if so clears them. - * @param way The way to be processed - * @param coords List of coordinates for the way (not used) - * @param nodeTags List of node ids and the key value pairs for the tags of that node. These values can be used to - * apply restrictions on a way introduced by items like lift gates that are nodes on the way + * + * @param way The way to be processed + * @param coords List of coordinates for the way (not used) + * @param nodeTags List of node ids and the key value pairs for the tags of that node. These values can be used to + * apply restrictions on a way introduced by items like lift gates that are nodes on the way */ @Override - public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) { + public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) { if (hasRestrictions) { hasRestrictions = false; restrictions = 0; } - if(nodeTags != null) { + if (nodeTags != null) { for (Map tagPairs : nodeTags.values()) { for (Map.Entry pair : tagPairs.entrySet()) { way.setTag(pair.getKey(), pair.getValue()); @@ -162,9 +165,10 @@ public void processWay(ReaderWay way, Coordinate[] coords, Map tags) { int res = 0; @@ -185,9 +189,10 @@ private int getRestrictionType(ReaderWay way, List tags) { /** * Get the type of restrictions that have been set on the way. - * @param way The way to be checked - * @param tag The tag(key) that should be accessed for the access restrictions - * @return 0 if no restriction, else the integer encoded restriction value for the way + * + * @param way The way to be checked + * @param tag The tag(key) that should be accessed for the access restrictions + * @return 0 if no restriction, else the integer encoded restriction value for the way */ private int getRestrictionType(ReaderWay way, String tag) { int res = 0; @@ -204,9 +209,10 @@ private int getRestrictionType(ReaderWay way, String tag) { /** * Take the encoded restriction value and update it with the passed restriction value - * @param encodedRestrictions Integer representation of the current restrictions - * @param restrictionValue The new restriction to be applied - * @return An integer encoded representation of all restrictions that have been set + * + * @param encodedRestrictions Integer representation of the current restrictions + * @param restrictionValue The new restriction to be applied + * @return An integer encoded representation of all restrictions that have been set */ private int updateRestriction(int encodedRestrictions, String restrictionValue) { int res = encodedRestrictions; @@ -228,9 +234,10 @@ private int updateRestriction(int encodedRestrictions, String restrictionValue) /** * Check if access is allowed on the way. e.g. it would check if motor_car=yes/permissive/destination etc. is set - * @param way The OSM way to be checked - * @param tagNames The tags (keys) to be checked - * @return Whether access is allowed on the way + * + * @param way The OSM way to be checked + * @param tagNames The tags (keys) to be checked + * @return Whether access is allowed on the way */ private boolean isAccessAllowed(ReaderWay way, List tagNames) { return way.hasTag(tagNames, permissiveValues); @@ -238,9 +245,10 @@ private boolean isAccessAllowed(ReaderWay way, List tagNames) { /** * Check if access is allowed on the way. e.g. it would check if motor_car=yes/permissive/destination etc. is set - * @param way The OSM way to be checked - * @param tagName The single tag (key) to be checked - * @return Whether access is allowed on the way + * + * @param way The OSM way to be checked + * @param tagName The single tag (key) to be checked + * @return Whether access is allowed on the way */ private boolean isAccessAllowed(ReaderWay way, String tagName) { return way.hasTag(tagName, permissiveValues); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/ShadowIndexGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/ShadowIndexGraphStorageBuilder.java index 38435d0534..e8deb43aa6 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/ShadowIndexGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/ShadowIndexGraphStorageBuilder.java @@ -1,14 +1,14 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; + * You should have received a copy of the GNU Lesser General Public License along with this library; * if not, see . * */ @@ -31,13 +31,12 @@ /** * This class builds the shadow index data as a new ShadowGraphStorage. - * */ public class ShadowIndexGraphStorageBuilder extends AbstractGraphStorageBuilder { private static final Logger LOGGER = Logger.getLogger(ShadowIndexGraphStorageBuilder.class.getName()); private ShadowIndexGraphStorage _storage; - private Map osm_shadowindex_lookup = new HashMap<>(); - private int max_level = 100; + private final Map osm_shadowindex_lookup = new HashMap<>(); + private final int max_level = 100; private final int no_data = 30; public ShadowIndexGraphStorageBuilder() { @@ -75,23 +74,18 @@ private void readShadowIndicesFromCSV(String csvFile) throws IOException { } - private boolean parseCSVrow(String row, String[] rowValues) { + private boolean parseCSVrow(String row, String[] rowValues) { if (Helper.isEmpty(row)) - return false; - + return false; + int pos = row.indexOf(','); - if (pos > 0) - { - rowValues[0] = row.substring(0, pos).trim(); - rowValues[1] = row.substring(pos+1, row.length()).trim(); - // read, check and push "osm_id" and "shadow level" values - if (Helper.isEmpty(rowValues[0]) || Helper.isEmpty(rowValues[1])) - return false; - - return true; - } - else - return false; + if (pos > 0) { + rowValues[0] = row.substring(0, pos).trim(); + rowValues[1] = row.substring(pos + 1).trim(); + // read, check and push "osm_id" and "shadow level" values + return !Helper.isEmpty(rowValues[0]) && !Helper.isEmpty(rowValues[1]); + } else + return false; } @Override @@ -102,8 +96,8 @@ public void processWay(ReaderWay way) { @Override public void processEdge(ReaderWay way, EdgeIteratorState edge) { //_storage.setEdgeValue(edge.getEdge(), getShadowIndex(way.getId())); - byte shadow_index = getShadowIndex(way.getId()); - _storage.setEdgeValue(edge.getEdge(), shadow_index); + byte shadow_index = getShadowIndex(way.getId()); + _storage.setEdgeValue(edge.getEdge(), shadow_index); } private byte getShadowIndex(long id) { @@ -114,7 +108,7 @@ private byte getShadowIndex(long id) { if (shadow_index > max_level) { LOGGER.warn("\nThe shadow index value of osm way, id = " + id + " is " + shadow_index - + ", which is larger than than max level!"); + + ", which is larger than than max level!"); return (byte) max_level; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/SpeedGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/SpeedGraphStorageBuilder.java index cd200487b4..f35c4c8650 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/SpeedGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/SpeedGraphStorageBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -24,33 +24,33 @@ import java.util.List; public class SpeedGraphStorageBuilder extends AbstractGraphStorageBuilder { - private SpeedStorage storage; - - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new IllegalStateException("GraphStorageBuilder has been already initialized."); - - // extract profiles from GraphHopper instance - EncodingManager encMgr = graphhopper.getEncodingManager(); - List encoders = encMgr.fetchEdgeEncoders(); - FlagEncoder flagEncoder = encoders.get(0); - - storage = new SpeedStorage(flagEncoder); - return storage; - } - - @Override - public void processWay(ReaderWay way) { - //No processing on input data - } - - @Override - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - //No processing on input data - } - - @Override - public String getName() { - return "Speed"; - } + private SpeedStorage storage; + + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new IllegalStateException("GraphStorageBuilder has been already initialized."); + + // extract profiles from GraphHopper instance + EncodingManager encMgr = graphhopper.getEncodingManager(); + List encoders = encMgr.fetchEdgeEncoders(); + FlagEncoder flagEncoder = encoders.get(0); + + storage = new SpeedStorage(flagEncoder); + return storage; + } + + @Override + public void processWay(ReaderWay way) { + //No processing on input data + } + + @Override + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + //No processing on input data + } + + @Override + public String getName() { + return "Speed"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TollwaysGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TollwaysGraphStorageBuilder.java index 025fbb9744..e3cb826a4c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TollwaysGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TollwaysGraphStorageBuilder.java @@ -13,78 +13,76 @@ */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import com.graphhopper.GraphHopper; import com.graphhopper.reader.ReaderWay; import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; - import org.heigit.ors.routing.graphhopper.extensions.TollwayType; import org.heigit.ors.routing.graphhopper.extensions.storages.TollwaysGraphStorage; -public class TollwaysGraphStorageBuilder extends AbstractGraphStorageBuilder -{ - private TollwaysGraphStorage storage; - private int tollways; - private final List tollTags = new ArrayList<>(6); - - public TollwaysGraphStorageBuilder() { - // Currently consider only toll tags relevant to cars or hgvs: - tollTags.addAll(Arrays.asList("toll", "toll:hgv", "toll:N1", "toll:N2", "toll:N3", "toll:motorcar")); - } - - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new Exception("GraphStorageBuilder has been already initialized."); - - storage = new TollwaysGraphStorage(); - - return storage; - } - - public void processWay(ReaderWay way) { - tollways = TollwayType.NONE; - - for (String key : tollTags) { - if (way.hasTag(key)) { - String value = way.getTag(key); - - if (value != null) { - switch (key) { - case "toll" -> setFlag(TollwayType.GENERAL, value); - case "toll:hgv" -> setFlag(TollwayType.HGV, value); - case "toll:N1" -> //currently not used in OSM - setFlag(TollwayType.N1, value); - case "toll:N2" -> setFlag(TollwayType.N2, value); - case "toll:N3" -> setFlag(TollwayType.N3, value); - case "toll:motorcar" -> setFlag(TollwayType.MOTORCAR, value); - default -> { - } - } - } - } - } - - } - - private void setFlag(int flag, String value) { - switch (value) { - case "yes" -> tollways |= flag; - case "no" -> tollways &= ~flag; - default -> { - } - } - } - - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - storage.setEdgeValue(edge.getEdge(), tollways); - } - - @Override - public String getName() { - return "Tollways"; - } +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class TollwaysGraphStorageBuilder extends AbstractGraphStorageBuilder { + private TollwaysGraphStorage storage; + private int tollways; + private final List tollTags = new ArrayList<>(6); + + public TollwaysGraphStorageBuilder() { + // Currently consider only toll tags relevant to cars or hgvs: + tollTags.addAll(Arrays.asList("toll", "toll:hgv", "toll:N1", "toll:N2", "toll:N3", "toll:motorcar")); + } + + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new Exception("GraphStorageBuilder has been already initialized."); + + storage = new TollwaysGraphStorage(); + + return storage; + } + + public void processWay(ReaderWay way) { + tollways = TollwayType.NONE; + + for (String key : tollTags) { + if (way.hasTag(key)) { + String value = way.getTag(key); + + if (value != null) { + switch (key) { + case "toll" -> setFlag(TollwayType.GENERAL, value); + case "toll:hgv" -> setFlag(TollwayType.HGV, value); + case "toll:N1" -> //currently not used in OSM + setFlag(TollwayType.N1, value); + case "toll:N2" -> setFlag(TollwayType.N2, value); + case "toll:N3" -> setFlag(TollwayType.N3, value); + case "toll:motorcar" -> setFlag(TollwayType.MOTORCAR, value); + default -> { + } + } + } + } + } + + } + + private void setFlag(int flag, String value) { + switch (value) { + case "yes" -> tollways |= flag; + case "no" -> tollways &= ~flag; + default -> { + } + } + } + + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + storage.setEdgeValue(edge.getEdge(), tollways); + } + + @Override + public String getName() { + return "Tollways"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TrailDifficultyScaleGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TrailDifficultyScaleGraphStorageBuilder.java index 688211eaf1..d822f2f4d6 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TrailDifficultyScaleGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/TrailDifficultyScaleGraphStorageBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -18,70 +18,69 @@ import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.Helper; - import org.heigit.ors.routing.graphhopper.extensions.storages.TrailDifficultyScaleGraphStorage; public class TrailDifficultyScaleGraphStorageBuilder extends AbstractGraphStorageBuilder { - private TrailDifficultyScaleGraphStorage storage; - private int hikingScale; - private int mtbScale; - private int mtbUphillScale; + private TrailDifficultyScaleGraphStorage storage; + private int hikingScale; + private int mtbScale; + private int mtbUphillScale; - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new Exception("GraphStorageBuilder has been already initialized."); - storage = new TrailDifficultyScaleGraphStorage(); - return storage; - } + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new Exception("GraphStorageBuilder has been already initialized."); + storage = new TrailDifficultyScaleGraphStorage(); + return storage; + } - public void processWay(ReaderWay way) { - hikingScale = getSacScale(way.getTag("sac_scale")); - mtbScale = getMtbScale(way.getTag("mtb:scale")); - if (mtbScale == 0) - mtbScale = getMtbScale(way.getTag("mtb:scale:imba")); - mtbUphillScale = getMtbScale(way.getTag("mtb:scale:uphill")); - if (mtbUphillScale == 0) - mtbUphillScale = mtbScale; - } + public void processWay(ReaderWay way) { + hikingScale = getSacScale(way.getTag("sac_scale")); + mtbScale = getMtbScale(way.getTag("mtb:scale")); + if (mtbScale == 0) + mtbScale = getMtbScale(way.getTag("mtb:scale:imba")); + mtbUphillScale = getMtbScale(way.getTag("mtb:scale:uphill")); + if (mtbUphillScale == 0) + mtbUphillScale = mtbScale; + } - private int getSacScale(String value) { - if (!Helper.isEmpty(value)) { - switch(value) { - case "hiking": - return 1; - case "mountain_hiking": - return 2; - case "demanding_mountain_hiking": - return 3; - case "alpine_hiking": - return 4; - case "demanding_alpine_hiking": - return 5; - case "difficult_alpine_hiking": - return 6; - default: - } - } - return 0; - } + private int getSacScale(String value) { + if (!Helper.isEmpty(value)) { + switch (value) { + case "hiking": + return 1; + case "mountain_hiking": + return 2; + case "demanding_mountain_hiking": + return 3; + case "alpine_hiking": + return 4; + case "demanding_alpine_hiking": + return 5; + case "difficult_alpine_hiking": + return 6; + default: + } + } + return 0; + } - private int getMtbScale(String value) { - if (!Helper.isEmpty(value)) { - try { - return Integer.parseInt(value) + 1; - } catch(Exception ex) { - // do nothing - } - } - return 0; - } + private int getMtbScale(String value) { + if (!Helper.isEmpty(value)) { + try { + return Integer.parseInt(value) + 1; + } catch (Exception ex) { + // do nothing + } + } + return 0; + } - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - storage.setEdgeValue(edge.getEdge(), hikingScale, mtbScale, mtbUphillScale); - } + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + storage.setEdgeValue(edge.getEdge(), hikingScale, mtbScale, mtbUphillScale); + } - @Override - public String getName() { - return "TrailDifficulty"; - } + @Override + public String getName() { + return "TrailDifficulty"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WayCategoryGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WayCategoryGraphStorageBuilder.java index dcdf046dac..6e437892f5 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WayCategoryGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WayCategoryGraphStorageBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -25,62 +25,62 @@ import java.util.Map.Entry; public class WayCategoryGraphStorageBuilder extends AbstractGraphStorageBuilder { - private WayCategoryGraphStorage storage; - protected final HashSet ferries; - private int wayType = 0; - - public WayCategoryGraphStorageBuilder() { - ferries = new HashSet<>(5); - ferries.add("shuttle_train"); - ferries.add("ferry"); - } - - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new Exception("GraphStorageBuilder has been already initialized."); - - storage = new WayCategoryGraphStorage(); - - return storage; - } - - public void processWay(ReaderWay way) { - wayType = 0; - - boolean hasHighway = way.hasTag("highway"); - boolean isFerryRoute = way.hasTag("route", ferries); - - if (hasHighway || isFerryRoute) { - java.util.Iterator> it = way.getProperties(); - - while (it.hasNext()) { - Map.Entry pairs = it.next(); - String key = pairs.getKey(); - String value = pairs.getValue().toString(); - - if (key.equals("highway")) { - if (value.equals("motorway") || value.equals("motorway_link")) { - wayType |= AvoidFeatureFlags.HIGHWAYS; - } else if (value.equals("steps")) { - wayType |= AvoidFeatureFlags.STEPS; - } - } else if (value.equals("yes") && key.startsWith("toll")) { - wayType |= AvoidFeatureFlags.TOLLWAYS; - } else if (key.equals("route") && isFerryRoute) { - wayType |= AvoidFeatureFlags.FERRIES; - } else if (("ford".equals(key) && value.equals("yes"))) { - wayType |= AvoidFeatureFlags.FORDS; - } - } - } - } - - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - storage.setEdgeValue(edge.getEdge(), wayType); - } - - @Override - public String getName() { - return "WayCategory"; - } + private WayCategoryGraphStorage storage; + protected final HashSet ferries; + private int wayType = 0; + + public WayCategoryGraphStorageBuilder() { + ferries = new HashSet<>(5); + ferries.add("shuttle_train"); + ferries.add("ferry"); + } + + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new Exception("GraphStorageBuilder has been already initialized."); + + storage = new WayCategoryGraphStorage(); + + return storage; + } + + public void processWay(ReaderWay way) { + wayType = 0; + + boolean hasHighway = way.hasTag("highway"); + boolean isFerryRoute = way.hasTag("route", ferries); + + if (hasHighway || isFerryRoute) { + java.util.Iterator> it = way.getProperties(); + + while (it.hasNext()) { + Map.Entry pairs = it.next(); + String key = pairs.getKey(); + String value = pairs.getValue().toString(); + + if (key.equals("highway")) { + if (value.equals("motorway") || value.equals("motorway_link")) { + wayType |= AvoidFeatureFlags.HIGHWAYS; + } else if (value.equals("steps")) { + wayType |= AvoidFeatureFlags.STEPS; + } + } else if (value.equals("yes") && key.startsWith("toll")) { + wayType |= AvoidFeatureFlags.TOLLWAYS; + } else if (key.equals("route") && isFerryRoute) { + wayType |= AvoidFeatureFlags.FERRIES; + } else if (("ford".equals(key) && value.equals("yes"))) { + wayType |= AvoidFeatureFlags.FORDS; + } + } + } + } + + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + storage.setEdgeValue(edge.getEdge(), wayType); + } + + @Override + public String getName() { + return "WayCategory"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WaySurfaceTypeGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WaySurfaceTypeGraphStorageBuilder.java index 360b3e8024..0147caac46 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WaySurfaceTypeGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WaySurfaceTypeGraphStorageBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.storages.builders; @@ -25,58 +25,58 @@ import java.util.HashSet; public class WaySurfaceTypeGraphStorageBuilder extends AbstractGraphStorageBuilder { - public static final String TAG_HIGHWAY = "highway"; - public static final String TAG_SURFACE = "surface"; - public static final String TAG_ROUTE = "route"; - private WaySurfaceTypeGraphStorage storage; - private final WaySurfaceDescription waySurfaceDesc = new WaySurfaceDescription(); - protected final HashSet ferries; - - public WaySurfaceTypeGraphStorageBuilder() { - ferries = new HashSet<>(5); - ferries.add("shuttle_train"); - ferries.add("ferry"); - } - - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new Exception("GraphStorageBuilder has been already initialized."); - - storage = new WaySurfaceTypeGraphStorage(); - return storage; - } + public static final String TAG_HIGHWAY = "highway"; + public static final String TAG_SURFACE = "surface"; + public static final String TAG_ROUTE = "route"; + private WaySurfaceTypeGraphStorage storage; + private final WaySurfaceDescription waySurfaceDesc = new WaySurfaceDescription(); + protected final HashSet ferries; - public void processWay(ReaderWay way) { - waySurfaceDesc.reset(); + public WaySurfaceTypeGraphStorageBuilder() { + ferries = new HashSet<>(5); + ferries.add("shuttle_train"); + ferries.add("ferry"); + } - int wayType; - if (way.hasTag(TAG_ROUTE, ferries)) { - wayType = WayType.FERRY; - } else if (way.hasTag(TAG_HIGHWAY)) { - wayType = WayType.getFromString(way.getTag(TAG_HIGHWAY)); - } else { - return; - } - waySurfaceDesc.setWayType(wayType); + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new Exception("GraphStorageBuilder has been already initialized."); - int surfaceType = way.hasTag(TAG_SURFACE) ? SurfaceType.getFromString(way.getTag(TAG_SURFACE)) : SurfaceType.UNKNOWN; - if (surfaceType == SurfaceType.UNKNOWN) { - if (wayType == WayType.ROAD || wayType == WayType.STATE_ROAD || wayType == WayType.STREET) { - surfaceType = SurfaceType.PAVED; - } else if (wayType == WayType.PATH) { - surfaceType = SurfaceType.UNPAVED; - } - } - waySurfaceDesc.setSurfaceType(surfaceType); + storage = new WaySurfaceTypeGraphStorage(); + return storage; + } - } + public void processWay(ReaderWay way) { + waySurfaceDesc.reset(); - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - storage.setEdgeValue(edge.getEdge(), waySurfaceDesc); - } + int wayType; + if (way.hasTag(TAG_ROUTE, ferries)) { + wayType = WayType.FERRY; + } else if (way.hasTag(TAG_HIGHWAY)) { + wayType = WayType.getFromString(way.getTag(TAG_HIGHWAY)); + } else { + return; + } + waySurfaceDesc.setWayType(wayType); - @Override - public String getName() { - return "WaySurfaceType"; - } + int surfaceType = way.hasTag(TAG_SURFACE) ? SurfaceType.getFromString(way.getTag(TAG_SURFACE)) : SurfaceType.UNKNOWN; + if (surfaceType == SurfaceType.UNKNOWN) { + if (wayType == WayType.ROAD || wayType == WayType.STATE_ROAD || wayType == WayType.STREET) { + surfaceType = SurfaceType.PAVED; + } else if (wayType == WayType.PATH) { + surfaceType = SurfaceType.UNPAVED; + } + } + waySurfaceDesc.setSurfaceType(surfaceType); + + } + + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + storage.setEdgeValue(edge.getEdge(), waySurfaceDesc); + } + + @Override + public String getName() { + return "WaySurfaceType"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilder.java index d7e56b038c..3701bc5b12 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilder.java @@ -17,780 +17,778 @@ import com.graphhopper.reader.ReaderWay; import com.graphhopper.storage.GraphExtension; import com.graphhopper.util.EdgeIteratorState; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.routing.graphhopper.extensions.WheelchairAttributes; import org.heigit.ors.routing.graphhopper.extensions.WheelchairTypesEncoder; import org.heigit.ors.routing.graphhopper.extensions.storages.WheelchairAttributesGraphStorage; import org.heigit.ors.util.UnitsConverter; +import org.locationtech.jts.geom.Coordinate; import java.util.*; public class WheelchairGraphStorageBuilder extends AbstractGraphStorageBuilder { - public static final String KEY_SLOPED_CURB = "sloped_curb"; - public static final String KEY_SLOPED_KERB = "sloped_kerb"; - public static final String KEY_KERB_HEIGHT = "kerb:height"; - public static final String KEY_FOOTWAY = "footway"; - public static final String SW_VAL_RIGHT = "right"; - public static final String SW_VAL_LEFT = "left"; - public static final String KEY_BOTH = "both"; - public static final String KEY_SIDEWALK_BOTH = "sidewalk:both:"; - public static final String KEY_FOOTWAY_BOTH = "footway:both:"; - public static final String KEY_CURB_HEIGHT = "curb:height"; - - public enum Side { - LEFT, - RIGHT, - NONE - } - - private WheelchairAttributesGraphStorage storage; - private final WheelchairAttributes wheelchairAttributes; - private final WheelchairAttributes wheelchairAttributesLeftSide; - private final WheelchairAttributes wheelchairAttributesRightSide; - - private Map> nodeTagsOnWay; - private Map cleanedTags; - - private boolean hasLeftSidewalk = false; - private boolean hasRightSidewalk = false; - private boolean kerbHeightOnlyOnCrossing = false; - - public WheelchairGraphStorageBuilder() { - wheelchairAttributes = new WheelchairAttributes(); - wheelchairAttributesLeftSide = new WheelchairAttributes(); - wheelchairAttributesRightSide = new WheelchairAttributes(); - nodeTagsOnWay = new HashMap<>(); - cleanedTags = new HashMap<>(); - } - - /** - * Constructor - Used for testing - * @param onlyAttachKerbsToCrossings Only attach kerb heights to crossings? - */ - public WheelchairGraphStorageBuilder(boolean onlyAttachKerbsToCrossings) { - this(); - kerbHeightOnlyOnCrossing = onlyAttachKerbsToCrossings; - } - - /** - * Initiate the wheelchair storage builder - * - * @param graphhopper The graphhopper instance to run against - * @return The storage that is created from the builder - * @throws Exception Thrown when the storage has already been initialized - */ - @Override - public GraphExtension init(GraphHopper graphhopper) throws Exception { - if (storage != null) - throw new Exception("GraphStorageBuilder has been already initialized."); - - if(parameters.containsKey("KerbsOnCrossings")) { - kerbHeightOnlyOnCrossing = Boolean.parseBoolean(parameters.get("KerbsOnCrossings")); - } - storage = new WheelchairAttributesGraphStorage(); - return storage; - } - - /** - * Call the processWay method with empty coordinates and tags - * @param way The way to process - */ - @Override - public void processWay(ReaderWay way) { - this.processWay(way, new Coordinate[0], new HashMap<>()); - } - - /** - * Process the way - * - * @param way The way to be processed - * @param coords Coordinates of the way - * @param nodeTags Tags that have been stored on nodes of the way that should be used during processing - */ - @Override - public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) - { - // Start by resetting storage variables after the previous way - wheelchairAttributes.reset(); - wheelchairAttributesLeftSide.reset(); - wheelchairAttributesRightSide.reset(); - hasRightSidewalk = false; - hasLeftSidewalk = false; - - this.nodeTagsOnWay = nodeTags; - - // Annoyingly, it seems often to be the case that rather than using ":" to seperate tag parts, "." is used, so - // we need to take this into account - cleanedTags = cleanTags(way.getTags()); - - // Now we need to process the way specific to whether it is a separate feature (i.e. footway) or is attached - // to a road feature (i.e. with the tag sidewalk=left) - processWayCheckForSeparateFeature(way); - - // We still need to always process the way itself even if it separate so that we can get sidewalk info (a - // separate footway can still have sidewalk tags...) - processSidewalksAttachedToWay(way); - - // the way has known suitability if it can be classified as seperate footway - wheelchairAttributes.setSuitable(isSeparateFootway(way) || way.hasTag("wheelchair_accessible", true)); - - // the sidewalks always imply known suitability - wheelchairAttributesLeftSide.setSuitable(true); - wheelchairAttributesRightSide.setSuitable(true); - - // Process the kerb tags. - processKerbTags(); - } - - /** - * Return the attributes for the sidewalk on the specified side of the road, or the general attributes when NONE is provided - * - * @param side The side of the road you want the data for - * @return The WheelchairAttributes object containing the inofrmation for the specified side - */ - public WheelchairAttributes getStoredAttributes(Side side) { - return switch (side) { - case LEFT -> wheelchairAttributesLeftSide; - case RIGHT -> wheelchairAttributesRightSide; - case NONE -> wheelchairAttributes; - default -> null; - }; - } - - /** - * Go through tags and attempt to remove any invalid keys (i.e. when compound keys have been entered using a '.' rather than ':' - * - * @param dirtyTags The OSM tag collection that needs to be cleaned - * - * @return A cleaned version of the tags on the way (. replaced with : in tag names) - */ - private HashMap cleanTags(Map dirtyTags) { - HashMap cleanedTagsMap = new HashMap<>(); - for(Map.Entry entry : dirtyTags.entrySet()) { - String cleanKey = entry.getKey().replace(".",":"); - cleanedTagsMap.put(cleanKey, entry.getValue()); - } - return cleanedTagsMap; - } - - /** - * Process footways that are attached to an OSM way via the sidewalk tags. It looks for parameters important for - * wheelchair routing such as width, smoothness and kerb height and then stores these in the attributes object - * ready for use when the edge(s) are processed. It also detects which side of the base way that the sidewalks - * have been created for and stores the information appropriately. - * - * @param way The way to be processed - */ - private void processSidewalksAttachedToWay(ReaderWay way) { - - detectAndRecordSidewalkSide(way); - - // get surface type (asphalt, sand etc.) - setSidewalkAttribute(WheelchairAttributes.Attribute.SURFACE); - - // get smoothness value (good, terrible etc.) - setSidewalkAttribute(WheelchairAttributes.Attribute.SMOOTHNESS); - - // Get the track type (grade1, grade4 etc.) - setSidewalkAttribute(WheelchairAttributes.Attribute.TRACK); - - // Get the width of the way (2, 0.1 etc.) - setSidewalkAttribute(WheelchairAttributes.Attribute.WIDTH); - - // Get the incline of the way (10%, 6% etc.) - setSidewalkAttribute(WheelchairAttributes.Attribute.INCLINE); - - } - - /** - * Process a footway that has been stored in OSM as a separate feature, such as a crossing, footpath or pedestrian - * way. The same as the attached processing, it looks for the different attributes as tags that are important for - * wheelchair routing and stores them against the generic wheelchair storage object - */ - private void processWayCheckForSeparateFeature(ReaderWay way) { - boolean markSurfaceQualityKnown = isSeparateFootway(way); - setWayAttribute(WheelchairAttributes.Attribute.SURFACE, markSurfaceQualityKnown); - setWayAttribute(WheelchairAttributes.Attribute.SMOOTHNESS, markSurfaceQualityKnown); - setWayAttribute(WheelchairAttributes.Attribute.TRACK, markSurfaceQualityKnown); - setWayAttribute(WheelchairAttributes.Attribute.WIDTH, markSurfaceQualityKnown); - setWayAttribute(WheelchairAttributes.Attribute.INCLINE, markSurfaceQualityKnown); - } - - /** - * Set the specified attribute in the attribute storage object based on the information gathered from the way. This - * method ony sets the attribute in the attribute storage object for the standalone way and not sidewalks. - * @param attribute The attribute to process - * @param markSurfaceQualityKnown Whether or not to also set the surfaceQualityKnown flag in the WheelchairAttributes object - */ - private void setWayAttribute(WheelchairAttributes.Attribute attribute, boolean markSurfaceQualityKnown) { - if (cleanedTags.containsKey(attributeToTagName(attribute))) { - setWheelchairAttribute((String) cleanedTags.get(attributeToTagName(attribute)), attribute, markSurfaceQualityKnown); - } - } - - /** - * Set teh specified attribute in the attribute storage objects for the left and right sidewalks, - * - * @param attribute The attribute to process - */ - private void setSidewalkAttribute(WheelchairAttributes.Attribute attribute) { - String[] tagValues; - - tagValues = getSidedTagValue(attributeToTagName(attribute)); - - if(tagValues[0] != null && !tagValues[0].isEmpty()) { - setSidewalkAttributeForSide(tagValues[0], attribute, Side.LEFT); - } - if(tagValues[1] != null && !tagValues[1].isEmpty()) { - setSidewalkAttributeForSide(tagValues[1], attribute, Side.RIGHT); - } - } - - /** - * Detect if there are sidewalks stored on the way and if so, mark that these are present - * - * @param way The way to look for sidewalks on - */ - private void detectAndRecordSidewalkSide(ReaderWay way) { - if (way.hasTag("sidewalk")) { - String sw = way.getTag("sidewalk"); - switch (sw) { - case SW_VAL_LEFT -> hasLeftSidewalk = true; - case SW_VAL_RIGHT -> hasRightSidewalk = true; - case KEY_BOTH -> { - hasLeftSidewalk = true; - hasRightSidewalk = true; - } - default -> { - } - } - } - } - - /** - * Convert an attribute from the wheelchair attribute storage to a corresponding osm tag key - * - * @param attribute The attribute that the tag key is required for - * @return The OSM tag key that corresponds to the attribute - */ - private String attributeToTagName(WheelchairAttributes.Attribute attribute) { - return switch (attribute) { - case SURFACE -> "surface"; - case SMOOTHNESS -> "smoothness"; - case TRACK -> "tracktype"; - case WIDTH -> "width"; - case INCLINE -> "incline"; - case KERB -> "kerb"; - default -> ""; - }; - } - - /** - * Set the specified attribute of the specified sidewalk to be the value passed - * - * @param value The value to store - * @param attribute The attribute to store the value against - * @param side The sidewalk the attribute is for - */ - private void setSidewalkAttributeForSide(String value, WheelchairAttributes.Attribute attribute, Side side) { - switch (side) { - case LEFT -> { - hasLeftSidewalk = true; - wheelchairAttributesLeftSide.setAttribute(attribute, convertTagValueToEncodedValue(attribute, value), true); - } - case RIGHT -> { - hasRightSidewalk = true; - wheelchairAttributesRightSide.setAttribute(attribute, convertTagValueToEncodedValue(attribute, value), true); - } - default -> { - } - } - } - - /** - * Set the specified attribute on the standalone way to be the value passed - * - * @param value The value to store - * @param attribute The attribute to store the value against - * @param markSurfaceQualityKnown Whether or not to also set the surfaceQualityKnown flag in the WheelchairAttributes object - */ - private void setWheelchairAttribute(String value, WheelchairAttributes.Attribute attribute, boolean markSurfaceQualityKnown) { - wheelchairAttributes.setAttribute(attribute, convertTagValueToEncodedValue(attribute, value), markSurfaceQualityKnown); - } - - /** - * Transform (if needed) a value into an encoded value using the correct encoder. - * - * @param attribute The attribute the value is for - * @param tagValue The string value stored in the tag - * @return The correctly encoded value - */ - private int convertTagValueToEncodedValue(WheelchairAttributes.Attribute attribute, String tagValue) { - switch(attribute) { - case SMOOTHNESS: - case TRACK: - case SURFACE: try { - return WheelchairTypesEncoder.getEncodedType(attribute, tagValue.toLowerCase()); - } catch (Exception notRecognisedEncodedTypeError) { - return -1; - } - case WIDTH: - return (int)(UnitsConverter.convertOSMDistanceTagToMeters(tagValue.toLowerCase())*100); - case INCLINE: - return getInclineFromTagValue(tagValue.toLowerCase()); - case KERB: - return convertKerbTagValueToCentimetres(tagValue.toLowerCase()); - default: - return -1; - } - } - - /** - * Get the kerb height value from a set of tags. The method takes into account different ways of spelling and representing the kerb height and then adds the kerb information - * to the wheelchair attribute objects - */ - private void processKerbTags() { - String[] assumedKerbTags = new String[] { - "curb", - "kerb", - KEY_SLOPED_CURB, - KEY_SLOPED_KERB - }; - String[] explicitKerbTags = new String[] { - KEY_KERB_HEIGHT, - KEY_CURB_HEIGHT - }; - - int height = calcSingleKerbHeightFromTagList(assumedKerbTags, -1); - // Explicit heights overwrite assumed - height = calcSingleKerbHeightFromTagList(explicitKerbTags, height); - - if (height > -1) { - wheelchairAttributes.setSlopedKerbHeight(height); - } - - // Now for if the values are attached to sides of the way - int[] heights = calcSingleKerbHeightFromSidedTagList(assumedKerbTags, new int[] { -1, -1}); - heights = calcSingleKerbHeightFromSidedTagList(explicitKerbTags, heights); - - if (heights[0] > -1) { - hasLeftSidewalk = true; - wheelchairAttributesLeftSide.setSlopedKerbHeight(heights[0]); - } - - if (heights[1] > -1) { - hasLeftSidewalk = true; - wheelchairAttributesRightSide.setSlopedKerbHeight(heights[1]); - } - } - - /** - * Calculate the kerb height from the way that should be stored on the graph bsaed on the tag keys specified - * - * @param kerbTags The tag keys that should be evaluated - * @param initialValue The initial value for the return. If no kerb height info is found, this value is returned - * @return The value to use as the kerb height derived from the specified tag keys. - */ - private int calcSingleKerbHeightFromTagList(String[] kerbTags, int initialValue) { - int height = initialValue; - for (String kerbTag : kerbTags) { - int kerbHeightValue = convertKerbTagValueToCentimetres((String) cleanedTags.get(kerbTag)); - if (kerbHeightValue != -1) { - height = kerbHeightValue; - } - } - return height; - } - - /** - * Calculate the kerb heights from the way that should be stored on the graph bsaed on the tag keys specified. - * This method looks at the tags which specify a side to the road) - * - * @param kerbTags The tag keys that should be evaluated - * @param initialValues The initial value for the return. If no kerb height info is found, this value is returned - * @return The values to use as the kerb height derived from the specified tag keys. The first item - * in the array is for the left side, and the second is the right side. - */ - private int[] calcSingleKerbHeightFromSidedTagList(String[] kerbTags, int[] initialValues) { - int[] heights = initialValues; - int height = -1; - for (String kerbTag : kerbTags) { - String[] tagValues = getSidedKerbTagValuesToApply(kerbTag); - if(tagValues[0] != null && !tagValues[0].isEmpty()) { - height = convertKerbTagValueToCentimetres(tagValues[0].toLowerCase()); - if (height > -1) { - heights[0] = height; - } - } - if(tagValues[1] != null && !tagValues[1].isEmpty()) { - height = convertKerbTagValueToCentimetres(tagValues[1].toLowerCase()); - if (height > -1) { - heights[1] = height; - } - } - } - - return heights; - } - - /** - * Look at way and try to find the correct kerb heights for it. In some cases when the kerbs are attached directly to a way they are - * marked as start and end and so we need to look through the various tags to try and find these. - * - * @param key The base key that we are investigating (e.g. "kerb", "sloped_kerb" etc.) - * @return The textual tag that should be used as the kerb height - */ - private String[] getSidedKerbTagValuesToApply(String key) { - // If we are looking at the kerbs, sometimes the start and end of a way is marked as having different kerb - // heights using the ...:start and ...:end tags. For now, we just want to get the worse of these values (the - // highest) - double leftStart = -1; - double leftEnd = -1; - double rightStart = -1; - double rightEnd = -1; - - String[] endValues = getSidedTagValue(key + ":end"); - // Convert - if(endValues[0] != null && !endValues[0].isEmpty()) { - leftEnd = convertKerbTagValueToCentimetres(endValues[0]); - } - if(endValues[1] != null && !endValues[1].isEmpty()) { - rightEnd = convertKerbTagValueToCentimetres(endValues[1]); - } - String[] startValues = getSidedTagValue(key + ":start"); - // Convert - if(startValues[0] != null && !startValues[0].isEmpty()) { - leftStart = convertKerbTagValueToCentimetres(startValues[0]); - } - if(startValues[1] != null && !startValues[1].isEmpty()) { - rightStart = convertKerbTagValueToCentimetres(startValues[1]); - } - - // Now compare to find the worst - String[] values = new String[2]; - if(leftEnd > leftStart ) - values[0] = endValues[0]; - else if(leftStart > leftEnd) - values[0] = startValues[0]; - - if(rightEnd > rightStart) - values[1] = endValues[1]; - else if(rightStart > rightEnd) - values[1] = startValues[1]; - - return values; - } - - /** - * Compare the attributes gained for the given property between the sidewalks on the left and the right hand side - * of the feature and identify which is worse. This is useful if for some reason the sidewalks can not be created - * as separate edges from the feature, in which case you would avoid the whole way if an attribute was seen as - * impassible. - * - * @param attr The attribute to be assessed (surface, smoothness etc.) - * - * @return The value that is seen as being the worst - */ - private int getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute attr) { - switch(attr) { - case SURFACE: - return Math.max(Math.max(wheelchairAttributesLeftSide.getSurfaceType(), wheelchairAttributesRightSide.getSurfaceType()), - wheelchairAttributes.getSurfaceType()); - case SMOOTHNESS: - return Math.max(Math.max(wheelchairAttributesLeftSide.getSmoothnessType(), wheelchairAttributesRightSide.getSmoothnessType()), - wheelchairAttributes.getSmoothnessType()); - case KERB: - return Math.max(Math.max(wheelchairAttributesLeftSide.getSlopedKerbHeight(), wheelchairAttributesRightSide.getSlopedKerbHeight()), - wheelchairAttributes.getSlopedKerbHeight()); - case WIDTH: - // default value is 0, but this will always be returned so we need to do a check - int l = wheelchairAttributesLeftSide.getWidth(); - int r = wheelchairAttributesRightSide.getWidth(); - int w = wheelchairAttributes.getWidth(); - if (l <= 0) l = Integer.MAX_VALUE; - if (r <= 0) r = Integer.MAX_VALUE; - if (w <= 0) w = Integer.MAX_VALUE; - - int ret = Math.min(Math.min(l,r),w); - if (ret == Integer.MAX_VALUE) ret = 0; - - return ret; - case TRACK: - return Math.max(Math.max(wheelchairAttributesLeftSide.getTrackType(), wheelchairAttributesRightSide.getTrackType()), - wheelchairAttributes.getTrackType()); - case INCLINE: - return Math.max(Math.max(wheelchairAttributesLeftSide.getIncline(), wheelchairAttributesRightSide.getIncline()), - wheelchairAttributes.getIncline()); - - default: - return 0; - } - } - - /** - * Process an individual edge which has been derived from the way and then store it in the storage. - * - * @param way The parent way feature - * @param edge The specific edge to be processed - */ - @Override - public void processEdge(ReaderWay way, EdgeIteratorState edge) { - // We want to copy so that we don't overwrite original values as this edge is only part of the way - WheelchairAttributes at = wheelchairAttributes.copy(); - - // Get the kerb heights for the individual edge as this may overwrite the original - int kerbHeight = getKerbHeightForEdge(way); - if (kerbHeight > -1) { - at.setSlopedKerbHeight(kerbHeight); - } - - // Check for if we have specified which side the processing is for - if(way.hasTag("ors-sidewalk-side")) { - String side = way.getTag("ors-sidewalk-side"); - if(side.equals(SW_VAL_LEFT)) { - // Only get the attributes for the left side - at = getAttributes(SW_VAL_LEFT); - at.setSide(WheelchairAttributes.Side.LEFT); + public static final String KEY_SLOPED_CURB = "sloped_curb"; + public static final String KEY_SLOPED_KERB = "sloped_kerb"; + public static final String KEY_KERB_HEIGHT = "kerb:height"; + public static final String KEY_FOOTWAY = "footway"; + public static final String SW_VAL_RIGHT = "right"; + public static final String SW_VAL_LEFT = "left"; + public static final String KEY_BOTH = "both"; + public static final String KEY_SIDEWALK_BOTH = "sidewalk:both:"; + public static final String KEY_FOOTWAY_BOTH = "footway:both:"; + public static final String KEY_CURB_HEIGHT = "curb:height"; + + public enum Side { + LEFT, + RIGHT, + NONE + } + + private WheelchairAttributesGraphStorage storage; + private final WheelchairAttributes wheelchairAttributes; + private final WheelchairAttributes wheelchairAttributesLeftSide; + private final WheelchairAttributes wheelchairAttributesRightSide; + + private Map> nodeTagsOnWay; + private Map cleanedTags; + + private boolean hasLeftSidewalk = false; + private boolean hasRightSidewalk = false; + private boolean kerbHeightOnlyOnCrossing = false; + + public WheelchairGraphStorageBuilder() { + wheelchairAttributes = new WheelchairAttributes(); + wheelchairAttributesLeftSide = new WheelchairAttributes(); + wheelchairAttributesRightSide = new WheelchairAttributes(); + nodeTagsOnWay = new HashMap<>(); + cleanedTags = new HashMap<>(); + } + + /** + * Constructor - Used for testing + * + * @param onlyAttachKerbsToCrossings Only attach kerb heights to crossings? + */ + public WheelchairGraphStorageBuilder(boolean onlyAttachKerbsToCrossings) { + this(); + kerbHeightOnlyOnCrossing = onlyAttachKerbsToCrossings; + } + + /** + * Initiate the wheelchair storage builder + * + * @param graphhopper The graphhopper instance to run against + * @throws Exception Thrown when the storage has already been initialized + * @return The storage that is created from the builder + */ + @Override + public GraphExtension init(GraphHopper graphhopper) throws Exception { + if (storage != null) + throw new Exception("GraphStorageBuilder has been already initialized."); + + if (parameters.containsKey("KerbsOnCrossings")) { + kerbHeightOnlyOnCrossing = Boolean.parseBoolean(parameters.get("KerbsOnCrossings")); + } + storage = new WheelchairAttributesGraphStorage(); + return storage; + } + + /** + * Call the processWay method with empty coordinates and tags + * + * @param way The way to process + */ + @Override + public void processWay(ReaderWay way) { + this.processWay(way, new Coordinate[0], new HashMap<>()); + } + + /** + * Process the way + * + * @param way The way to be processed + * @param coords Coordinates of the way + * @param nodeTags Tags that have been stored on nodes of the way that should be used during processing + */ + @Override + public void processWay(ReaderWay way, Coordinate[] coords, Map> nodeTags) { + // Start by resetting storage variables after the previous way + wheelchairAttributes.reset(); + wheelchairAttributesLeftSide.reset(); + wheelchairAttributesRightSide.reset(); + hasRightSidewalk = false; + hasLeftSidewalk = false; + + this.nodeTagsOnWay = nodeTags; + + // Annoyingly, it seems often to be the case that rather than using ":" to seperate tag parts, "." is used, so + // we need to take this into account + cleanedTags = cleanTags(way.getTags()); + + // Now we need to process the way specific to whether it is a separate feature (i.e. footway) or is attached + // to a road feature (i.e. with the tag sidewalk=left) + processWayCheckForSeparateFeature(way); + + // We still need to always process the way itself even if it separate so that we can get sidewalk info (a + // separate footway can still have sidewalk tags...) + processSidewalksAttachedToWay(way); + + // the way has known suitability if it can be classified as seperate footway + wheelchairAttributes.setSuitable(isSeparateFootway(way) || way.hasTag("wheelchair_accessible", true)); + + // the sidewalks always imply known suitability + wheelchairAttributesLeftSide.setSuitable(true); + wheelchairAttributesRightSide.setSuitable(true); + + // Process the kerb tags. + processKerbTags(); + } + + /** + * Return the attributes for the sidewalk on the specified side of the road, or the general attributes when NONE is provided + * + * @param side The side of the road you want the data for + * @return The WheelchairAttributes object containing the inofrmation for the specified side + */ + public WheelchairAttributes getStoredAttributes(Side side) { + return switch (side) { + case LEFT -> wheelchairAttributesLeftSide; + case RIGHT -> wheelchairAttributesRightSide; + case NONE -> wheelchairAttributes; + default -> null; + }; + } + + /** + * Go through tags and attempt to remove any invalid keys (i.e. when compound keys have been entered using a '.' rather than ':' + * + * @param dirtyTags The OSM tag collection that needs to be cleaned + * @return A cleaned version of the tags on the way (. replaced with : in tag names) + */ + private HashMap cleanTags(Map dirtyTags) { + HashMap cleanedTagsMap = new HashMap<>(); + for (Map.Entry entry : dirtyTags.entrySet()) { + String cleanKey = entry.getKey().replace(".", ":"); + cleanedTagsMap.put(cleanKey, entry.getValue()); + } + return cleanedTagsMap; + } + + /** + * Process footways that are attached to an OSM way via the sidewalk tags. It looks for parameters important for + * wheelchair routing such as width, smoothness and kerb height and then stores these in the attributes object + * ready for use when the edge(s) are processed. It also detects which side of the base way that the sidewalks + * have been created for and stores the information appropriately. + * + * @param way The way to be processed + */ + private void processSidewalksAttachedToWay(ReaderWay way) { + + detectAndRecordSidewalkSide(way); + + // get surface type (asphalt, sand etc.) + setSidewalkAttribute(WheelchairAttributes.Attribute.SURFACE); + + // get smoothness value (good, terrible etc.) + setSidewalkAttribute(WheelchairAttributes.Attribute.SMOOTHNESS); + + // Get the track type (grade1, grade4 etc.) + setSidewalkAttribute(WheelchairAttributes.Attribute.TRACK); + + // Get the width of the way (2, 0.1 etc.) + setSidewalkAttribute(WheelchairAttributes.Attribute.WIDTH); + + // Get the incline of the way (10%, 6% etc.) + setSidewalkAttribute(WheelchairAttributes.Attribute.INCLINE); + + } + + /** + * Process a footway that has been stored in OSM as a separate feature, such as a crossing, footpath or pedestrian + * way. The same as the attached processing, it looks for the different attributes as tags that are important for + * wheelchair routing and stores them against the generic wheelchair storage object + */ + private void processWayCheckForSeparateFeature(ReaderWay way) { + boolean markSurfaceQualityKnown = isSeparateFootway(way); + setWayAttribute(WheelchairAttributes.Attribute.SURFACE, markSurfaceQualityKnown); + setWayAttribute(WheelchairAttributes.Attribute.SMOOTHNESS, markSurfaceQualityKnown); + setWayAttribute(WheelchairAttributes.Attribute.TRACK, markSurfaceQualityKnown); + setWayAttribute(WheelchairAttributes.Attribute.WIDTH, markSurfaceQualityKnown); + setWayAttribute(WheelchairAttributes.Attribute.INCLINE, markSurfaceQualityKnown); + } + + /** + * Set the specified attribute in the attribute storage object based on the information gathered from the way. This + * method ony sets the attribute in the attribute storage object for the standalone way and not sidewalks. + * + * @param attribute The attribute to process + * @param markSurfaceQualityKnown Whether or not to also set the surfaceQualityKnown flag in the WheelchairAttributes object + */ + private void setWayAttribute(WheelchairAttributes.Attribute attribute, boolean markSurfaceQualityKnown) { + if (cleanedTags.containsKey(attributeToTagName(attribute))) { + setWheelchairAttribute((String) cleanedTags.get(attributeToTagName(attribute)), attribute, markSurfaceQualityKnown); + } + } + + /** + * Set teh specified attribute in the attribute storage objects for the left and right sidewalks, + * + * @param attribute The attribute to process + */ + private void setSidewalkAttribute(WheelchairAttributes.Attribute attribute) { + String[] tagValues; + + tagValues = getSidedTagValue(attributeToTagName(attribute)); + + if (tagValues[0] != null && !tagValues[0].isEmpty()) { + setSidewalkAttributeForSide(tagValues[0], attribute, Side.LEFT); + } + if (tagValues[1] != null && !tagValues[1].isEmpty()) { + setSidewalkAttributeForSide(tagValues[1], attribute, Side.RIGHT); + } + } + + /** + * Detect if there are sidewalks stored on the way and if so, mark that these are present + * + * @param way The way to look for sidewalks on + */ + private void detectAndRecordSidewalkSide(ReaderWay way) { + if (way.hasTag("sidewalk")) { + String sw = way.getTag("sidewalk"); + switch (sw) { + case SW_VAL_LEFT -> hasLeftSidewalk = true; + case SW_VAL_RIGHT -> hasRightSidewalk = true; + case KEY_BOTH -> { + hasLeftSidewalk = true; + hasRightSidewalk = true; + } + default -> { + } + } + } + } + + /** + * Convert an attribute from the wheelchair attribute storage to a corresponding osm tag key + * + * @param attribute The attribute that the tag key is required for + * @return The OSM tag key that corresponds to the attribute + */ + private String attributeToTagName(WheelchairAttributes.Attribute attribute) { + return switch (attribute) { + case SURFACE -> "surface"; + case SMOOTHNESS -> "smoothness"; + case TRACK -> "tracktype"; + case WIDTH -> "width"; + case INCLINE -> "incline"; + case KERB -> "kerb"; + default -> ""; + }; + } + + /** + * Set the specified attribute of the specified sidewalk to be the value passed + * + * @param value The value to store + * @param attribute The attribute to store the value against + * @param side The sidewalk the attribute is for + */ + private void setSidewalkAttributeForSide(String value, WheelchairAttributes.Attribute attribute, Side side) { + switch (side) { + case LEFT -> { + hasLeftSidewalk = true; + wheelchairAttributesLeftSide.setAttribute(attribute, convertTagValueToEncodedValue(attribute, value), true); + } + case RIGHT -> { + hasRightSidewalk = true; + wheelchairAttributesRightSide.setAttribute(attribute, convertTagValueToEncodedValue(attribute, value), true); + } + default -> { + } + } + } + + /** + * Set the specified attribute on the standalone way to be the value passed + * + * @param value The value to store + * @param attribute The attribute to store the value against + * @param markSurfaceQualityKnown Whether or not to also set the surfaceQualityKnown flag in the WheelchairAttributes object + */ + private void setWheelchairAttribute(String value, WheelchairAttributes.Attribute attribute, boolean markSurfaceQualityKnown) { + wheelchairAttributes.setAttribute(attribute, convertTagValueToEncodedValue(attribute, value), markSurfaceQualityKnown); + } + + /** + * Transform (if needed) a value into an encoded value using the correct encoder. + * + * @param attribute The attribute the value is for + * @param tagValue The string value stored in the tag + * @return The correctly encoded value + */ + private int convertTagValueToEncodedValue(WheelchairAttributes.Attribute attribute, String tagValue) { + switch (attribute) { + case SMOOTHNESS: + case TRACK: + case SURFACE: + try { + return WheelchairTypesEncoder.getEncodedType(attribute, tagValue.toLowerCase()); + } catch (Exception notRecognisedEncodedTypeError) { + return -1; + } + case WIDTH: + return (int) (UnitsConverter.convertOSMDistanceTagToMeters(tagValue.toLowerCase()) * 100); + case INCLINE: + return getInclineFromTagValue(tagValue.toLowerCase()); + case KERB: + return convertKerbTagValueToCentimetres(tagValue.toLowerCase()); + default: + return -1; + } + } + + /** + * Get the kerb height value from a set of tags. The method takes into account different ways of spelling and representing the kerb height and then adds the kerb information + * to the wheelchair attribute objects + */ + private void processKerbTags() { + String[] assumedKerbTags = new String[]{ + "curb", + "kerb", + KEY_SLOPED_CURB, + KEY_SLOPED_KERB + }; + String[] explicitKerbTags = new String[]{ + KEY_KERB_HEIGHT, + KEY_CURB_HEIGHT + }; + + int height = calcSingleKerbHeightFromTagList(assumedKerbTags, -1); + // Explicit heights overwrite assumed + height = calcSingleKerbHeightFromTagList(explicitKerbTags, height); + + if (height > -1) { + wheelchairAttributes.setSlopedKerbHeight(height); + } + + // Now for if the values are attached to sides of the way + int[] heights = calcSingleKerbHeightFromSidedTagList(assumedKerbTags, new int[]{-1, -1}); + heights = calcSingleKerbHeightFromSidedTagList(explicitKerbTags, heights); + + if (heights[0] > -1) { + hasLeftSidewalk = true; + wheelchairAttributesLeftSide.setSlopedKerbHeight(heights[0]); + } + + if (heights[1] > -1) { + hasLeftSidewalk = true; + wheelchairAttributesRightSide.setSlopedKerbHeight(heights[1]); + } + } + + /** + * Calculate the kerb height from the way that should be stored on the graph bsaed on the tag keys specified + * + * @param kerbTags The tag keys that should be evaluated + * @param initialValue The initial value for the return. If no kerb height info is found, this value is returned + * @return The value to use as the kerb height derived from the specified tag keys. + */ + private int calcSingleKerbHeightFromTagList(String[] kerbTags, int initialValue) { + int height = initialValue; + for (String kerbTag : kerbTags) { + int kerbHeightValue = convertKerbTagValueToCentimetres((String) cleanedTags.get(kerbTag)); + if (kerbHeightValue != -1) { + height = kerbHeightValue; + } + } + return height; + } + + /** + * Calculate the kerb heights from the way that should be stored on the graph bsaed on the tag keys specified. + * This method looks at the tags which specify a side to the road) + * + * @param kerbTags The tag keys that should be evaluated + * @param initialValues The initial value for the return. If no kerb height info is found, this value is returned + * @return The values to use as the kerb height derived from the specified tag keys. The first item + * in the array is for the left side, and the second is the right side. + */ + private int[] calcSingleKerbHeightFromSidedTagList(String[] kerbTags, int[] initialValues) { + int[] heights = initialValues; + int height = -1; + for (String kerbTag : kerbTags) { + String[] tagValues = getSidedKerbTagValuesToApply(kerbTag); + if (tagValues[0] != null && !tagValues[0].isEmpty()) { + height = convertKerbTagValueToCentimetres(tagValues[0].toLowerCase()); + if (height > -1) { + heights[0] = height; + } + } + if (tagValues[1] != null && !tagValues[1].isEmpty()) { + height = convertKerbTagValueToCentimetres(tagValues[1].toLowerCase()); + if (height > -1) { + heights[1] = height; + } + } + } + + return heights; + } + + /** + * Look at way and try to find the correct kerb heights for it. In some cases when the kerbs are attached directly to a way they are + * marked as start and end and so we need to look through the various tags to try and find these. + * + * @param key The base key that we are investigating (e.g. "kerb", "sloped_kerb" etc.) + * @return The textual tag that should be used as the kerb height + */ + private String[] getSidedKerbTagValuesToApply(String key) { + // If we are looking at the kerbs, sometimes the start and end of a way is marked as having different kerb + // heights using the ...:start and ...:end tags. For now, we just want to get the worse of these values (the + // highest) + double leftStart = -1; + double leftEnd = -1; + double rightStart = -1; + double rightEnd = -1; + + String[] endValues = getSidedTagValue(key + ":end"); + // Convert + if (endValues[0] != null && !endValues[0].isEmpty()) { + leftEnd = convertKerbTagValueToCentimetres(endValues[0]); + } + if (endValues[1] != null && !endValues[1].isEmpty()) { + rightEnd = convertKerbTagValueToCentimetres(endValues[1]); + } + String[] startValues = getSidedTagValue(key + ":start"); + // Convert + if (startValues[0] != null && !startValues[0].isEmpty()) { + leftStart = convertKerbTagValueToCentimetres(startValues[0]); + } + if (startValues[1] != null && !startValues[1].isEmpty()) { + rightStart = convertKerbTagValueToCentimetres(startValues[1]); + } + + // Now compare to find the worst + String[] values = new String[2]; + if (leftEnd > leftStart) + values[0] = endValues[0]; + else if (leftStart > leftEnd) + values[0] = startValues[0]; + + if (rightEnd > rightStart) + values[1] = endValues[1]; + else if (rightStart > rightEnd) + values[1] = startValues[1]; + + return values; + } + + /** + * Compare the attributes gained for the given property between the sidewalks on the left and the right hand side + * of the feature and identify which is worse. This is useful if for some reason the sidewalks can not be created + * as separate edges from the feature, in which case you would avoid the whole way if an attribute was seen as + * impassible. + * + * @param attr The attribute to be assessed (surface, smoothness etc.) + * @return The value that is seen as being the worst + */ + private int getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute attr) { + switch (attr) { + case SURFACE: + return Math.max(Math.max(wheelchairAttributesLeftSide.getSurfaceType(), wheelchairAttributesRightSide.getSurfaceType()), + wheelchairAttributes.getSurfaceType()); + case SMOOTHNESS: + return Math.max(Math.max(wheelchairAttributesLeftSide.getSmoothnessType(), wheelchairAttributesRightSide.getSmoothnessType()), + wheelchairAttributes.getSmoothnessType()); + case KERB: + return Math.max(Math.max(wheelchairAttributesLeftSide.getSlopedKerbHeight(), wheelchairAttributesRightSide.getSlopedKerbHeight()), + wheelchairAttributes.getSlopedKerbHeight()); + case WIDTH: + // default value is 0, but this will always be returned so we need to do a check + int l = wheelchairAttributesLeftSide.getWidth(); + int r = wheelchairAttributesRightSide.getWidth(); + int w = wheelchairAttributes.getWidth(); + if (l <= 0) l = Integer.MAX_VALUE; + if (r <= 0) r = Integer.MAX_VALUE; + if (w <= 0) w = Integer.MAX_VALUE; + + int ret = Math.min(Math.min(l, r), w); + if (ret == Integer.MAX_VALUE) ret = 0; + + return ret; + case TRACK: + return Math.max(Math.max(wheelchairAttributesLeftSide.getTrackType(), wheelchairAttributesRightSide.getTrackType()), + wheelchairAttributes.getTrackType()); + case INCLINE: + return Math.max(Math.max(wheelchairAttributesLeftSide.getIncline(), wheelchairAttributesRightSide.getIncline()), + wheelchairAttributes.getIncline()); + + default: + return 0; + } + } + + /** + * Process an individual edge which has been derived from the way and then store it in the storage. + * + * @param way The parent way feature + * @param edge The specific edge to be processed + */ + @Override + public void processEdge(ReaderWay way, EdgeIteratorState edge) { + // We want to copy so that we don't overwrite original values as this edge is only part of the way + WheelchairAttributes at = wheelchairAttributes.copy(); + + // Get the kerb heights for the individual edge as this may overwrite the original + int kerbHeight = getKerbHeightForEdge(way); + if (kerbHeight > -1) { + at.setSlopedKerbHeight(kerbHeight); + } + + // Check for if we have specified which side the processing is for + if (way.hasTag("ors-sidewalk-side")) { + String side = way.getTag("ors-sidewalk-side"); + if (side.equals(SW_VAL_LEFT)) { + // Only get the attributes for the left side + at = getAttributes(SW_VAL_LEFT); + at.setSide(WheelchairAttributes.Side.LEFT); + } + if (side.equals(SW_VAL_RIGHT)) { + at = getAttributes(SW_VAL_RIGHT); + at.setSide(WheelchairAttributes.Side.RIGHT); } - if(side.equals(SW_VAL_RIGHT)) { - at = getAttributes(SW_VAL_RIGHT); - at.setSide(WheelchairAttributes.Side.RIGHT); - } } else { - // if we have sidewalks attached, then we should also look at those. We should only hit this point if - // the preprocessing hasn't detected that there are sidewalks even though there are... - if (hasRightSidewalk || hasLeftSidewalk) { - at = combineAttributesOfWayWhenBothSidesPresent(at); - } - } - - storage.setEdgeValues(edge.getEdge(), at); - - } - - /** - * Get an overriding kerb height if needed from the nodes that are on the way rather than the data stored on the way itself. - * This should be the case if we are specifying to only store kerb heights on crossings as these features do not normally - * have kerb heights attached to them - * - * @param way The way that is being investigated - * @return A kerb height from the tags of the nodes on the way, or -1 if no kerb heights are found/required - */ - int getKerbHeightForEdge(ReaderWay way) { - int kerbHeight = -1; - - if(!kerbHeightOnlyOnCrossing || (way.hasTag(KEY_FOOTWAY) && way.getTag(KEY_FOOTWAY).equals("crossing"))) { - // Look for kerb information - kerbHeight = getKerbHeightFromNodeTags(); - } - - return kerbHeight; - } - - /** - * Look at the information stored against the nodes of the way and extract the kerb height to use for the whole way - * from those data. - * - * @return The derived kerb height in centimetres from teh nodes that are on the way - */ - int getKerbHeightFromNodeTags() { - // Assumed kerb heights are those obtained from a tag without the explicit :height attribute - List assumedKerbHeights = new ArrayList<>(); - // Explicit heights are those provided by the :height tag - these should take precidence - List explicitKerbHeights = new ArrayList<>(); - - for(Map.Entry> entry: nodeTagsOnWay.entrySet()) { - Map tags = entry.getValue(); - for (Map.Entry tag : tags.entrySet()) { - switch (tag.getKey()) { - case KEY_SLOPED_CURB, "curb", "kerb", KEY_SLOPED_KERB -> - assumedKerbHeights.add(convertKerbTagValueToCentimetres(tag.getValue())); - case KEY_KERB_HEIGHT -> explicitKerbHeights.add(convertKerbTagValueToCentimetres(tag.getValue())); - default -> { - } - } - } - } - if (!explicitKerbHeights.isEmpty()) { - return Collections.max(explicitKerbHeights); - } else if(!assumedKerbHeights.isEmpty()) { - // If we have multiple kerb heights, we need to apply the largest to the edge as this is the worst - return Collections.max(assumedKerbHeights); - } else { - return -1; - } - } - - /** - * When sidewalks are tagged on both sides for a way and we do not want to process them as separate items then we need - * to get the "worst" for each attribute and use that. - * - * @param attributes The attributes storage object that needs to be merged - * @return A resultant combined object - */ - public WheelchairAttributes combineAttributesOfWayWhenBothSidesPresent(WheelchairAttributes attributes) { - WheelchairAttributes at = attributes; - - int tr = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.TRACK); - if (tr > 0) at.setTrackType(tr); - - int su = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.SURFACE); - if (su > 0) at.setSurfaceType(su); - - int sm = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.SMOOTHNESS); - if (sm > 0) at.setSmoothnessType(sm); - - int sl = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.KERB); - if (sl > 0) at.setSlopedKerbHeight(sl); - - int wi = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.WIDTH); - if (wi > 0) at.setWidth(wi); - - int in = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.INCLINE); - if (in > 0) at.setIncline(in); - - at.setSurfaceQualityKnown( - wheelchairAttributesLeftSide.isSurfaceQualityKnown() - && wheelchairAttributesRightSide.isSurfaceQualityKnown() - && attributes.isSurfaceQualityKnown() - ); - - at.setSuitable( - wheelchairAttributesLeftSide.isSuitable() - && wheelchairAttributesRightSide.isSuitable() - && attributes.isSuitable() - ); - - return at; - } - - /** - * Get the attributes of a sidewalk on the specified side of the road - * - * @param side The side you want the attributes for - * - * @return A WheelchairAttributes object for the side requested. If there are no attributes for the specified - * side, then the overall attributes for the way are returned - */ - private WheelchairAttributes getAttributes(String side) { - WheelchairAttributes at = wheelchairAttributes.copy(); - - // Now get the specific items - switch (side) { - case SW_VAL_LEFT -> at = at.merge(wheelchairAttributesLeftSide); - case SW_VAL_RIGHT -> at = at.merge(wheelchairAttributesRightSide); - default -> { - } - } - return at; - } - - /** - * Converts a kerb height value to a numerical height (in centimetres). A kerb could be stored as an explicit height or - * as an indicator as to whether the kerb is lowered or not. - * - * @param value The value of the tag - * @return The presumed height of the kerb in metres - */ - private int convertKerbTagValueToCentimetres(String value) { - int centimetreHeight = -1; - - if (value == null) { - return -1; - } - switch (value) { - case "yes", KEY_BOTH, "low", "lowered", "dropped", "sloped" -> centimetreHeight = 3; - case "no", "none", "one", "rolled", "regular" -> centimetreHeight = 15; - case "at_grade", "flush" -> centimetreHeight = 0; - default -> { - double metresHeight = UnitsConverter.convertOSMDistanceTagToMeters(value); - // If no unit was given in the tag, the value might be in meters or centimeters; we can only guess - // depending on the value - if (metresHeight < 0.15) { - centimetreHeight = (int) (metresHeight * 100); - } else { - centimetreHeight = (int) metresHeight; - } - } - } - - return centimetreHeight; - } - - /** - * Get the values obtained from a way for a specific sidewalk property. For example, providing the property - * "surface" would check the way for the surface tag stored against attached sidewalks using the keys - * sidewalk:left:surface, sidewalk:right:surface, and sidewalk:both:surface. The obtained values are then returned - * in an array. - * - * @param property The property to be extracted - * - * @return A String array containing two values - the first is the property for the left sidewalk and - * the second is the property value for the right sidewalk. - */ - private String[] getSidedTagValue(String property) { - String[] values = new String[2]; - // Left side - if(cleanedTags.containsKey("sidewalk:left:" + property)) - values[0] = (String) cleanedTags.get("sidewalk:left:" + property); - else if(cleanedTags.containsKey("footway:left:" +property)) - values[0] = (String) cleanedTags.get("footway:left:" + property); - // Right side - if(cleanedTags.containsKey("sidewalk:right:" + property)) - values[1] = (String) cleanedTags.get("sidewalk:right:" + property); - else if(cleanedTags.containsKey("footway:right:" +property)) - values[1] = (String) cleanedTags.get("footway:right:" + property); - - // Both - if(cleanedTags.containsKey(KEY_SIDEWALK_BOTH + property)) { - values[0] = (String) cleanedTags.get(KEY_SIDEWALK_BOTH + property); - values[1] = (String) cleanedTags.get(KEY_SIDEWALK_BOTH + property); - } - else if(cleanedTags.containsKey(KEY_FOOTWAY_BOTH +property)) { - values[0] = (String) cleanedTags.get(KEY_FOOTWAY_BOTH + property); - values[1] = (String) cleanedTags.get(KEY_FOOTWAY_BOTH + property); - } - return values; - } - - private int getInclineFromTagValue(String inclineValue) { - double decimalIncline = UnitsConverter.convertOSMInclineValueToPercentage(inclineValue, true); - decimalIncline = Math.min(decimalIncline, 15.0); - return (int) Math.round(decimalIncline); - } - - - /** - * Determine if the way is a separate footway object or a road feature. - * - * @param way The OSM way object to be assessed - * @return Whether the way is seen as a separately drawn footway (true) or a road (false) - */ - private boolean isSeparateFootway(ReaderWay way) { - String type = way.getTag("highway", ""); - - String[] pedestrianWayTypes = { - "living_street", - "pedestrian", - KEY_FOOTWAY, - "path", - "crossing", - "track" - }; - - // Check if it is a footpath or pedestrian - if(!type.isEmpty()) { - // We are looking at a separate footpath - // we are looking at a road feature so any footway would be attached to it as a tag - return Arrays.asList(pedestrianWayTypes).contains(type); - } - - return true; - } - - @Override - public String getName() { - return "Wheelchair"; - } + // if we have sidewalks attached, then we should also look at those. We should only hit this point if + // the preprocessing hasn't detected that there are sidewalks even though there are... + if (hasRightSidewalk || hasLeftSidewalk) { + at = combineAttributesOfWayWhenBothSidesPresent(at); + } + } + + storage.setEdgeValues(edge.getEdge(), at); + + } + + /** + * Get an overriding kerb height if needed from the nodes that are on the way rather than the data stored on the way itself. + * This should be the case if we are specifying to only store kerb heights on crossings as these features do not normally + * have kerb heights attached to them + * + * @param way The way that is being investigated + * @return A kerb height from the tags of the nodes on the way, or -1 if no kerb heights are found/required + */ + int getKerbHeightForEdge(ReaderWay way) { + int kerbHeight = -1; + + if (!kerbHeightOnlyOnCrossing || (way.hasTag(KEY_FOOTWAY) && way.getTag(KEY_FOOTWAY).equals("crossing"))) { + // Look for kerb information + kerbHeight = getKerbHeightFromNodeTags(); + } + + return kerbHeight; + } + + /** + * Look at the information stored against the nodes of the way and extract the kerb height to use for the whole way + * from those data. + * + * @return The derived kerb height in centimetres from teh nodes that are on the way + */ + int getKerbHeightFromNodeTags() { + // Assumed kerb heights are those obtained from a tag without the explicit :height attribute + List assumedKerbHeights = new ArrayList<>(); + // Explicit heights are those provided by the :height tag - these should take precidence + List explicitKerbHeights = new ArrayList<>(); + + for (Map.Entry> entry : nodeTagsOnWay.entrySet()) { + Map tags = entry.getValue(); + for (Map.Entry tag : tags.entrySet()) { + switch (tag.getKey()) { + case KEY_SLOPED_CURB, "curb", "kerb", KEY_SLOPED_KERB -> + assumedKerbHeights.add(convertKerbTagValueToCentimetres(tag.getValue())); + case KEY_KERB_HEIGHT -> explicitKerbHeights.add(convertKerbTagValueToCentimetres(tag.getValue())); + default -> { + } + } + } + } + if (!explicitKerbHeights.isEmpty()) { + return Collections.max(explicitKerbHeights); + } else if (!assumedKerbHeights.isEmpty()) { + // If we have multiple kerb heights, we need to apply the largest to the edge as this is the worst + return Collections.max(assumedKerbHeights); + } else { + return -1; + } + } + + /** + * When sidewalks are tagged on both sides for a way and we do not want to process them as separate items then we need + * to get the "worst" for each attribute and use that. + * + * @param attributes The attributes storage object that needs to be merged + * @return A resultant combined object + */ + public WheelchairAttributes combineAttributesOfWayWhenBothSidesPresent(WheelchairAttributes attributes) { + WheelchairAttributes at = attributes; + + int tr = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.TRACK); + if (tr > 0) at.setTrackType(tr); + + int su = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.SURFACE); + if (su > 0) at.setSurfaceType(su); + + int sm = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.SMOOTHNESS); + if (sm > 0) at.setSmoothnessType(sm); + + int sl = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.KERB); + if (sl > 0) at.setSlopedKerbHeight(sl); + + int wi = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.WIDTH); + if (wi > 0) at.setWidth(wi); + + int in = getWorseAttributeValueFromSeparateItems(WheelchairAttributes.Attribute.INCLINE); + if (in > 0) at.setIncline(in); + + at.setSurfaceQualityKnown( + wheelchairAttributesLeftSide.isSurfaceQualityKnown() + && wheelchairAttributesRightSide.isSurfaceQualityKnown() + && attributes.isSurfaceQualityKnown() + ); + + at.setSuitable( + wheelchairAttributesLeftSide.isSuitable() + && wheelchairAttributesRightSide.isSuitable() + && attributes.isSuitable() + ); + + return at; + } + + /** + * Get the attributes of a sidewalk on the specified side of the road + * + * @param side The side you want the attributes for + * @return A WheelchairAttributes object for the side requested. If there are no attributes for the specified + * side, then the overall attributes for the way are returned + */ + private WheelchairAttributes getAttributes(String side) { + WheelchairAttributes at = wheelchairAttributes.copy(); + + // Now get the specific items + switch (side) { + case SW_VAL_LEFT -> at = at.merge(wheelchairAttributesLeftSide); + case SW_VAL_RIGHT -> at = at.merge(wheelchairAttributesRightSide); + default -> { + } + } + return at; + } + + /** + * Converts a kerb height value to a numerical height (in centimetres). A kerb could be stored as an explicit height or + * as an indicator as to whether the kerb is lowered or not. + * + * @param value The value of the tag + * @return The presumed height of the kerb in metres + */ + private int convertKerbTagValueToCentimetres(String value) { + int centimetreHeight = -1; + + if (value == null) { + return -1; + } + switch (value) { + case "yes", KEY_BOTH, "low", "lowered", "dropped", "sloped" -> centimetreHeight = 3; + case "no", "none", "one", "rolled", "regular" -> centimetreHeight = 15; + case "at_grade", "flush" -> centimetreHeight = 0; + default -> { + double metresHeight = UnitsConverter.convertOSMDistanceTagToMeters(value); + // If no unit was given in the tag, the value might be in meters or centimeters; we can only guess + // depending on the value + if (metresHeight < 0.15) { + centimetreHeight = (int) (metresHeight * 100); + } else { + centimetreHeight = (int) metresHeight; + } + } + } + + return centimetreHeight; + } + + /** + * Get the values obtained from a way for a specific sidewalk property. For example, providing the property + * "surface" would check the way for the surface tag stored against attached sidewalks using the keys + * sidewalk:left:surface, sidewalk:right:surface, and sidewalk:both:surface. The obtained values are then returned + * in an array. + * + * @param property The property to be extracted + * @return A String array containing two values - the first is the property for the left sidewalk and + * the second is the property value for the right sidewalk. + */ + private String[] getSidedTagValue(String property) { + String[] values = new String[2]; + // Left side + if (cleanedTags.containsKey("sidewalk:left:" + property)) + values[0] = (String) cleanedTags.get("sidewalk:left:" + property); + else if (cleanedTags.containsKey("footway:left:" + property)) + values[0] = (String) cleanedTags.get("footway:left:" + property); + // Right side + if (cleanedTags.containsKey("sidewalk:right:" + property)) + values[1] = (String) cleanedTags.get("sidewalk:right:" + property); + else if (cleanedTags.containsKey("footway:right:" + property)) + values[1] = (String) cleanedTags.get("footway:right:" + property); + + // Both + if (cleanedTags.containsKey(KEY_SIDEWALK_BOTH + property)) { + values[0] = (String) cleanedTags.get(KEY_SIDEWALK_BOTH + property); + values[1] = (String) cleanedTags.get(KEY_SIDEWALK_BOTH + property); + } else if (cleanedTags.containsKey(KEY_FOOTWAY_BOTH + property)) { + values[0] = (String) cleanedTags.get(KEY_FOOTWAY_BOTH + property); + values[1] = (String) cleanedTags.get(KEY_FOOTWAY_BOTH + property); + } + return values; + } + + private int getInclineFromTagValue(String inclineValue) { + double decimalIncline = UnitsConverter.convertOSMInclineValueToPercentage(inclineValue, true); + decimalIncline = Math.min(decimalIncline, 15.0); + return (int) Math.round(decimalIncline); + } + + + /** + * Determine if the way is a separate footway object or a road feature. + * + * @param way The OSM way object to be assessed + * @return Whether the way is seen as a separately drawn footway (true) or a road (false) + */ + private boolean isSeparateFootway(ReaderWay way) { + String type = way.getTag("highway", ""); + + String[] pedestrianWayTypes = { + "living_street", + "pedestrian", + KEY_FOOTWAY, + "path", + "crossing", + "track" + }; + + // Check if it is a footpath or pedestrian + if (!type.isEmpty()) { + // We are looking at a separate footpath + // we are looking at a road feature so any footway would be attached to it as a tag + return Arrays.asList(pedestrianWayTypes).contains(type); + } + + return true; + } + + @Override + public String getName() { + return "Wheelchair"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtils.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtils.java index 6e6fe4897b..1db8602ace 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtils.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtils.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.util; @@ -17,39 +17,40 @@ import java.nio.ByteBuffer; public class EncodeUtils { - private EncodeUtils() {} - - /** - * Takes a long value and converts it into a byte array of size 8. - * - * @param longValue - * @return An 8 long byte array representation of the long number - */ - public static byte[] longToByteArray(long longValue) { - ByteBuffer longToByteBuffer = ByteBuffer.allocate(Long.BYTES); - longToByteBuffer.putLong(longValue); - return longToByteBuffer.array(); - } - - /** - * Takes a byte array and converts it to a long value representation - * - * @param byteArray - * @return The long number representation of the bytes - */ - public static long byteArrayToLong(byte[] byteArray) { - ByteBuffer byteToLongBuffer = ByteBuffer.allocate(Long.BYTES); - // Need to make up to the needed 8 bytes - byte[] storageBytes = {0,0,0,0,0,0,0,0}; - int differenceInSize = storageBytes.length - byteArray.length; - - for(int i = byteArray.length-1; i >= 0; i--) { - if(differenceInSize + i >= 0) - storageBytes[differenceInSize + i] = byteArray[i]; - } - - byteToLongBuffer.put(storageBytes); - ((Buffer)byteToLongBuffer).flip(); // Changes in Java 9 make the cast to Buffer necessary - return byteToLongBuffer.getLong(); - } + private EncodeUtils() { + } + + /** + * Takes a long value and converts it into a byte array of size 8. + * + * @param longValue + * @return An 8 long byte array representation of the long number + */ + public static byte[] longToByteArray(long longValue) { + ByteBuffer longToByteBuffer = ByteBuffer.allocate(Long.BYTES); + longToByteBuffer.putLong(longValue); + return longToByteBuffer.array(); + } + + /** + * Takes a byte array and converts it to a long value representation + * + * @param byteArray + * @return The long number representation of the bytes + */ + public static long byteArrayToLong(byte[] byteArray) { + ByteBuffer byteToLongBuffer = ByteBuffer.allocate(Long.BYTES); + // Need to make up to the needed 8 bytes + byte[] storageBytes = {0, 0, 0, 0, 0, 0, 0, 0}; + int differenceInSize = storageBytes.length - byteArray.length; + + for (int i = byteArray.length - 1; i >= 0; i--) { + if (differenceInSize + i >= 0) + storageBytes[differenceInSize + i] = byteArray[i]; + } + + byteToLongBuffer.put(storageBytes); + ((Buffer) byteToLongBuffer).flip(); // Changes in Java 9 make the cast to Buffer necessary + return byteToLongBuffer.getLong(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/MultiSourceStoppingCriterion.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/MultiSourceStoppingCriterion.java index 1966bad0c9..f9364b5ede 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/MultiSourceStoppingCriterion.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/MultiSourceStoppingCriterion.java @@ -10,9 +10,9 @@ import java.util.PriorityQueue; public class MultiSourceStoppingCriterion { - private int treeEntrySize; + private final int treeEntrySize; private AveragedMultiTreeSPEntry combinedUnsettled; - private IntHashSet targetSet; + private final IntHashSet targetSet; IntObjectMap targetMap; IntObjectMap allTargetsForSourceFound; @@ -23,8 +23,9 @@ public MultiSourceStoppingCriterion(IntHashSet targetSet, IntObjectMap(treeEntrySize); } + public boolean isFinished(AveragedMultiTreeSPEntry currEdge, PriorityQueue prioQueue) { - if(combinedUnsettled != null && checkAllTargetsForAllSourcesFound()) + if (combinedUnsettled != null && checkAllTargetsForAllSourcesFound()) return !queueHasSmallerWeight(combinedUnsettled, prioQueue); if (!targetSet.contains(currEdge.getAdjNode())) @@ -42,12 +43,12 @@ public boolean isFinished(AveragedMultiTreeSPEntry currEdge, PriorityQueue entry : targetMap){ + for (IntObjectCursor entry : targetMap) { for (int source = 0; source < treeEntrySize; ++source) { - if(allTargetsForSourceFound.getOrDefault(source, false)) { + if (allTargetsForSourceFound.getOrDefault(source, false)) { double entryWeight = entry.value.getItem(source).getWeight(); @@ -75,37 +76,38 @@ public void updateCombinedUnsettled(){ /** * Check whether the priorityqueue has an entry that could possibly lead to a shorter path for any of the subItems + * * @return */ private boolean queueHasSmallerWeight(AveragedMultiTreeSPEntry target, PriorityQueue prioQueue) { for (AveragedMultiTreeSPEntry entry : prioQueue) { for (int i = 0; i < treeEntrySize; ++i) { - if(entry.getItem(i).getWeight() < target.getItem(i).getWeight()) + if (entry.getItem(i).getWeight() < target.getItem(i).getWeight()) return true; } } return false; } - private boolean checkAllTargetsForAllSourcesFound(){ - for (int source = 0; source < treeEntrySize; source++){ - if(combinedUnsettled.getItem(source).getWeight() == -1.0) + private boolean checkAllTargetsForAllSourcesFound() { + for (int source = 0; source < treeEntrySize; source++) { + if (combinedUnsettled.getItem(source).getWeight() == -1.0) return false; } return true; } private void setSourceTargetsFound() { - for(int source = 0; source < treeEntrySize; source += 1){ - if(allTargetsForSourceFound.getOrDefault(source, false)) + for (int source = 0; source < treeEntrySize; source += 1) { + if (allTargetsForSourceFound.getOrDefault(source, false)) continue; boolean allFound = true; for (IntCursor targetId : targetSet) { //The target has not been reached yet - if(!targetMap.containsKey(targetId.value)) + if (!targetMap.containsKey(targetId.value)) return; AveragedMultiTreeSPEntry target = targetMap.get(targetId.value); - if(target.getItem(source).getWeight() == Double.POSITIVE_INFINITY) { + if (target.getItem(source).getWeight() == Double.POSITIVE_INFINITY) { allFound = false; break; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/ORSParameters.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/ORSParameters.java index 55e21cce05..31102c3ebe 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/ORSParameters.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/util/ORSParameters.java @@ -20,7 +20,8 @@ * @author Hendrik Leuschner */ public class ORSParameters { - private ORSParameters() {} + private ORSParameters() { + } /* Parameters with an 'INIT' prefix are used as defaults and/or are configured at start.*/ static final String ROUTING_INIT_PREFIX = "routing."; @@ -29,7 +30,8 @@ private ORSParameters() {} * Parameters that can be passed as hints and influence routing per request. */ public static final class Weighting { - private Weighting() {} + private Weighting() { + } public static final String TIME_DEPENDENT_SPEED_OR_ACCESS = "time_dependent_speed_or_access"; } @@ -39,7 +41,8 @@ private Weighting() {} * Properties for routing with contraction hierarchies speedup */ public static final class Core { - private Core() {} + private Core() { + } public static final String PREPARE = "prepare.core."; /** @@ -61,7 +64,8 @@ private Core() {} * Properties for routing with landmark speedup */ public static final class CoreLandmark { - private CoreLandmark() {} + private CoreLandmark() { + } public static final String PREPARE = "prepare.corelm."; /** @@ -94,7 +98,8 @@ private CoreLandmark() {} * Properties for partition preparation */ public static final class FastIsochrone { - private FastIsochrone(){} + private FastIsochrone() { + } public static final String PREPARE = "prepare.fastisochrone."; /** diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AdditionWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AdditionWeighting.java index e95d2d1261..75348aa95b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AdditionWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AdditionWeighting.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.weighting; @@ -22,49 +22,49 @@ // TODO (cleanup): The name is misleading as the class does not only // perform addition. Rename into SoftWeighting public class AdditionWeighting extends AbstractAdjustedWeighting { - private final Weighting[] weightings; + private final Weighting[] weightings; - /* - * @deprecated This constructor reveals too much of the implementation - * details. Use {@link AdditionWeighting(Collection weightings, Weighting superWeighting)} - */ - @Deprecated + /* + * @deprecated This constructor reveals too much of the implementation + * details. Use {@link AdditionWeighting(Collection weightings, Weighting superWeighting)} + */ + @Deprecated public AdditionWeighting(Weighting[] weightings, Weighting superWeighting) { super(superWeighting); this.weightings = weightings.clone(); } - public AdditionWeighting(Collection weightings, Weighting superWeighting) { - super(superWeighting); - this.weightings = weightings.toArray(new Weighting[0]); - } + public AdditionWeighting(Collection weightings, Weighting superWeighting) { + super(superWeighting); + this.weightings = weightings.toArray(new Weighting[0]); + } @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse, long edgeEnterTime) { double sumOfWeights = 0; - for (Weighting weighting:weightings) { - sumOfWeights += weighting.calcEdgeWeight(edgeState, reverse); - } - return superWeighting.calcEdgeWeight(edgeState, reverse, edgeEnterTime) * sumOfWeights; + for (Weighting weighting : weightings) { + sumOfWeights += weighting.calcEdgeWeight(edgeState, reverse); + } + return superWeighting.calcEdgeWeight(edgeState, reverse, edgeEnterTime) * sumOfWeights; } - @Override - public String getName() { - return "addition"; - } + @Override + public String getName() { + return "addition"; + } - @Override - public int hashCode() { - return ("AddWeighting" + this).hashCode(); - } + @Override + public int hashCode() { + return ("AddWeighting" + this).hashCode(); + } - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final AdditionWeighting other = (AdditionWeighting) obj; - return toString().equals(other.toString()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final AdditionWeighting other = (AdditionWeighting) obj; + return toString().equals(other.toString()); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AvoidHillsWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AvoidHillsWeighting.java index 8aafcb8bc5..b1e43e6c9d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AvoidHillsWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/AvoidHillsWeighting.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.weighting; @@ -24,15 +24,16 @@ /** * Special weighting for down/uphills *

    + * * @author Maxim Rylov */ public class AvoidHillsWeighting extends FastestWeighting { - private final HillIndexGraphStorage gsHillIndex; - private final byte[] buffer; - private double maxSteepness = -1; - //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 - private static final double[] PENALTY_FACTOR = {1.0, 1.0, 1.1, 1.5, 1.7, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.2, 3.5, 3.7, 3.9, 4.2}; - //old values: 1.0, 1.0, 1.1, 1.5, 2.0, 2.1, 2.3, 2.4, 2.5, 2.7, 2.9, 3.1, 3.3, 3.6, 3.8, 4.5 + private final HillIndexGraphStorage gsHillIndex; + private final byte[] buffer; + private double maxSteepness = -1; + //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 + private static final double[] PENALTY_FACTOR = {1.0, 1.0, 1.1, 1.5, 1.7, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.2, 3.5, 3.7, 3.9, 4.2}; + //old values: 1.0, 1.0, 1.1, 1.5, 2.0, 2.1, 2.3, 2.4, 2.5, 2.7, 2.9, 3.1, 3.3, 3.6, 3.8, 4.5 public AvoidHillsWeighting(FlagEncoder encoder, PMap map, GraphHopperStorage graphStorage) { super(encoder, map); @@ -43,30 +44,30 @@ public AvoidHillsWeighting(FlagEncoder encoder, PMap map, GraphHopperStorage gra @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { - if (gsHillIndex != null) { - boolean revert = edgeState.getBaseNode() < edgeState.getAdjNode(); - int hillIndex = gsHillIndex.getEdgeValue(edgeState.getEdge(), revert, buffer); + if (gsHillIndex != null) { + boolean revert = edgeState.getBaseNode() < edgeState.getAdjNode(); + int hillIndex = gsHillIndex.getEdgeValue(edgeState.getEdge(), revert, buffer); - if (maxSteepness > 0 && hillIndex > maxSteepness) - return 100; + if (maxSteepness > 0 && hillIndex > maxSteepness) + return 100; - return PENALTY_FACTOR[hillIndex]; - } - return 1; + return PENALTY_FACTOR[hillIndex]; + } + return 1; } - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final AvoidHillsWeighting other = (AvoidHillsWeighting) obj; - return toString().equals(other.toString()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final AvoidHillsWeighting other = (AvoidHillsWeighting) obj; + return toString().equals(other.toString()); + } - @Override - public int hashCode() { - return ("AvoidHillsWeighting" + this).hashCode(); - } + @Override + public int hashCode() { + return ("AvoidHillsWeighting" + this).hashCode(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ConstantWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ConstantWeighting.java index 587b7511c4..2c5f323f58 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ConstantWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ConstantWeighting.java @@ -11,7 +11,7 @@ public class ConstantWeighting implements Weighting { public ConstantWeighting(double weight, long millis) { this.weight = weight; - this. millis = millis; + this.millis = millis; } @Override diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/DistanceWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/DistanceWeighting.java index c364b751fe..0af00ac09a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/DistanceWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/DistanceWeighting.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.weighting; @@ -28,18 +28,18 @@ public double calcEdgeWeight(EdgeIteratorState edge, boolean reverse) { if (speed == 0) return Double.POSITIVE_INFINITY; - return edge.getDistance(); + return edge.getDistance(); } - @Override - public double getMinWeight(double distance) { - return 0; - } + @Override + public double getMinWeight(double distance) { + return 0; + } - @Override - public String getName() { - return "distance"; - } + @Override + public String getName() { + return "distance"; + } @Override public boolean equals(Object obj) { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/FastestSafeWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/FastestSafeWeighting.java index bc900d59ec..a558f42e62 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/FastestSafeWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/FastestSafeWeighting.java @@ -1,65 +1,65 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.weighting; import com.graphhopper.routing.util.FlagEncoder; -import com.graphhopper.routing.weighting.TurnCostProvider; -import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import com.graphhopper.routing.weighting.FastestWeighting; +import com.graphhopper.routing.weighting.TurnCostProvider; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.PMap; import org.heigit.ors.routing.graphhopper.extensions.flagencoders.FlagEncoderKeys; +import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; /** * Special weighting for (motor)bike *

    - * + * * @author Peter Karich */ public class FastestSafeWeighting extends FastestWeighting { - private final Double priorityThreshold = PriorityCode.REACH_DEST.getValue() / (double)PriorityCode.BEST.getValue(); - - public FastestSafeWeighting(FlagEncoder encoder, PMap map, TurnCostProvider turnCostProvider) { - super(encoder, map, turnCostProvider); - } + private final Double priorityThreshold = PriorityCode.REACH_DEST.getValue() / (double) PriorityCode.BEST.getValue(); + + public FastestSafeWeighting(FlagEncoder encoder, PMap map, TurnCostProvider turnCostProvider) { + super(encoder, map, turnCostProvider); + } - @Override - public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse, long edgeEnterTime) { - double weight = super.calcEdgeWeight(edgeState, reverse, edgeEnterTime); - if (Double.isInfinite(weight)) - return Double.POSITIVE_INFINITY; + @Override + public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse, long edgeEnterTime) { + double weight = super.calcEdgeWeight(edgeState, reverse, edgeEnterTime); + if (Double.isInfinite(weight)) + return Double.POSITIVE_INFINITY; - double priority = getFlagEncoder().getDecimalEncodedValue(FlagEncoderKeys.PRIORITY_KEY).getDecimal(reverse, edgeState.getFlags()); + double priority = getFlagEncoder().getDecimalEncodedValue(FlagEncoderKeys.PRIORITY_KEY).getDecimal(reverse, edgeState.getFlags()); - if (priority <= priorityThreshold) - weight *= 2; + if (priority <= priorityThreshold) + weight *= 2; - return weight; - } + return weight; + } - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final FastestSafeWeighting other = (FastestSafeWeighting) obj; - return toString().equals(other.toString()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final FastestSafeWeighting other = (FastestSafeWeighting) obj; + return toString().equals(other.toString()); + } - @Override - public int hashCode() { - return ("FastestSafeWeighting" + this).hashCode(); - } + @Override + public int hashCode() { + return ("FastestSafeWeighting" + this).hashCode(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/GreenWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/GreenWeighting.java index 8f531cbcdf..12382bfa4c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/GreenWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/GreenWeighting.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.weighting; @@ -34,12 +34,12 @@ public class GreenWeighting extends FastestWeighting { public GreenWeighting(FlagEncoder encoder, PMap map, GraphHopperStorage graphStorage) { super(encoder, map); - + gsGreenIndex = GraphStorageUtils.getGraphExtension(graphStorage, GreenIndexGraphStorage.class); double factor = map.getDouble("factor", 1); - + for (int i = 0; i < TOTAL_LEVEL; i++) - factors[i] = calcGreenWeightFactor(i, factor); + factors[i] = calcGreenWeightFactor(i, factor); } private double calcGreenWeightFactor(int level, double factor) { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/HeatStressWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/HeatStressWeighting.java index 152efd9c46..424526aab2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/HeatStressWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/HeatStressWeighting.java @@ -11,9 +11,9 @@ public class HeatStressWeighting extends FastestWeighting { - private CsvGraphStorage heatStressStorage; - private byte[] buffer; - private double weightingFactor; + private final CsvGraphStorage heatStressStorage; + private final byte[] buffer; + private final double weightingFactor; private final String columnName; private final int columnIndex; // Caches index of columnName for performance reasons diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/LimitedAccessWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/LimitedAccessWeighting.java index b92f4143fa..71b1f65d14 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/LimitedAccessWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/LimitedAccessWeighting.java @@ -48,9 +48,9 @@ public LimitedAccessWeighting(Weighting superWeighting, PMap map) { throw new IllegalArgumentException("road_access is not available"); // ensure that we do not need to change getMinWeight, i.e. road_access_factor >= 1 - double defaultDestinationFactor = encoder.getTransportationMode().isMotorVehicle()? VEHICLE_DESTINATION_FACTOR : DEFAULT_DESTINATION_FACTOR; + double defaultDestinationFactor = encoder.getTransportationMode().isMotorVehicle() ? VEHICLE_DESTINATION_FACTOR : DEFAULT_DESTINATION_FACTOR; destinationPenalty = checkBounds("road_access_destination_factor", map.getDouble("road_access_destination_factor", defaultDestinationFactor), MIN_DESTINATION_FACTOR, MAX_DESTINATION_FACTOR); - double defaultPrivateFactor = encoder.getTransportationMode().isMotorVehicle()? VEHICLE_PRIVATE_FACTOR : DEFAULT_PRIVATE_FACTOR; + double defaultPrivateFactor = encoder.getTransportationMode().isMotorVehicle() ? VEHICLE_PRIVATE_FACTOR : DEFAULT_PRIVATE_FACTOR; privatePenalty = checkBounds("road_access_private_factor", map.getDouble("road_access_private_factor", defaultPrivateFactor), MIN_PRIVATE_FACTOR, MAX_PRIVATE_FACTOR); roadAccessEnc = destinationPenalty > 1 || privatePenalty > 1 ? encoder.getEnumEncodedValue(RoadAccess.KEY, RoadAccess.class) : null; } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ORSPriorityWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ORSPriorityWeighting.java index ccf4895fbc..f260964a43 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ORSPriorityWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ORSPriorityWeighting.java @@ -1,70 +1,70 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.weighting; import com.graphhopper.routing.ev.DecimalEncodedValue; import com.graphhopper.routing.util.FlagEncoder; -import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import com.graphhopper.routing.weighting.TurnCostProvider; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.PMap; import org.heigit.ors.routing.graphhopper.extensions.flagencoders.FlagEncoderKeys; +import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import static com.graphhopper.routing.util.EncodingManager.getKey; public class ORSPriorityWeighting extends ORSFastestWeighting { - private static final double PRIORITY_BEST = PriorityCode.BEST.getValue(); - private static final double PRIORITY_UNCHANGED = PriorityCode.UNCHANGED.getValue(); - private final DecimalEncodedValue priorityEncoder; + private static final double PRIORITY_BEST = PriorityCode.BEST.getValue(); + private static final double PRIORITY_UNCHANGED = PriorityCode.UNCHANGED.getValue(); + private final DecimalEncodedValue priorityEncoder; - public ORSPriorityWeighting(FlagEncoder encoder, PMap map, TurnCostProvider tcp) { - super(encoder, map, tcp); - priorityEncoder = encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY)); - } + public ORSPriorityWeighting(FlagEncoder encoder, PMap map, TurnCostProvider tcp) { + super(encoder, map, tcp); + priorityEncoder = encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY)); + } - @Override - public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse, long edgeEnterTime) { - double weight = super.calcEdgeWeight(edgeState, reverse, edgeEnterTime); - if (Double.isInfinite(weight)) - return Double.POSITIVE_INFINITY; + @Override + public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse, long edgeEnterTime) { + double weight = super.calcEdgeWeight(edgeState, reverse, edgeEnterTime); + if (Double.isInfinite(weight)) + return Double.POSITIVE_INFINITY; - double priority = priorityEncoder.getDecimal(reverse, edgeState.getFlags()); + double priority = priorityEncoder.getDecimal(reverse, edgeState.getFlags()); - double normalizedPriority = priority * PRIORITY_BEST - PRIORITY_UNCHANGED; + double normalizedPriority = priority * PRIORITY_BEST - PRIORITY_UNCHANGED; - double factor = Math.pow(2, normalizedPriority / (PRIORITY_UNCHANGED - PRIORITY_BEST)); + double factor = Math.pow(2, normalizedPriority / (PRIORITY_UNCHANGED - PRIORITY_BEST)); - return weight * factor; - } + return weight * factor; + } - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final ORSPriorityWeighting other = (ORSPriorityWeighting) obj; - return toString().equals(other.toString()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final ORSPriorityWeighting other = (ORSPriorityWeighting) obj; + return toString().equals(other.toString()); + } - @Override - public int hashCode() { - return ("ORSPriorityWeighting" + this).hashCode(); - } + @Override + public int hashCode() { + return ("ORSPriorityWeighting" + this).hashCode(); + } - @Override - public String getName() { - return "recommended"; - } + @Override + public String getName() { + return "recommended"; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/PreferencePriorityWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/PreferencePriorityWeighting.java index a1fcffaf2e..cb8c296c09 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/PreferencePriorityWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/PreferencePriorityWeighting.java @@ -15,68 +15,69 @@ import com.graphhopper.routing.ev.DecimalEncodedValue; import com.graphhopper.routing.util.FlagEncoder; -import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import com.graphhopper.routing.weighting.FastestWeighting; import com.graphhopper.routing.weighting.TurnCostProvider; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.PMap; import org.heigit.ors.routing.graphhopper.extensions.flagencoders.FlagEncoderKeys; +import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import static com.graphhopper.routing.util.EncodingManager.getKey; public class PreferencePriorityWeighting extends FastestWeighting { - private static final double THRESHOLD_VERY_BAD = PriorityCode.AVOID_IF_POSSIBLE.getValue() / (double)PriorityCode.BEST.getValue(); - private static final double THRESHOLD_REACH_DEST = PriorityCode.REACH_DEST.getValue() / (double)PriorityCode.BEST.getValue(); - private static final double THRESHOLD_PREFER = PriorityCode.PREFER.getValue() / (double)PriorityCode.BEST.getValue(); - private static final double THRESHOLD_VERY_NICE = PriorityCode.VERY_NICE.getValue() / (double)PriorityCode.BEST.getValue(); - private final DecimalEncodedValue priorityEncoder; + private static final double THRESHOLD_VERY_BAD = PriorityCode.AVOID_IF_POSSIBLE.getValue() / (double) PriorityCode.BEST.getValue(); + private static final double THRESHOLD_REACH_DEST = PriorityCode.REACH_DEST.getValue() / (double) PriorityCode.BEST.getValue(); + private static final double THRESHOLD_PREFER = PriorityCode.PREFER.getValue() / (double) PriorityCode.BEST.getValue(); + private static final double THRESHOLD_VERY_NICE = PriorityCode.VERY_NICE.getValue() / (double) PriorityCode.BEST.getValue(); + private final DecimalEncodedValue priorityEncoder; + + public PreferencePriorityWeighting(FlagEncoder encoder, PMap map) { + super(encoder, map); + priorityEncoder = encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY)); + } - public PreferencePriorityWeighting(FlagEncoder encoder, PMap map) { - super(encoder, map); - priorityEncoder = encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY)); - } + public PreferencePriorityWeighting(FlagEncoder encoder, PMap map, TurnCostProvider tcp) { + super(encoder, map, tcp); + priorityEncoder = encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY)); + } - public PreferencePriorityWeighting(FlagEncoder encoder, PMap map, TurnCostProvider tcp) { - super(encoder, map, tcp); - priorityEncoder = encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY)); - } - @Override - public double calcEdgeWeight( EdgeIteratorState edgeState, boolean reverse) { - double weight = super.calcEdgeWeight(edgeState, reverse); - if (Double.isInfinite(weight)) - weight = 0.0; + @Override + public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { + double weight = super.calcEdgeWeight(edgeState, reverse); + if (Double.isInfinite(weight)) + weight = 0.0; - double priority = priorityEncoder.getDecimal(reverse, edgeState.getFlags()); + double priority = priorityEncoder.getDecimal(reverse, edgeState.getFlags()); - if (priority <= THRESHOLD_REACH_DEST) - priority /= 1.5; - else if (priority <= THRESHOLD_VERY_BAD) - priority /= 1.25; - else if (priority == THRESHOLD_PREFER) - priority *= 1.5; - else if (priority >= THRESHOLD_VERY_NICE) - priority *= 2.2; + if (priority <= THRESHOLD_REACH_DEST) + priority /= 1.5; + else if (priority <= THRESHOLD_VERY_BAD) + priority /= 1.25; + else if (priority == THRESHOLD_PREFER) + priority *= 1.5; + else if (priority >= THRESHOLD_VERY_NICE) + priority *= 2.2; - return weight / (0.5 + priority); - } + return weight / (0.5 + priority); + } - @Override - public String getName() { - return "recommended"; - } + @Override + public String getName() { + return "recommended"; + } - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final PreferencePriorityWeighting other = (PreferencePriorityWeighting) obj; - return toString().equals(other.toString()); - } + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final PreferencePriorityWeighting other = (PreferencePriorityWeighting) obj; + return toString().equals(other.toString()); + } - @Override - public int hashCode() { - return ("PreferencePriorityWeighting" + this).hashCode(); - } + @Override + public int hashCode() { + return ("PreferencePriorityWeighting" + this).hashCode(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/QuietWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/QuietWeighting.java index d8cf5e4f3b..f8f1e8bed9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/QuietWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/QuietWeighting.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.graphhopper.extensions.weighting; @@ -35,16 +35,16 @@ public QuietWeighting(FlagEncoder encoder, PMap map, GraphHopperStorage graphSto } private double calcNoiseWeightFactor(int level) { - if ( level == 0) - return 1; - else if ( level <=1 ) - return 1 + weightingFactor * 10; - else if ( level <=2 ) - return 1 + weightingFactor * weightingFactor * 200; // drop factor for noise level 2 and 3 dramatically, but still larger then the factor for noise level 1 - else if (level <=3 ) - return 1 + weightingFactor * weightingFactor * 400; + if (level == 0) + return 1; + else if (level <= 1) + return 1 + weightingFactor * 10; + else if (level <= 2) + return 1 + weightingFactor * weightingFactor * 200; // drop factor for noise level 2 and 3 dramatically, but still larger then the factor for noise level 1 + else if (level <= 3) + return 1 + weightingFactor * weightingFactor * 400; else - throw new AssertionError("The noise level "+ level + " is not supported!"); + throw new AssertionError("The noise level " + level + " is not supported!"); } @Override diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ShadowWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ShadowWeighting.java index 80ac263ee3..8cbcdb1e07 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ShadowWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/ShadowWeighting.java @@ -26,9 +26,9 @@ public class ShadowWeighting extends FastestWeighting { private static final Logger LOGGER = Logger.getLogger(ShadowWeighting.class.getName()); - private ShadowIndexGraphStorage _shadowIndexStorage; - private byte[] _buffer = new byte[1]; - private double _userWeighting; + private final ShadowIndexGraphStorage _shadowIndexStorage; + private final byte[] _buffer = new byte[1]; + private final double _userWeighting; public ShadowWeighting(FlagEncoder encoder, PMap map, GraphHopperStorage graphStorage) { super(encoder, map); @@ -47,7 +47,7 @@ private double calShadowWeighting(int shadowIndexValue) { @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { int shadowValue = _shadowIndexStorage - .getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edgeState), _buffer); + .getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edgeState), _buffer); return calShadowWeighting(shadowValue); } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/SteepnessDifficultyWeighting.java b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/SteepnessDifficultyWeighting.java index f76f10f259..f2444aa68f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/SteepnessDifficultyWeighting.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/graphhopper/extensions/weighting/SteepnessDifficultyWeighting.java @@ -1,11 +1,11 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License along with this library; @@ -23,58 +23,58 @@ import org.heigit.ors.routing.graphhopper.extensions.storages.HillIndexGraphStorage; public class SteepnessDifficultyWeighting extends FastestWeighting { - - private final HillIndexGraphStorage gsHillIndex; - private final byte[] buffer; - private double[] difficultyWeights; + + private final HillIndexGraphStorage gsHillIndex; + private final byte[] buffer; + private double[] difficultyWeights; private static final double[][] BIKE_DIFFICULTY_MATRIX = { // [4][20] - {0.5, 0.5, 0.5, 0.7, 0.9, 1.5, 3, 3.5, 4, 5, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15, 15.5}, - {0.7, 0.6, 0.6, 0.5, 0.5, 0.8, 1.0, 2, 3, 4, 5, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15, 15.5}, - {1.6, 1.6, 1.5, 1.5, 0.7, 0.5, 0.5, 0.5, 1, 2, 2.5, 2.5, 3, 4, 5, 7.5, 7.6, 7.7, 7.8, 7.9}, - {1.6, 1.6, 1.5, 1.5, 0.9, 0.7, 0.5, 0.5, 0.6, 0.7, 0.9, 1.2, 2, 3, 5, 6, 7.7, 7.8, 7.9, 8.0} - }; + {0.5, 0.5, 0.5, 0.7, 0.9, 1.5, 3, 3.5, 4, 5, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15, 15.5}, + {0.7, 0.6, 0.6, 0.5, 0.5, 0.8, 1.0, 2, 3, 4, 5, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15, 15.5}, + {1.6, 1.6, 1.5, 1.5, 0.7, 0.5, 0.5, 0.5, 1, 2, 2.5, 2.5, 3, 4, 5, 7.5, 7.6, 7.7, 7.8, 7.9}, + {1.6, 1.6, 1.5, 1.5, 0.9, 0.7, 0.5, 0.5, 0.6, 0.7, 0.9, 1.2, 2, 3, 5, 6, 7.7, 7.8, 7.9, 8.0} + }; public SteepnessDifficultyWeighting(FlagEncoder encoder, PMap map, GraphHopperStorage graphStorage) { super(encoder, map); buffer = new byte[1]; - int difficultyLevel = map.getInt("level", -1); + int difficultyLevel = map.getInt("level", -1); gsHillIndex = GraphStorageUtils.getGraphExtension(graphStorage, HillIndexGraphStorage.class); // TODO: Check for upper bound of difficultyLevel. What is the right behavior here? - // TODO: Ignoring as for negative values, or throwing a dedicated exception? + // TODO: Ignoring as for negative values, or throwing a dedicated exception? if (gsHillIndex != null && difficultyLevel >= 0) { - difficultyWeights = BIKE_DIFFICULTY_MATRIX[difficultyLevel]; + difficultyWeights = BIKE_DIFFICULTY_MATRIX[difficultyLevel]; } } - + @Override public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) { - if (gsHillIndex != null) { - boolean revert = edgeState.getBaseNode() < edgeState.getAdjNode(); - int hillIndex = gsHillIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edgeState), revert, buffer); + if (gsHillIndex != null) { + boolean revert = edgeState.getBaseNode() < edgeState.getAdjNode(); + int hillIndex = gsHillIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edgeState), revert, buffer); - if (difficultyWeights != null) { - // TODO: Clarify whether hillIndex should be checked for out of bounds. - return difficultyWeights[hillIndex]; - } - } - return 1.0; + if (difficultyWeights != null) { + // TODO: Clarify whether hillIndex should be checked for out of bounds. + return difficultyWeights[hillIndex]; + } + } + return 1.0; } - @Override - public boolean equals(Object obj) { - // TODO: Clarify whether equals should depend on difficulty level. - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final SteepnessDifficultyWeighting other = (SteepnessDifficultyWeighting) obj; - return toString().equals(other.toString()); - } + @Override + public boolean equals(Object obj) { + // TODO: Clarify whether equals should depend on difficulty level. + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final SteepnessDifficultyWeighting other = (SteepnessDifficultyWeighting) obj; + return toString().equals(other.toString()); + } - @Override - public int hashCode() { - // TODO: Clarify whether hashCode should depend on difficulty level. - return ("SteepnessDifficultyWeighting" + this).hashCode(); - } + @Override + public int hashCode() { + // TODO: Clarify whether hashCode should depend on difficulty level. + return ("SteepnessDifficultyWeighting" + this).hashCode(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslator.java b/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslator.java index 4d18e67a6c..08cd761931 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslator.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslator.java @@ -19,190 +19,190 @@ import org.heigit.ors.localization.LanguageResources; public class InstructionTranslator { - private static final String STR_TURN_MANEUVER = "{turn_maneuver}"; - private static final String STR_WAY_NAME = "{way_name}"; - private static final String STR_EXIT_NUMBER = "{exit_number}"; - private static final String STR_DIRECTION = "{direction}"; - private static final String STR_NAME = "{name}"; - private static final String STR_HEADSIGN = "{headsign}"; - - private final String[] directions; - private final String actionDepartDefault; - private final String actionDepartName; - private final String actionPtStart; - private final String actionPtStartWithHeadsign; - private final String actionPtTransfer; - private final String actionPtTransferWithHeadsign; - private final String actionPtEnd; - private final String[] actionArriveDefault; - private final String[] actionArriveName; - private final String actionRoundaboutDefault; - private final String actionRoundaboutName; - private final String actionContinueDefault; - private final String actionContinueName; - private final String actionKeepDefault; - private final String actionKeepName; - private final String actionTurnDefault; - private final String actionTurnName; - private final String[] numerals; - private final String[] turnManeuvers; - - InstructionTranslator(LanguageResources resources) throws Exception { - directions = new String[8]; - directions[0] = resources.getTranslation("instructions.directions.north"); - directions[1] = resources.getTranslation("instructions.directions.northeast"); - directions[2] = resources.getTranslation("instructions.directions.east"); - directions[3] = resources.getTranslation("instructions.directions.southeast"); - directions[4] = resources.getTranslation("instructions.directions.south"); - directions[5] = resources.getTranslation("instructions.directions.southwest"); - directions[6] = resources.getTranslation("instructions.directions.west"); - directions[7] = resources.getTranslation("instructions.directions.northwest"); - - turnManeuvers = new String[10]; - turnManeuvers[0] = resources.getTranslation("instructions.turn_maneuvers.left"); - turnManeuvers[1] = resources.getTranslation("instructions.turn_maneuvers.right"); - turnManeuvers[2] = resources.getTranslation("instructions.turn_maneuvers.sharp_left"); - turnManeuvers[3] = resources.getTranslation("instructions.turn_maneuvers.sharp_right"); - turnManeuvers[4] = resources.getTranslation("instructions.turn_maneuvers.slight_left"); - turnManeuvers[5] = resources.getTranslation("instructions.turn_maneuvers.slight_right"); - turnManeuvers[6] = resources.getTranslation("instructions.turn_maneuvers.straight"); - turnManeuvers[7] = resources.getTranslation("instructions.turn_maneuvers.uturn"); - turnManeuvers[8] = resources.getTranslation("instructions.turn_maneuvers.left"); - turnManeuvers[9] = resources.getTranslation("instructions.turn_maneuvers.right"); - - numerals = new String[11]; - for (int i = 1; i<=10; i++) - numerals[i] = resources.getTranslation("instructions.numerals." + i); - - actionDepartDefault = resources.getTranslation("instructions.actions.depart.default.default"); - actionDepartName = resources.getTranslation("instructions.actions.depart.default.name"); - actionPtStart = resources.getTranslation("instructions.actions.pt.start.default"); - actionPtStartWithHeadsign = resources.getTranslation("instructions.actions.pt.start.headsign"); - actionPtTransfer = resources.getTranslation("instructions.actions.pt.transfer.default"); - actionPtTransferWithHeadsign = resources.getTranslation("instructions.actions.pt.transfer.headsign"); - actionPtEnd = resources.getTranslation("instructions.actions.pt.end"); - actionContinueDefault = resources.getTranslation("instructions.actions.continue.default.default"); - actionContinueName = resources.getTranslation("instructions.actions.continue.default.name"); - actionKeepDefault = resources.getTranslation("instructions.actions.keep.default.default"); - actionKeepName = resources.getTranslation("instructions.actions.keep.default.name"); - actionTurnDefault = resources.getTranslation("instructions.actions.turn.default.default"); - actionTurnName = resources.getTranslation("instructions.actions.turn.default.name"); - actionRoundaboutDefault = resources.getTranslation("instructions.actions.roundabout.default.exit.default"); - actionRoundaboutName = resources.getTranslation("instructions.actions.roundabout.default.exit.name"); - - actionArriveDefault = new String[4]; - actionArriveName = new String[4]; - actionArriveDefault[0] = resources.getTranslation("instructions.actions.arrive.default.default"); - actionArriveDefault[1] = resources.getTranslation("instructions.actions.arrive.left.default"); - actionArriveDefault[2] = resources.getTranslation("instructions.actions.arrive.right.default"); - actionArriveDefault[3] = resources.getTranslation("instructions.actions.arrive.straight.default"); - actionArriveName[0] = resources.getTranslation("instructions.actions.arrive.default.name"); - actionArriveName[1] = resources.getTranslation("instructions.actions.arrive.left.name"); - actionArriveName[2] = resources.getTranslation("instructions.actions.arrive.right.name"); - actionArriveName[3] = resources.getTranslation("instructions.actions.arrive.straight.name"); - } - - public String getContinue(InstructionType type, String wayName) { - if (Helper.isEmpty(wayName)) - return actionContinueDefault.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]); - else - return actionContinueName.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]).replace(STR_WAY_NAME, wayName); - } - - public String getTurn(InstructionType type, String wayName) { - if (Helper.isEmpty(wayName)) - return actionTurnDefault.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]); - else - return actionTurnName.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]).replace(STR_WAY_NAME, wayName); - } - - public String getKeep(InstructionType type, String wayName) { - if (Helper.isEmpty(wayName)) - return actionKeepDefault.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]); - else - return actionKeepName.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]).replace(STR_WAY_NAME, wayName); - } - - public String getRoundabout(int exitNumber, String wayName) { - boolean isWayNull = Helper.isEmpty(wayName); - String str = isWayNull ? actionRoundaboutDefault : actionRoundaboutName; - boolean isExitNull = (exitNumber == 0); - - // We need to check if the exit number is greater than 10, as that is the most we have in the n-th representation - boolean highNumber = (exitNumber > numerals.length-1); - - //If there was an error in finding the exit number, return "UNKNOWN". If there is no way name, don't return a way name - if(isExitNull) - str = str.replace(STR_EXIT_NUMBER, "UNKNOWN"); - else { - String numeral; - if(highNumber) { - // if it is a high number which is very rare, then we dont use the numeral representation, just the - // number itself - // Converting to the th is too complicated due to exceptions and the position of the "th" - - numeral = Integer.toString(exitNumber); - } else { - numeral = numerals[exitNumber]; - } - - str = str.replace(STR_EXIT_NUMBER, numeral); - } - if (isWayNull) - return str; - else - return str.replace(STR_WAY_NAME, wayName); - } - - public String getDepart(CardinalDirection direction, String wayName) { - if (Helper.isEmpty(wayName)) - return actionDepartDefault.replace(STR_DIRECTION, directions[direction.ordinal()]); - else - return actionDepartName.replace(STR_DIRECTION, directions[direction.ordinal()]).replace(STR_WAY_NAME, wayName); - } - - public String getPt(InstructionType type, String name) { - return getPt(type, name, null); - } - - public String getPt(InstructionType type, String name, String headsign) { - switch (type){ - case PT_ENTER: - if (!Helper.isEmpty(headsign)) - return actionPtStartWithHeadsign.replace(STR_NAME, name).replace(STR_HEADSIGN, headsign); - return actionPtStart.replace(STR_NAME, name); - case PT_TRANSFER: - if (!Helper.isEmpty(headsign)) - return actionPtTransferWithHeadsign.replace(STR_NAME, name).replace(STR_HEADSIGN, headsign); - return actionPtTransfer.replace(STR_NAME, name); - case PT_EXIT: - return actionPtEnd.replace(STR_NAME, name); - default: - return ""; - } - } - - public String getArrive(ArrivalDirection direction, String wayName) { - if (Helper.isEmpty(wayName)) - return actionArriveDefault[direction.ordinal()]; - else - return actionArriveName[direction.ordinal()].replace(STR_WAY_NAME, wayName); - } - - private int getTurnManeuver(InstructionType type) { - return switch (type) { - case TURN_LEFT -> 0; - case TURN_RIGHT -> 1; - case TURN_SHARP_LEFT -> 2; - case TURN_SHARP_RIGHT -> 3; - case TURN_SLIGHT_LEFT -> 4; - case TURN_SLIGHT_RIGHT -> 5; - case CONTINUE -> 6; - case KEEP_LEFT -> 8; - case KEEP_RIGHT -> 9; - default -> 0; - }; - //TODO - // _turnManeuvers[7] = _resources.getTranslation("instructions.turn_maneuvers.uturn") - } + private static final String STR_TURN_MANEUVER = "{turn_maneuver}"; + private static final String STR_WAY_NAME = "{way_name}"; + private static final String STR_EXIT_NUMBER = "{exit_number}"; + private static final String STR_DIRECTION = "{direction}"; + private static final String STR_NAME = "{name}"; + private static final String STR_HEADSIGN = "{headsign}"; + + private final String[] directions; + private final String actionDepartDefault; + private final String actionDepartName; + private final String actionPtStart; + private final String actionPtStartWithHeadsign; + private final String actionPtTransfer; + private final String actionPtTransferWithHeadsign; + private final String actionPtEnd; + private final String[] actionArriveDefault; + private final String[] actionArriveName; + private final String actionRoundaboutDefault; + private final String actionRoundaboutName; + private final String actionContinueDefault; + private final String actionContinueName; + private final String actionKeepDefault; + private final String actionKeepName; + private final String actionTurnDefault; + private final String actionTurnName; + private final String[] numerals; + private final String[] turnManeuvers; + + InstructionTranslator(LanguageResources resources) throws Exception { + directions = new String[8]; + directions[0] = resources.getTranslation("instructions.directions.north"); + directions[1] = resources.getTranslation("instructions.directions.northeast"); + directions[2] = resources.getTranslation("instructions.directions.east"); + directions[3] = resources.getTranslation("instructions.directions.southeast"); + directions[4] = resources.getTranslation("instructions.directions.south"); + directions[5] = resources.getTranslation("instructions.directions.southwest"); + directions[6] = resources.getTranslation("instructions.directions.west"); + directions[7] = resources.getTranslation("instructions.directions.northwest"); + + turnManeuvers = new String[10]; + turnManeuvers[0] = resources.getTranslation("instructions.turn_maneuvers.left"); + turnManeuvers[1] = resources.getTranslation("instructions.turn_maneuvers.right"); + turnManeuvers[2] = resources.getTranslation("instructions.turn_maneuvers.sharp_left"); + turnManeuvers[3] = resources.getTranslation("instructions.turn_maneuvers.sharp_right"); + turnManeuvers[4] = resources.getTranslation("instructions.turn_maneuvers.slight_left"); + turnManeuvers[5] = resources.getTranslation("instructions.turn_maneuvers.slight_right"); + turnManeuvers[6] = resources.getTranslation("instructions.turn_maneuvers.straight"); + turnManeuvers[7] = resources.getTranslation("instructions.turn_maneuvers.uturn"); + turnManeuvers[8] = resources.getTranslation("instructions.turn_maneuvers.left"); + turnManeuvers[9] = resources.getTranslation("instructions.turn_maneuvers.right"); + + numerals = new String[11]; + for (int i = 1; i <= 10; i++) + numerals[i] = resources.getTranslation("instructions.numerals." + i); + + actionDepartDefault = resources.getTranslation("instructions.actions.depart.default.default"); + actionDepartName = resources.getTranslation("instructions.actions.depart.default.name"); + actionPtStart = resources.getTranslation("instructions.actions.pt.start.default"); + actionPtStartWithHeadsign = resources.getTranslation("instructions.actions.pt.start.headsign"); + actionPtTransfer = resources.getTranslation("instructions.actions.pt.transfer.default"); + actionPtTransferWithHeadsign = resources.getTranslation("instructions.actions.pt.transfer.headsign"); + actionPtEnd = resources.getTranslation("instructions.actions.pt.end"); + actionContinueDefault = resources.getTranslation("instructions.actions.continue.default.default"); + actionContinueName = resources.getTranslation("instructions.actions.continue.default.name"); + actionKeepDefault = resources.getTranslation("instructions.actions.keep.default.default"); + actionKeepName = resources.getTranslation("instructions.actions.keep.default.name"); + actionTurnDefault = resources.getTranslation("instructions.actions.turn.default.default"); + actionTurnName = resources.getTranslation("instructions.actions.turn.default.name"); + actionRoundaboutDefault = resources.getTranslation("instructions.actions.roundabout.default.exit.default"); + actionRoundaboutName = resources.getTranslation("instructions.actions.roundabout.default.exit.name"); + + actionArriveDefault = new String[4]; + actionArriveName = new String[4]; + actionArriveDefault[0] = resources.getTranslation("instructions.actions.arrive.default.default"); + actionArriveDefault[1] = resources.getTranslation("instructions.actions.arrive.left.default"); + actionArriveDefault[2] = resources.getTranslation("instructions.actions.arrive.right.default"); + actionArriveDefault[3] = resources.getTranslation("instructions.actions.arrive.straight.default"); + actionArriveName[0] = resources.getTranslation("instructions.actions.arrive.default.name"); + actionArriveName[1] = resources.getTranslation("instructions.actions.arrive.left.name"); + actionArriveName[2] = resources.getTranslation("instructions.actions.arrive.right.name"); + actionArriveName[3] = resources.getTranslation("instructions.actions.arrive.straight.name"); + } + + public String getContinue(InstructionType type, String wayName) { + if (Helper.isEmpty(wayName)) + return actionContinueDefault.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]); + else + return actionContinueName.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]).replace(STR_WAY_NAME, wayName); + } + + public String getTurn(InstructionType type, String wayName) { + if (Helper.isEmpty(wayName)) + return actionTurnDefault.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]); + else + return actionTurnName.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]).replace(STR_WAY_NAME, wayName); + } + + public String getKeep(InstructionType type, String wayName) { + if (Helper.isEmpty(wayName)) + return actionKeepDefault.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]); + else + return actionKeepName.replace(STR_TURN_MANEUVER, turnManeuvers[getTurnManeuver(type)]).replace(STR_WAY_NAME, wayName); + } + + public String getRoundabout(int exitNumber, String wayName) { + boolean isWayNull = Helper.isEmpty(wayName); + String str = isWayNull ? actionRoundaboutDefault : actionRoundaboutName; + boolean isExitNull = (exitNumber == 0); + + // We need to check if the exit number is greater than 10, as that is the most we have in the n-th representation + boolean highNumber = (exitNumber > numerals.length - 1); + + //If there was an error in finding the exit number, return "UNKNOWN". If there is no way name, don't return a way name + if (isExitNull) + str = str.replace(STR_EXIT_NUMBER, "UNKNOWN"); + else { + String numeral; + if (highNumber) { + // if it is a high number which is very rare, then we dont use the numeral representation, just the + // number itself + // Converting to the th is too complicated due to exceptions and the position of the "th" + + numeral = Integer.toString(exitNumber); + } else { + numeral = numerals[exitNumber]; + } + + str = str.replace(STR_EXIT_NUMBER, numeral); + } + if (isWayNull) + return str; + else + return str.replace(STR_WAY_NAME, wayName); + } + + public String getDepart(CardinalDirection direction, String wayName) { + if (Helper.isEmpty(wayName)) + return actionDepartDefault.replace(STR_DIRECTION, directions[direction.ordinal()]); + else + return actionDepartName.replace(STR_DIRECTION, directions[direction.ordinal()]).replace(STR_WAY_NAME, wayName); + } + + public String getPt(InstructionType type, String name) { + return getPt(type, name, null); + } + + public String getPt(InstructionType type, String name, String headsign) { + switch (type) { + case PT_ENTER: + if (!Helper.isEmpty(headsign)) + return actionPtStartWithHeadsign.replace(STR_NAME, name).replace(STR_HEADSIGN, headsign); + return actionPtStart.replace(STR_NAME, name); + case PT_TRANSFER: + if (!Helper.isEmpty(headsign)) + return actionPtTransferWithHeadsign.replace(STR_NAME, name).replace(STR_HEADSIGN, headsign); + return actionPtTransfer.replace(STR_NAME, name); + case PT_EXIT: + return actionPtEnd.replace(STR_NAME, name); + default: + return ""; + } + } + + public String getArrive(ArrivalDirection direction, String wayName) { + if (Helper.isEmpty(wayName)) + return actionArriveDefault[direction.ordinal()]; + else + return actionArriveName[direction.ordinal()].replace(STR_WAY_NAME, wayName); + } + + private int getTurnManeuver(InstructionType type) { + return switch (type) { + case TURN_LEFT -> 0; + case TURN_RIGHT -> 1; + case TURN_SHARP_LEFT -> 2; + case TURN_SHARP_RIGHT -> 3; + case TURN_SLIGHT_LEFT -> 4; + case TURN_SLIGHT_RIGHT -> 5; + case CONTINUE -> 6; + case KEEP_LEFT -> 8; + case KEEP_RIGHT -> 9; + default -> 0; + }; + //TODO + // _turnManeuvers[7] = _resources.getTranslation("instructions.turn_maneuvers.uturn") + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslatorsCache.java b/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslatorsCache.java index 675dfd418d..f11a7f9397 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslatorsCache.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionTranslatorsCache.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.instructions; @@ -19,32 +19,31 @@ import java.util.Map; public class InstructionTranslatorsCache { - private final Map translators; - private static InstructionTranslatorsCache mInstance = null; - - private InstructionTranslatorsCache() - { - translators = new HashMap<>(); - } - - public static InstructionTranslatorsCache getInstance() { - if(null == mInstance) { - synchronized(InstructionTranslatorsCache.class) { - mInstance = new InstructionTranslatorsCache(); - } - } - return mInstance; - } - - public InstructionTranslator getTranslator(String langCode) throws Exception { - int hashCode = langCode.hashCode(); - InstructionTranslator res = translators.get(hashCode); - if (res == null) { - synchronized(InstructionTranslatorsCache.class) { - res = new InstructionTranslator(LocalizationManager.getInstance().getLanguageResources(langCode)); - translators.put(hashCode, res); - } - } - return res; - } + private final Map translators; + private static InstructionTranslatorsCache mInstance = null; + + private InstructionTranslatorsCache() { + translators = new HashMap<>(); + } + + public static InstructionTranslatorsCache getInstance() { + if (null == mInstance) { + synchronized (InstructionTranslatorsCache.class) { + mInstance = new InstructionTranslatorsCache(); + } + } + return mInstance; + } + + public InstructionTranslator getTranslator(String langCode) throws Exception { + int hashCode = langCode.hashCode(); + InstructionTranslator res = translators.get(hashCode); + if (res == null) { + synchronized (InstructionTranslatorsCache.class) { + res = new InstructionTranslator(LocalizationManager.getInstance().getLanguageResources(langCode)); + translators.put(hashCode, res); + } + } + return res; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionType.java b/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionType.java index d141634956..04800dcd2a 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionType.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/instructions/InstructionType.java @@ -1,20 +1,19 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.instructions; -public enum InstructionType -{ +public enum InstructionType { TURN_LEFT, /*0*/ TURN_RIGHT, /*1*/ TURN_SHARP_LEFT, /*2*/ @@ -26,7 +25,7 @@ public enum InstructionType EXIT_ROUNDABOUT, /*8*/ UTURN, /*9*/ FINISH, /*10*/ - DEPART, /*11*/ + DEPART, /*11*/ KEEP_LEFT, /*12*/ KEEP_RIGHT, /*13*/ PT_ENTER, /*14*/ diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/parameters/ProfileParameters.java b/ors-engine/src/main/java/org/heigit/ors/routing/parameters/ProfileParameters.java index f9c871ed21..b0e35236ca 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/parameters/ProfileParameters.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/parameters/ProfileParameters.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.parameters; @@ -23,19 +23,17 @@ public class ProfileParameters { protected ProfileWeightingCollection weightings; public void add(ProfileWeighting weighting) { - if (weightings == null) - weightings = new ProfileWeightingCollection(); - weightings.add(weighting); + if (weightings == null) + weightings = new ProfileWeightingCollection(); + weightings.add(weighting); } - - public ProfileWeightingCollection getWeightings() - { - return weightings; + + public ProfileWeightingCollection getWeightings() { + return weightings; } - - public boolean hasWeightings() - { - return weightings != null && weightings.size() > 0; + + public boolean hasWeightings() { + return weightings != null && weightings.size() > 0; } public List getValidRestrictions() { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/parameters/VehicleParameters.java b/ors-engine/src/main/java/org/heigit/ors/routing/parameters/VehicleParameters.java index eeaea65de4..fba1d5d0ec 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/parameters/VehicleParameters.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/parameters/VehicleParameters.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.parameters; @@ -18,74 +18,74 @@ import java.util.List; public class VehicleParameters extends ProfileParameters { - private double length = 0.0; - private double height = 0.0; - private double width = 0.0; - private double weight = 0.0; - private double axleload = 0.0; - private int characteristics = VehicleLoadCharacteristicsFlags.NONE; - - public double getLength() { - return length; - } - - public void setLength(double length) { - this.length = length; - } - - public double getHeight() { - return height; - } - - public void setHeight(double height) { - this.height = height; - } - - public double getWidth() { - return width; - } - - public void setWidth(double width) { - this.width = width; - } - - public double getWeight() { - return weight; - } - - public void setWeight(double weight) { - this.weight = weight; - } - - public double getAxleload() { - return axleload; - } - - public void setAxleload(double axleload) { - this.axleload = axleload; - } - - public int getLoadCharacteristics() { - return characteristics; - } - - public void setLoadCharacteristics(int characteristics) { - this.characteristics = characteristics; - } - - public boolean hasAttributes() { - return height > 0.0 || length > 0.0 || width > 0.0 || weight > 0.0 || axleload > 0.0 || characteristics != 0; - } - - @Override - public List getValidRestrictions() { - List valid = super.getValidRestrictions(); - valid.add("height"); - valid.add("length"); - valid.add("width"); - valid.add("weight"); - valid.add("hazmat"); - valid.add("axleload"); - return valid; - } + private double length = 0.0; + private double height = 0.0; + private double width = 0.0; + private double weight = 0.0; + private double axleload = 0.0; + private int characteristics = VehicleLoadCharacteristicsFlags.NONE; + + public double getLength() { + return length; + } + + public void setLength(double length) { + this.length = length; + } + + public double getHeight() { + return height; + } + + public void setHeight(double height) { + this.height = height; + } + + public double getWidth() { + return width; + } + + public void setWidth(double width) { + this.width = width; + } + + public double getWeight() { + return weight; + } + + public void setWeight(double weight) { + this.weight = weight; + } + + public double getAxleload() { + return axleload; + } + + public void setAxleload(double axleload) { + this.axleload = axleload; + } + + public int getLoadCharacteristics() { + return characteristics; + } + + public void setLoadCharacteristics(int characteristics) { + this.characteristics = characteristics; + } + + public boolean hasAttributes() { + return height > 0.0 || length > 0.0 || width > 0.0 || weight > 0.0 || axleload > 0.0 || characteristics != 0; + } + + @Override + public List getValidRestrictions() { + List valid = super.getValidRestrictions(); + valid.add("height"); + valid.add("length"); + valid.add("width"); + valid.add("weight"); + valid.add("hazmat"); + valid.add("axleload"); + return valid; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/parameters/WheelchairParameters.java b/ors-engine/src/main/java/org/heigit/ors/routing/parameters/WheelchairParameters.java index d60cf3f623..a9f2238965 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/parameters/WheelchairParameters.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/parameters/WheelchairParameters.java @@ -1,91 +1,103 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.parameters; import java.util.List; public class WheelchairParameters extends ProfileParameters { - private float maxIncline = Float.MAX_VALUE * -1.0f; - private float maxSlopedKerb = -1.0F; - private int surfaceType; - private int trackType; - private int smoothnessType; - private float minWidth = 0.0f; - private boolean surfaceQualityKnown = false; - private boolean allowUnsuitable = false; - - public float getMaximumIncline() { - return maxIncline; - } - - public void setMaximumIncline(float maxIncline) { - this.maxIncline = maxIncline; - } - - public int getSurfaceType() { - return surfaceType; - } - - public void setSurfaceType(int surfaceType) { - this.surfaceType = surfaceType; - } - - public float getMaximumSlopedKerb() { - return maxSlopedKerb; - } - - public void setMaximumSlopedKerb(float maxSlopedKerb) { - this.maxSlopedKerb = maxSlopedKerb; - } - - public int getTrackType() { - return trackType; - } - - public void setTrackType(int trackType) { - this.trackType = trackType; - } - - public int getSmoothnessType() { - return smoothnessType; - } - - public void setSmoothnessType(int smoothnessType) { - this.smoothnessType = smoothnessType; - } - - public float getMinimumWidth() { return minWidth; } - - public void setMinimumWidth(float width) { minWidth = width; } - - public boolean isRequireSurfaceQualityKnown() { return surfaceQualityKnown; } - - public void setSurfaceQualityKnown(boolean surfaceQualityKnown) { this.surfaceQualityKnown = surfaceQualityKnown; } - - public boolean allowUnsuitable() { return allowUnsuitable; } - - public void setAllowUnsuitable(boolean allowUnsuitable) { this.allowUnsuitable = allowUnsuitable; } - - @Override - public List getValidRestrictions() { - List valid = super.getValidRestrictions(); - valid.add("surface_type"); - valid.add("track_type"); - valid.add("smoothness_type"); - valid.add("maximum_sloped_kerb"); - valid.add("maximum_incline"); - valid.add("minimum_width"); - return valid; - } + private float maxIncline = Float.MAX_VALUE * -1.0f; + private float maxSlopedKerb = -1.0F; + private int surfaceType; + private int trackType; + private int smoothnessType; + private float minWidth = 0.0f; + private boolean surfaceQualityKnown = false; + private boolean allowUnsuitable = false; + + public float getMaximumIncline() { + return maxIncline; + } + + public void setMaximumIncline(float maxIncline) { + this.maxIncline = maxIncline; + } + + public int getSurfaceType() { + return surfaceType; + } + + public void setSurfaceType(int surfaceType) { + this.surfaceType = surfaceType; + } + + public float getMaximumSlopedKerb() { + return maxSlopedKerb; + } + + public void setMaximumSlopedKerb(float maxSlopedKerb) { + this.maxSlopedKerb = maxSlopedKerb; + } + + public int getTrackType() { + return trackType; + } + + public void setTrackType(int trackType) { + this.trackType = trackType; + } + + public int getSmoothnessType() { + return smoothnessType; + } + + public void setSmoothnessType(int smoothnessType) { + this.smoothnessType = smoothnessType; + } + + public float getMinimumWidth() { + return minWidth; + } + + public void setMinimumWidth(float width) { + minWidth = width; + } + + public boolean isRequireSurfaceQualityKnown() { + return surfaceQualityKnown; + } + + public void setSurfaceQualityKnown(boolean surfaceQualityKnown) { + this.surfaceQualityKnown = surfaceQualityKnown; + } + + public boolean allowUnsuitable() { + return allowUnsuitable; + } + + public void setAllowUnsuitable(boolean allowUnsuitable) { + this.allowUnsuitable = allowUnsuitable; + } + + @Override + public List getValidRestrictions() { + List valid = super.getValidRestrictions(); + valid.add("surface_type"); + valid.add("track_type"); + valid.add("smoothness_type"); + valid.add("maximum_sloped_kerb"); + valid.add("maximum_incline"); + valid.add("minimum_width"); + return valid; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/BordersExtractor.java b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/BordersExtractor.java index 273498d4a9..79db8b7f4f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/BordersExtractor.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/BordersExtractor.java @@ -5,7 +5,8 @@ import java.util.List; public class BordersExtractor { - public enum Avoid { CONTROLLED, NONE, ALL } + public enum Avoid {CONTROLLED, NONE, ALL} + private final BordersGraphStorage storage; private final int[] avoidCountries; @@ -36,8 +37,8 @@ public boolean restrictedCountry(int edgeId) { int startCountry = storage.getEdgeValue(edgeId, BordersGraphStorage.Property.START); int endCountry = storage.getEdgeValue(edgeId, BordersGraphStorage.Property.END); - for(int i = 0; i< avoidCountries.length; i++) { - if(startCountry == avoidCountries[i] || endCountry == avoidCountries[i] ) { + for (int i = 0; i < avoidCountries.length; i++) { + if (startCountry == avoidCountries[i] || endCountry == avoidCountries[i]) { return true; } } @@ -46,22 +47,23 @@ public boolean restrictedCountry(int edgeId) { /** * Check whether the start and end nodes of a list of edges are in the same country. + * * @param edgeIds Edges that the country should be checked for * @return true if at least one node is in the same country */ - public boolean isSameCountry(List edgeIds){ - if(edgeIds.isEmpty()) + public boolean isSameCountry(List edgeIds) { + if (edgeIds.isEmpty()) return true; short country0 = storage.getEdgeValue(edgeIds.get(0), BordersGraphStorage.Property.START); short country1 = storage.getEdgeValue(edgeIds.get(0), BordersGraphStorage.Property.END); - for(int edgeId : edgeIds) { + for (int edgeId : edgeIds) { short country2 = storage.getEdgeValue(edgeId, BordersGraphStorage.Property.START); short country3 = storage.getEdgeValue(edgeId, BordersGraphStorage.Property.END); - if(country0 != country2 - && country0 != country3 - && country1 != country2 - && country1 != country3) + if (country0 != country2 + && country0 != country3 + && country1 != country2 + && country1 != country3) return false; } return true; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ExtraInfoProcessor.java b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ExtraInfoProcessor.java index 54ac898e6b..30cdaa3c2d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ExtraInfoProcessor.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ExtraInfoProcessor.java @@ -16,14 +16,13 @@ import com.graphhopper.routing.querygraph.EdgeIteratorStateHelper; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.routing.util.PathProcessor; -import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import com.graphhopper.routing.weighting.PriorityWeighting; import com.graphhopper.storage.GraphExtension; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.PMap; import com.graphhopper.util.PointList; -import org.locationtech.jts.geom.Coordinate; +import org.apache.log4j.Logger; import org.heigit.ors.routing.RouteExtraInfo; import org.heigit.ors.routing.RouteExtraInfoFlag; import org.heigit.ors.routing.RoutingProfileType; @@ -31,14 +30,15 @@ import org.heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersPolygon; import org.heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersReader; import org.heigit.ors.routing.graphhopper.extensions.storages.*; +import org.heigit.ors.routing.graphhopper.extensions.util.PriorityCode; import org.heigit.ors.routing.parameters.ProfileParameters; import org.heigit.ors.routing.util.ElevationSmoother; import org.heigit.ors.routing.util.WaySurfaceDescription; +import org.heigit.ors.routing.util.extrainfobuilders.AppendableRouteExtraInfoBuilder; import org.heigit.ors.routing.util.extrainfobuilders.AppendableSteepnessExtraInfoBuilder; import org.heigit.ors.routing.util.extrainfobuilders.RouteExtraInfoBuilder; -import org.heigit.ors.routing.util.extrainfobuilders.AppendableRouteExtraInfoBuilder; import org.heigit.ors.routing.util.extrainfobuilders.SteepnessExtraInfoBuilder; -import org.apache.log4j.Logger; +import org.locationtech.jts.geom.Coordinate; import java.util.ArrayList; import java.util.List; @@ -46,512 +46,510 @@ import static com.graphhopper.routing.util.EncodingManager.getKey; public class ExtraInfoProcessor implements PathProcessor { - private WaySurfaceTypeGraphStorage extWaySurface; - private WayCategoryGraphStorage extWayCategory; - private GreenIndexGraphStorage extGreenIndex; - private NoiseIndexGraphStorage extNoiseIndex; - private TollwaysGraphStorage extTollways; - private TrailDifficultyScaleGraphStorage extTrailDifficulty; - private HillIndexGraphStorage extHillIndex; - private OsmIdGraphStorage extOsmId; - private RoadAccessRestrictionsGraphStorage extRoadAccessRestrictions; - private BordersGraphStorage extCountryTraversalInfo; - private CsvGraphStorage extCsvData; - private ShadowIndexGraphStorage extShadowIndex; - - private RouteExtraInfo surfaceInfo; - private RouteExtraInfoBuilder surfaceInfoBuilder; - - private RouteExtraInfo wayTypeInfo; - private RouteExtraInfoBuilder wayTypeInfoBuilder; - - private RouteExtraInfo steepnessInfo; - private SteepnessExtraInfoBuilder steepnessInfoBuilder; - - private RouteExtraInfo waySuitabilityInfo; - private RouteExtraInfoBuilder waySuitabilityInfoBuilder; - - private RouteExtraInfo wayCategoryInfo; - private RouteExtraInfoBuilder wayCategoryInfoBuilder; - - private RouteExtraInfo greenInfo; - private RouteExtraInfoBuilder greenInfoBuilder; - - private RouteExtraInfo noiseInfo; - private RouteExtraInfoBuilder noiseInfoBuilder; - - private RouteExtraInfo avgSpeedInfo; - private RouteExtraInfoBuilder avgSpeedInfoBuilder; - - private RouteExtraInfo tollwaysInfo; - private RouteExtraInfoBuilder tollwaysInfoBuilder; - private TollwayExtractor tollwayExtractor; - - private RouteExtraInfo trailDifficultyInfo; - private RouteExtraInfoBuilder trailDifficultyInfoBuilder; - - private RouteExtraInfo osmIdInfo; - private RouteExtraInfoBuilder osmIdInfoBuilder; - - private RouteExtraInfo roadAccessRestrictionsInfo; - private RouteExtraInfoBuilder roadAccessRestrictionsInfoBuilder; - - private RouteExtraInfo countryTraversalInfo; - private RouteExtraInfoBuilder countryTraversalInfoBuilder; - - private RouteExtraInfo csvInfo; - private RouteExtraInfoBuilder csvInfoBuilder; - int csvColumn = 0; - - private RouteExtraInfo shadowInfo; - private RouteExtraInfoBuilder shadowInfoBuilder; - - private List warningExtensions; - - private int profileType = RoutingProfileType.UNKNOWN; - private final FlagEncoder encoder; - private final boolean encoderWithPriority; - private final byte[] buffer; - private static final Logger LOGGER = Logger.getLogger(ExtraInfoProcessor.class.getName()); - - private String skippedExtraInfo = ""; - - private CountryBordersReader countryBordersReader; - - ExtraInfoProcessor(PMap opts, GraphHopperStorage graphHopperStorage, FlagEncoder enc, CountryBordersReader cbReader) throws Exception { - this(opts, graphHopperStorage, enc); - this.countryBordersReader = cbReader; - } - - ExtraInfoProcessor(PMap opts, GraphHopperStorage graphHopperStorage, FlagEncoder enc) throws Exception { - encoder = enc; - encoderWithPriority = encoder.supports(PriorityWeighting.class); - List skippedExtras = new ArrayList<>(); - - try { - PMap params = opts; - if (params == null) { - params = new PMap(); - } - - int extraInfo = params.getInt("routing_extra_info", 0); - profileType = params.getInt("routing_profile_type", 0); - ProfileParameters profileParameters = params.getObject("routing_profile_params", new ProfileParameters()); - boolean suppressWarnings = params.getBool("routing_suppress_warnings", false); - - warningExtensions = new ArrayList<>(); - - if(!suppressWarnings) - applyWarningExtensions(graphHopperStorage); - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.WAY_CATEGORY)) { - extWayCategory = GraphStorageUtils.getGraphExtension(graphHopperStorage, WayCategoryGraphStorage.class); - if (extWayCategory != null) { - wayCategoryInfo = new RouteExtraInfo("waycategory"); - wayCategoryInfoBuilder = new AppendableRouteExtraInfoBuilder(wayCategoryInfo); - } else { - skippedExtras.add("waycategory"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SURFACE) || includeExtraInfo(extraInfo, RouteExtraInfoFlag.WAY_TYPE)) { - extWaySurface = GraphStorageUtils.getGraphExtension(graphHopperStorage, WaySurfaceTypeGraphStorage.class); - if (extWaySurface != null) { - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SURFACE)) { - surfaceInfo = new RouteExtraInfo("surface"); - surfaceInfoBuilder = new AppendableRouteExtraInfoBuilder(surfaceInfo); - } - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.WAY_TYPE)) { - wayTypeInfo = new RouteExtraInfo("waytypes"); - wayTypeInfoBuilder = new AppendableRouteExtraInfoBuilder(wayTypeInfo); - } - } else { - skippedExtras.add("surface/waytypes"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.STEEPNESS)) { - if ("true".equals(graphHopperStorage.getProperties().get("elevation"))) { - steepnessInfo = new RouteExtraInfo("steepness"); - steepnessInfoBuilder = new AppendableSteepnessExtraInfoBuilder(steepnessInfo); - } else { - skippedExtras.add("steepness"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SUITABILITY)) { - waySuitabilityInfo = new RouteExtraInfo("suitability"); - waySuitabilityInfoBuilder = new AppendableRouteExtraInfoBuilder(waySuitabilityInfo); - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.AVG_SPEED)) { - avgSpeedInfo = new RouteExtraInfo("avgspeed"); - avgSpeedInfo.setFactor(10); - avgSpeedInfoBuilder = new AppendableRouteExtraInfoBuilder(avgSpeedInfo); - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.TOLLWAYS)) { - extTollways = GraphStorageUtils.getGraphExtension(graphHopperStorage, TollwaysGraphStorage.class); - if (extTollways != null) { - tollwaysInfo = new RouteExtraInfo("tollways", extTollways); - tollwaysInfoBuilder = new AppendableRouteExtraInfoBuilder(tollwaysInfo); - tollwayExtractor = new TollwayExtractor(extTollways, profileType, profileParameters); - } else { - skippedExtras.add("tollways"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.TRAIL_DIFFICULTY)) { - extTrailDifficulty = GraphStorageUtils.getGraphExtension(graphHopperStorage, TrailDifficultyScaleGraphStorage.class); - extHillIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, HillIndexGraphStorage.class); - - trailDifficultyInfo = new RouteExtraInfo("traildifficulty"); - trailDifficultyInfoBuilder = new AppendableRouteExtraInfoBuilder(trailDifficultyInfo); - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.GREEN)) { - extGreenIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, GreenIndexGraphStorage.class); - if (extGreenIndex != null) { - greenInfo = new RouteExtraInfo("green"); - greenInfoBuilder = new AppendableRouteExtraInfoBuilder(greenInfo); - } else { - skippedExtras.add("green"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.NOISE)) { - extNoiseIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, NoiseIndexGraphStorage.class); - if (extNoiseIndex != null) { - noiseInfo = new RouteExtraInfo("noise"); - noiseInfoBuilder = new AppendableRouteExtraInfoBuilder(noiseInfo); - } else { - skippedExtras.add("noise"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SHADOW)) { - extShadowIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, ShadowIndexGraphStorage.class); - if (extShadowIndex != null) { - shadowInfo = new RouteExtraInfo("shadow"); - shadowInfoBuilder = new AppendableRouteExtraInfoBuilder(shadowInfo); - } else { - skippedExtras.add("shadow"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.OSM_ID)) { - extOsmId = GraphStorageUtils.getGraphExtension(graphHopperStorage, OsmIdGraphStorage.class); - if (extOsmId != null) { - osmIdInfo = new RouteExtraInfo("osmId"); - osmIdInfoBuilder = new AppendableRouteExtraInfoBuilder(osmIdInfo); - } else { - skippedExtras.add("osmid"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.ROAD_ACCESS_RESTRICTIONS)) { - extRoadAccessRestrictions = GraphStorageUtils.getGraphExtension(graphHopperStorage, RoadAccessRestrictionsGraphStorage.class); - if (extRoadAccessRestrictions != null) { - roadAccessRestrictionsInfo = new RouteExtraInfo("roadaccessrestrictions", extRoadAccessRestrictions); - roadAccessRestrictionsInfoBuilder = new AppendableRouteExtraInfoBuilder(roadAccessRestrictionsInfo); - } else { - skippedExtras.add("roadaccessrestrictions"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.COUNTRY_INFO)) { - extCountryTraversalInfo = GraphStorageUtils.getGraphExtension(graphHopperStorage, BordersGraphStorage.class); - if (extCountryTraversalInfo != null) { - countryTraversalInfo = new RouteExtraInfo("countryinfo", extCountryTraversalInfo); - countryTraversalInfoBuilder = new AppendableRouteExtraInfoBuilder(countryTraversalInfo); - } else { - skippedExtras.add("countryinfo"); - } - } - - if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.CSV)) { - extCsvData = GraphStorageUtils.getGraphExtension(graphHopperStorage, CsvGraphStorage.class); - if (extCsvData != null) { - csvInfo = new RouteExtraInfo("csv"); - csvInfoBuilder = new AppendableRouteExtraInfoBuilder(csvInfo); - csvColumn = extCsvData.columnIndex(params.getString("weighting_#csv#column", "")); - } else { - skippedExtras.add("csv"); - } - } - } catch (Exception ex) { - LOGGER.error(ex); - } - if (!skippedExtras.isEmpty()) { - skippedExtraInfo = String.join(", ", skippedExtras); - } - buffer = new byte[4]; - } - - /** - * Loop through the GraphExtensions of the storage and store in the warningExtensions object those that implement - * the WarningGraphExtension interface and are set to be used for generating warnings. - * - * @param graphHopperStorage the storage containing the warnings - */ - private void applyWarningExtensions(GraphHopperStorage graphHopperStorage) { - GraphExtension[] extensions = graphHopperStorage.getExtensions().getExtensions(); - for(GraphExtension ge : extensions) { - if (ge instanceof WarningGraphExtension extension && extension.isUsedForWarning()) { - warningExtensions.add(RouteExtraInfoFlag.getFromString(extension.getName())); - } - } - } - - /** - * Check if the extra info should be included in the generation or not by looking at the encoded extras value and - * the list of warning extras. - * - * @param encodedExtras The encoded value stating which extras were passed explicitly - * @param infoFlag The id of the extra info whose inclusion needs to be decided - * - */ - private boolean includeExtraInfo(int encodedExtras, int infoFlag) { - return RouteExtraInfoFlag.isSet(encodedExtras, infoFlag) || warningExtensions.contains(infoFlag); - } - - public List getExtras() { - List extras = new ArrayList<>(); - if (surfaceInfo != null) { - surfaceInfoBuilder.finish(); - extras.add(surfaceInfo); - } - if (wayTypeInfo != null) { - wayTypeInfoBuilder.finish(); - extras.add(wayTypeInfo); - } - if (steepnessInfo != null) { - steepnessInfoBuilder.finish(); - extras.add(steepnessInfo); - } - if (waySuitabilityInfo != null) { - waySuitabilityInfoBuilder.finish(); - extras.add(waySuitabilityInfo); - } - if (wayCategoryInfo != null) { - wayCategoryInfoBuilder.finish(); - extras.add(wayCategoryInfo); - } - if (avgSpeedInfo != null) { - avgSpeedInfoBuilder.finish(); - extras.add(avgSpeedInfo); - } - if (greenInfo != null) { - greenInfoBuilder.finish(); - extras.add(greenInfo); - } - if (noiseInfo != null) { - noiseInfoBuilder.finish(); - extras.add(noiseInfo); - } - if (tollwaysInfo != null) { - tollwaysInfoBuilder.finish(); - extras.add(tollwaysInfo); - } - if (trailDifficultyInfo != null) { - trailDifficultyInfoBuilder.finish(); - extras.add(trailDifficultyInfo); - } - if (osmIdInfo != null) { - osmIdInfoBuilder.finish(); - extras.add(osmIdInfo); - } - if (roadAccessRestrictionsInfo != null) { - roadAccessRestrictionsInfoBuilder.finish(); - extras.add(roadAccessRestrictionsInfo); - } - if (countryTraversalInfo != null) { - countryTraversalInfoBuilder.finish(); - extras.add(countryTraversalInfo); - } - if (csvInfo != null) { - csvInfoBuilder.finish(); - extras.add(csvInfo); - } - if (shadowInfo != null) { - shadowInfoBuilder.finish(); - extras.add(shadowInfo); - } - return extras; - } - - public void appendData(ExtraInfoProcessor more) { - if (surfaceInfo != null) - ((AppendableRouteExtraInfoBuilder) surfaceInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.surfaceInfoBuilder); - if (wayTypeInfo != null) - ((AppendableRouteExtraInfoBuilder) wayTypeInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.wayTypeInfoBuilder); - if (steepnessInfo != null) - ((AppendableSteepnessExtraInfoBuilder) steepnessInfoBuilder).append((AppendableSteepnessExtraInfoBuilder) more.steepnessInfoBuilder); - if (waySuitabilityInfo != null) - ((AppendableRouteExtraInfoBuilder) waySuitabilityInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.waySuitabilityInfoBuilder); - if (wayCategoryInfo != null) - ((AppendableRouteExtraInfoBuilder) wayCategoryInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.wayCategoryInfoBuilder); - if (avgSpeedInfo != null) - ((AppendableRouteExtraInfoBuilder) avgSpeedInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.avgSpeedInfoBuilder); - if (greenInfo != null) - ((AppendableRouteExtraInfoBuilder) greenInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.greenInfoBuilder); - if (noiseInfo != null) - ((AppendableRouteExtraInfoBuilder) noiseInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.noiseInfoBuilder); - if (tollwaysInfo != null) - ((AppendableRouteExtraInfoBuilder) tollwaysInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.tollwaysInfoBuilder); - if (trailDifficultyInfo != null) - ((AppendableRouteExtraInfoBuilder) trailDifficultyInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.trailDifficultyInfoBuilder); - if (osmIdInfo != null) - ((AppendableRouteExtraInfoBuilder) osmIdInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.osmIdInfoBuilder); - if (roadAccessRestrictionsInfo != null) - ((AppendableRouteExtraInfoBuilder) roadAccessRestrictionsInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.roadAccessRestrictionsInfoBuilder); - if (countryTraversalInfoBuilder != null) - ((AppendableRouteExtraInfoBuilder) countryTraversalInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.countryTraversalInfoBuilder); - if (csvInfo != null) - ((AppendableRouteExtraInfoBuilder) csvInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.csvInfoBuilder); - if (shadowInfo != null) - ((AppendableRouteExtraInfoBuilder) shadowInfoBuilder).append((AppendableRouteExtraInfoBuilder)more.shadowInfoBuilder); - } - - @Override - public void processPathEdge(EdgeIteratorState edge, PointList geom) { - double dist = edge.getDistance(); - - // TODO Add extra info for crossed countries - if (extCountryTraversalInfo != null && countryBordersReader != null) { - short country1 = extCountryTraversalInfo.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), BordersGraphStorage.Property.START); - short country2 = extCountryTraversalInfo.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), BordersGraphStorage.Property.END); - // This check will correct the countries of an edge if the starting coordinate of the route lies in a different country than the start of the edge. - if (country1 != country2 && geom.size() > 0) { - Coordinate coordinate = new Coordinate(); - coordinate.x = geom.getLon(0); - coordinate.y = geom.getLat(0); - CountryBordersPolygon[] countries = countryBordersReader.getCountry(coordinate); - if (countries.length >= 1) { - country1 = Short.parseShort(countryBordersReader.getId(countryBordersReader.getCountry(coordinate)[0].getName())); - } - } - if (countryTraversalInfoBuilder != null && country1 != 0) { - countryTraversalInfoBuilder.addSegment(country1, country1, geom, dist); - } - } - - if (extWaySurface != null && wayTypeInfo != null || surfaceInfo != null) { - WaySurfaceDescription wsd = extWaySurface.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - - if (surfaceInfoBuilder != null) - surfaceInfoBuilder.addSegment(wsd.getSurfaceType(), wsd.getSurfaceType(), geom, dist); - - if (wayTypeInfo != null) - wayTypeInfoBuilder.addSegment(wsd.getWayType(), wsd.getWayType(), geom, dist); - } - - if (wayCategoryInfoBuilder != null) { - int value = extWayCategory.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - wayCategoryInfoBuilder.addSegment(value, value, geom, dist); - } - - if (trailDifficultyInfoBuilder != null) { - int value = 0; - if (RoutingProfileType.isCycling(profileType)) { - boolean uphill = false; - if (extHillIndex != null) { - boolean revert = edge.getBaseNode() > edge.getAdjNode(); - int hillIndex = extHillIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), revert, buffer); - if (hillIndex > 0) - uphill = true; - } - value = extTrailDifficulty.getMtbScale(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer, uphill); - } - else if (RoutingProfileType.isWalking(profileType)) - value = extTrailDifficulty.getHikingScale(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - - trailDifficultyInfoBuilder.addSegment(value, value, geom, dist); - } - - if (avgSpeedInfoBuilder != null) { - double speed = encoder.getAverageSpeedEnc().getDecimal(false, edge.getFlags()); - avgSpeedInfoBuilder.addSegment(speed, (int)Math.round(speed* avgSpeedInfo.getFactor()), geom, dist); - } - - if (tollwaysInfoBuilder != null) { - int value = tollwayExtractor.getValue(EdgeIteratorStateHelper.getOriginalEdge(edge)); - tollwaysInfoBuilder.addSegment(value, value, geom, dist); - } - - if (waySuitabilityInfoBuilder != null) { - double priority; - int priorityIndex; - if (encoderWithPriority) { - priority = edge.get(encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY))); - priorityIndex = (int) Math.round(3 + priority * PriorityCode.BEST.getValue()); // normalize values between 3 and 10 - } else { - priority = encoder.getAverageSpeedEnc().getDecimal(false, edge.getFlags()) / encoder.getMaxSpeed(); - if (priority < 0.3) - priority = 0.3; - priorityIndex = (int) Math.round(priority * 10); - } - waySuitabilityInfoBuilder.addSegment(priority, priorityIndex, geom, dist); - } - - if (greenInfoBuilder != null) { - int value = extGreenIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - // This number is how many levels client can display in the stats bar - // FIXME should be changed when the specific bar legend for green routing is finished - int minClientVal = 3; - int maxClientVal = 10; - int clientVal = minClientVal + value * (maxClientVal - minClientVal + 1) / 64; - greenInfoBuilder.addSegment(value, clientVal, geom, dist); - } - - if (noiseInfoBuilder != null) { - int noiseLevel = extNoiseIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - // convert the noise level (from 0 to 3) to the values (from 7 to 10) for the client - if (noiseLevel > 3) - noiseLevel = 3; - - int clientNoiseLevel = noiseLevel + 7; - noiseInfoBuilder.addSegment(noiseLevel, clientNoiseLevel, geom, dist); - } - - if (osmIdInfoBuilder != null) { - long osmId = extOsmId.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge)); - - osmIdInfoBuilder.addSegment((double)osmId, osmId, geom, dist); - } - - if (roadAccessRestrictionsInfoBuilder != null) { - int value = extRoadAccessRestrictions.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - roadAccessRestrictionsInfoBuilder.addSegment(value, value, geom, dist); - } - - if (csvInfoBuilder != null) { - int value = extCsvData.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), csvColumn, buffer); - csvInfoBuilder.addSegment(value, value, geom, dist); - } - - if (shadowInfoBuilder != null) { - int shadowLevel = extShadowIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); - shadowInfoBuilder.addSegment(shadowLevel, shadowLevel, geom, dist); - } - } - - @Override - public PointList processPoints(PointList points) { + private WaySurfaceTypeGraphStorage extWaySurface; + private WayCategoryGraphStorage extWayCategory; + private GreenIndexGraphStorage extGreenIndex; + private NoiseIndexGraphStorage extNoiseIndex; + private TollwaysGraphStorage extTollways; + private TrailDifficultyScaleGraphStorage extTrailDifficulty; + private HillIndexGraphStorage extHillIndex; + private OsmIdGraphStorage extOsmId; + private RoadAccessRestrictionsGraphStorage extRoadAccessRestrictions; + private BordersGraphStorage extCountryTraversalInfo; + private CsvGraphStorage extCsvData; + private ShadowIndexGraphStorage extShadowIndex; + + private RouteExtraInfo surfaceInfo; + private RouteExtraInfoBuilder surfaceInfoBuilder; + + private RouteExtraInfo wayTypeInfo; + private RouteExtraInfoBuilder wayTypeInfoBuilder; + + private RouteExtraInfo steepnessInfo; + private SteepnessExtraInfoBuilder steepnessInfoBuilder; + + private RouteExtraInfo waySuitabilityInfo; + private RouteExtraInfoBuilder waySuitabilityInfoBuilder; + + private RouteExtraInfo wayCategoryInfo; + private RouteExtraInfoBuilder wayCategoryInfoBuilder; + + private RouteExtraInfo greenInfo; + private RouteExtraInfoBuilder greenInfoBuilder; + + private RouteExtraInfo noiseInfo; + private RouteExtraInfoBuilder noiseInfoBuilder; + + private RouteExtraInfo avgSpeedInfo; + private RouteExtraInfoBuilder avgSpeedInfoBuilder; + + private RouteExtraInfo tollwaysInfo; + private RouteExtraInfoBuilder tollwaysInfoBuilder; + private TollwayExtractor tollwayExtractor; + + private RouteExtraInfo trailDifficultyInfo; + private RouteExtraInfoBuilder trailDifficultyInfoBuilder; + + private RouteExtraInfo osmIdInfo; + private RouteExtraInfoBuilder osmIdInfoBuilder; + + private RouteExtraInfo roadAccessRestrictionsInfo; + private RouteExtraInfoBuilder roadAccessRestrictionsInfoBuilder; + + private RouteExtraInfo countryTraversalInfo; + private RouteExtraInfoBuilder countryTraversalInfoBuilder; + + private RouteExtraInfo csvInfo; + private RouteExtraInfoBuilder csvInfoBuilder; + int csvColumn = 0; + + private RouteExtraInfo shadowInfo; + private RouteExtraInfoBuilder shadowInfoBuilder; + + private List warningExtensions; + + private int profileType = RoutingProfileType.UNKNOWN; + private final FlagEncoder encoder; + private final boolean encoderWithPriority; + private final byte[] buffer; + private static final Logger LOGGER = Logger.getLogger(ExtraInfoProcessor.class.getName()); + + private String skippedExtraInfo = ""; + + private CountryBordersReader countryBordersReader; + + ExtraInfoProcessor(PMap opts, GraphHopperStorage graphHopperStorage, FlagEncoder enc, CountryBordersReader cbReader) throws Exception { + this(opts, graphHopperStorage, enc); + this.countryBordersReader = cbReader; + } + + ExtraInfoProcessor(PMap opts, GraphHopperStorage graphHopperStorage, FlagEncoder enc) throws Exception { + encoder = enc; + encoderWithPriority = encoder.supports(PriorityWeighting.class); + List skippedExtras = new ArrayList<>(); + + try { + PMap params = opts; + if (params == null) { + params = new PMap(); + } + + int extraInfo = params.getInt("routing_extra_info", 0); + profileType = params.getInt("routing_profile_type", 0); + ProfileParameters profileParameters = params.getObject("routing_profile_params", new ProfileParameters()); + boolean suppressWarnings = params.getBool("routing_suppress_warnings", false); + + warningExtensions = new ArrayList<>(); + + if (!suppressWarnings) + applyWarningExtensions(graphHopperStorage); + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.WAY_CATEGORY)) { + extWayCategory = GraphStorageUtils.getGraphExtension(graphHopperStorage, WayCategoryGraphStorage.class); + if (extWayCategory != null) { + wayCategoryInfo = new RouteExtraInfo("waycategory"); + wayCategoryInfoBuilder = new AppendableRouteExtraInfoBuilder(wayCategoryInfo); + } else { + skippedExtras.add("waycategory"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SURFACE) || includeExtraInfo(extraInfo, RouteExtraInfoFlag.WAY_TYPE)) { + extWaySurface = GraphStorageUtils.getGraphExtension(graphHopperStorage, WaySurfaceTypeGraphStorage.class); + if (extWaySurface != null) { + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SURFACE)) { + surfaceInfo = new RouteExtraInfo("surface"); + surfaceInfoBuilder = new AppendableRouteExtraInfoBuilder(surfaceInfo); + } + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.WAY_TYPE)) { + wayTypeInfo = new RouteExtraInfo("waytypes"); + wayTypeInfoBuilder = new AppendableRouteExtraInfoBuilder(wayTypeInfo); + } + } else { + skippedExtras.add("surface/waytypes"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.STEEPNESS)) { + if ("true".equals(graphHopperStorage.getProperties().get("elevation"))) { + steepnessInfo = new RouteExtraInfo("steepness"); + steepnessInfoBuilder = new AppendableSteepnessExtraInfoBuilder(steepnessInfo); + } else { + skippedExtras.add("steepness"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SUITABILITY)) { + waySuitabilityInfo = new RouteExtraInfo("suitability"); + waySuitabilityInfoBuilder = new AppendableRouteExtraInfoBuilder(waySuitabilityInfo); + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.AVG_SPEED)) { + avgSpeedInfo = new RouteExtraInfo("avgspeed"); + avgSpeedInfo.setFactor(10); + avgSpeedInfoBuilder = new AppendableRouteExtraInfoBuilder(avgSpeedInfo); + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.TOLLWAYS)) { + extTollways = GraphStorageUtils.getGraphExtension(graphHopperStorage, TollwaysGraphStorage.class); + if (extTollways != null) { + tollwaysInfo = new RouteExtraInfo("tollways", extTollways); + tollwaysInfoBuilder = new AppendableRouteExtraInfoBuilder(tollwaysInfo); + tollwayExtractor = new TollwayExtractor(extTollways, profileType, profileParameters); + } else { + skippedExtras.add("tollways"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.TRAIL_DIFFICULTY)) { + extTrailDifficulty = GraphStorageUtils.getGraphExtension(graphHopperStorage, TrailDifficultyScaleGraphStorage.class); + extHillIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, HillIndexGraphStorage.class); + + trailDifficultyInfo = new RouteExtraInfo("traildifficulty"); + trailDifficultyInfoBuilder = new AppendableRouteExtraInfoBuilder(trailDifficultyInfo); + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.GREEN)) { + extGreenIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, GreenIndexGraphStorage.class); + if (extGreenIndex != null) { + greenInfo = new RouteExtraInfo("green"); + greenInfoBuilder = new AppendableRouteExtraInfoBuilder(greenInfo); + } else { + skippedExtras.add("green"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.NOISE)) { + extNoiseIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, NoiseIndexGraphStorage.class); + if (extNoiseIndex != null) { + noiseInfo = new RouteExtraInfo("noise"); + noiseInfoBuilder = new AppendableRouteExtraInfoBuilder(noiseInfo); + } else { + skippedExtras.add("noise"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.SHADOW)) { + extShadowIndex = GraphStorageUtils.getGraphExtension(graphHopperStorage, ShadowIndexGraphStorage.class); + if (extShadowIndex != null) { + shadowInfo = new RouteExtraInfo("shadow"); + shadowInfoBuilder = new AppendableRouteExtraInfoBuilder(shadowInfo); + } else { + skippedExtras.add("shadow"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.OSM_ID)) { + extOsmId = GraphStorageUtils.getGraphExtension(graphHopperStorage, OsmIdGraphStorage.class); + if (extOsmId != null) { + osmIdInfo = new RouteExtraInfo("osmId"); + osmIdInfoBuilder = new AppendableRouteExtraInfoBuilder(osmIdInfo); + } else { + skippedExtras.add("osmid"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.ROAD_ACCESS_RESTRICTIONS)) { + extRoadAccessRestrictions = GraphStorageUtils.getGraphExtension(graphHopperStorage, RoadAccessRestrictionsGraphStorage.class); + if (extRoadAccessRestrictions != null) { + roadAccessRestrictionsInfo = new RouteExtraInfo("roadaccessrestrictions", extRoadAccessRestrictions); + roadAccessRestrictionsInfoBuilder = new AppendableRouteExtraInfoBuilder(roadAccessRestrictionsInfo); + } else { + skippedExtras.add("roadaccessrestrictions"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.COUNTRY_INFO)) { + extCountryTraversalInfo = GraphStorageUtils.getGraphExtension(graphHopperStorage, BordersGraphStorage.class); + if (extCountryTraversalInfo != null) { + countryTraversalInfo = new RouteExtraInfo("countryinfo", extCountryTraversalInfo); + countryTraversalInfoBuilder = new AppendableRouteExtraInfoBuilder(countryTraversalInfo); + } else { + skippedExtras.add("countryinfo"); + } + } + + if (includeExtraInfo(extraInfo, RouteExtraInfoFlag.CSV)) { + extCsvData = GraphStorageUtils.getGraphExtension(graphHopperStorage, CsvGraphStorage.class); + if (extCsvData != null) { + csvInfo = new RouteExtraInfo("csv"); + csvInfoBuilder = new AppendableRouteExtraInfoBuilder(csvInfo); + csvColumn = extCsvData.columnIndex(params.getString("weighting_#csv#column", "")); + } else { + skippedExtras.add("csv"); + } + } + } catch (Exception ex) { + LOGGER.error(ex); + } + if (!skippedExtras.isEmpty()) { + skippedExtraInfo = String.join(", ", skippedExtras); + } + buffer = new byte[4]; + } + + /** + * Loop through the GraphExtensions of the storage and store in the warningExtensions object those that implement + * the WarningGraphExtension interface and are set to be used for generating warnings. + * + * @param graphHopperStorage the storage containing the warnings + */ + private void applyWarningExtensions(GraphHopperStorage graphHopperStorage) { + GraphExtension[] extensions = graphHopperStorage.getExtensions().getExtensions(); + for (GraphExtension ge : extensions) { + if (ge instanceof WarningGraphExtension extension && extension.isUsedForWarning()) { + warningExtensions.add(RouteExtraInfoFlag.getFromString(extension.getName())); + } + } + } + + /** + * Check if the extra info should be included in the generation or not by looking at the encoded extras value and + * the list of warning extras. + * + * @param encodedExtras The encoded value stating which extras were passed explicitly + * @param infoFlag The id of the extra info whose inclusion needs to be decided + */ + private boolean includeExtraInfo(int encodedExtras, int infoFlag) { + return RouteExtraInfoFlag.isSet(encodedExtras, infoFlag) || warningExtensions.contains(infoFlag); + } + + public List getExtras() { + List extras = new ArrayList<>(); + if (surfaceInfo != null) { + surfaceInfoBuilder.finish(); + extras.add(surfaceInfo); + } + if (wayTypeInfo != null) { + wayTypeInfoBuilder.finish(); + extras.add(wayTypeInfo); + } + if (steepnessInfo != null) { + steepnessInfoBuilder.finish(); + extras.add(steepnessInfo); + } + if (waySuitabilityInfo != null) { + waySuitabilityInfoBuilder.finish(); + extras.add(waySuitabilityInfo); + } + if (wayCategoryInfo != null) { + wayCategoryInfoBuilder.finish(); + extras.add(wayCategoryInfo); + } + if (avgSpeedInfo != null) { + avgSpeedInfoBuilder.finish(); + extras.add(avgSpeedInfo); + } + if (greenInfo != null) { + greenInfoBuilder.finish(); + extras.add(greenInfo); + } + if (noiseInfo != null) { + noiseInfoBuilder.finish(); + extras.add(noiseInfo); + } + if (tollwaysInfo != null) { + tollwaysInfoBuilder.finish(); + extras.add(tollwaysInfo); + } + if (trailDifficultyInfo != null) { + trailDifficultyInfoBuilder.finish(); + extras.add(trailDifficultyInfo); + } + if (osmIdInfo != null) { + osmIdInfoBuilder.finish(); + extras.add(osmIdInfo); + } + if (roadAccessRestrictionsInfo != null) { + roadAccessRestrictionsInfoBuilder.finish(); + extras.add(roadAccessRestrictionsInfo); + } + if (countryTraversalInfo != null) { + countryTraversalInfoBuilder.finish(); + extras.add(countryTraversalInfo); + } + if (csvInfo != null) { + csvInfoBuilder.finish(); + extras.add(csvInfo); + } + if (shadowInfo != null) { + shadowInfoBuilder.finish(); + extras.add(shadowInfo); + } + return extras; + } + + public void appendData(ExtraInfoProcessor more) { + if (surfaceInfo != null) + ((AppendableRouteExtraInfoBuilder) surfaceInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.surfaceInfoBuilder); + if (wayTypeInfo != null) + ((AppendableRouteExtraInfoBuilder) wayTypeInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.wayTypeInfoBuilder); + if (steepnessInfo != null) + ((AppendableSteepnessExtraInfoBuilder) steepnessInfoBuilder).append((AppendableSteepnessExtraInfoBuilder) more.steepnessInfoBuilder); + if (waySuitabilityInfo != null) + ((AppendableRouteExtraInfoBuilder) waySuitabilityInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.waySuitabilityInfoBuilder); + if (wayCategoryInfo != null) + ((AppendableRouteExtraInfoBuilder) wayCategoryInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.wayCategoryInfoBuilder); + if (avgSpeedInfo != null) + ((AppendableRouteExtraInfoBuilder) avgSpeedInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.avgSpeedInfoBuilder); + if (greenInfo != null) + ((AppendableRouteExtraInfoBuilder) greenInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.greenInfoBuilder); + if (noiseInfo != null) + ((AppendableRouteExtraInfoBuilder) noiseInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.noiseInfoBuilder); + if (tollwaysInfo != null) + ((AppendableRouteExtraInfoBuilder) tollwaysInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.tollwaysInfoBuilder); + if (trailDifficultyInfo != null) + ((AppendableRouteExtraInfoBuilder) trailDifficultyInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.trailDifficultyInfoBuilder); + if (osmIdInfo != null) + ((AppendableRouteExtraInfoBuilder) osmIdInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.osmIdInfoBuilder); + if (roadAccessRestrictionsInfo != null) + ((AppendableRouteExtraInfoBuilder) roadAccessRestrictionsInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.roadAccessRestrictionsInfoBuilder); + if (countryTraversalInfoBuilder != null) + ((AppendableRouteExtraInfoBuilder) countryTraversalInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.countryTraversalInfoBuilder); + if (csvInfo != null) + ((AppendableRouteExtraInfoBuilder) csvInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.csvInfoBuilder); + if (shadowInfo != null) + ((AppendableRouteExtraInfoBuilder) shadowInfoBuilder).append((AppendableRouteExtraInfoBuilder) more.shadowInfoBuilder); + } + + @Override + public void processPathEdge(EdgeIteratorState edge, PointList geom) { + double dist = edge.getDistance(); + + // TODO Add extra info for crossed countries + if (extCountryTraversalInfo != null && countryBordersReader != null) { + short country1 = extCountryTraversalInfo.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), BordersGraphStorage.Property.START); + short country2 = extCountryTraversalInfo.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), BordersGraphStorage.Property.END); + // This check will correct the countries of an edge if the starting coordinate of the route lies in a different country than the start of the edge. + if (country1 != country2 && geom.size() > 0) { + Coordinate coordinate = new Coordinate(); + coordinate.x = geom.getLon(0); + coordinate.y = geom.getLat(0); + CountryBordersPolygon[] countries = countryBordersReader.getCountry(coordinate); + if (countries.length >= 1) { + country1 = Short.parseShort(countryBordersReader.getId(countryBordersReader.getCountry(coordinate)[0].getName())); + } + } + if (countryTraversalInfoBuilder != null && country1 != 0) { + countryTraversalInfoBuilder.addSegment(country1, country1, geom, dist); + } + } + + if (extWaySurface != null && wayTypeInfo != null || surfaceInfo != null) { + WaySurfaceDescription wsd = extWaySurface.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + + if (surfaceInfoBuilder != null) + surfaceInfoBuilder.addSegment(wsd.getSurfaceType(), wsd.getSurfaceType(), geom, dist); + + if (wayTypeInfo != null) + wayTypeInfoBuilder.addSegment(wsd.getWayType(), wsd.getWayType(), geom, dist); + } + + if (wayCategoryInfoBuilder != null) { + int value = extWayCategory.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + wayCategoryInfoBuilder.addSegment(value, value, geom, dist); + } + + if (trailDifficultyInfoBuilder != null) { + int value = 0; + if (RoutingProfileType.isCycling(profileType)) { + boolean uphill = false; + if (extHillIndex != null) { + boolean revert = edge.getBaseNode() > edge.getAdjNode(); + int hillIndex = extHillIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), revert, buffer); + if (hillIndex > 0) + uphill = true; + } + value = extTrailDifficulty.getMtbScale(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer, uphill); + } else if (RoutingProfileType.isWalking(profileType)) + value = extTrailDifficulty.getHikingScale(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + + trailDifficultyInfoBuilder.addSegment(value, value, geom, dist); + } + + if (avgSpeedInfoBuilder != null) { + double speed = encoder.getAverageSpeedEnc().getDecimal(false, edge.getFlags()); + avgSpeedInfoBuilder.addSegment(speed, (int) Math.round(speed * avgSpeedInfo.getFactor()), geom, dist); + } + + if (tollwaysInfoBuilder != null) { + int value = tollwayExtractor.getValue(EdgeIteratorStateHelper.getOriginalEdge(edge)); + tollwaysInfoBuilder.addSegment(value, value, geom, dist); + } + + if (waySuitabilityInfoBuilder != null) { + double priority; + int priorityIndex; + if (encoderWithPriority) { + priority = edge.get(encoder.getDecimalEncodedValue(getKey(encoder, FlagEncoderKeys.PRIORITY_KEY))); + priorityIndex = (int) Math.round(3 + priority * PriorityCode.BEST.getValue()); // normalize values between 3 and 10 + } else { + priority = encoder.getAverageSpeedEnc().getDecimal(false, edge.getFlags()) / encoder.getMaxSpeed(); + if (priority < 0.3) + priority = 0.3; + priorityIndex = (int) Math.round(priority * 10); + } + waySuitabilityInfoBuilder.addSegment(priority, priorityIndex, geom, dist); + } + + if (greenInfoBuilder != null) { + int value = extGreenIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + // This number is how many levels client can display in the stats bar + // FIXME should be changed when the specific bar legend for green routing is finished + int minClientVal = 3; + int maxClientVal = 10; + int clientVal = minClientVal + value * (maxClientVal - minClientVal + 1) / 64; + greenInfoBuilder.addSegment(value, clientVal, geom, dist); + } + + if (noiseInfoBuilder != null) { + int noiseLevel = extNoiseIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + // convert the noise level (from 0 to 3) to the values (from 7 to 10) for the client + if (noiseLevel > 3) + noiseLevel = 3; + + int clientNoiseLevel = noiseLevel + 7; + noiseInfoBuilder.addSegment(noiseLevel, clientNoiseLevel, geom, dist); + } + + if (osmIdInfoBuilder != null) { + long osmId = extOsmId.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge)); + + osmIdInfoBuilder.addSegment((double) osmId, osmId, geom, dist); + } + + if (roadAccessRestrictionsInfoBuilder != null) { + int value = extRoadAccessRestrictions.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + roadAccessRestrictionsInfoBuilder.addSegment(value, value, geom, dist); + } + + if (csvInfoBuilder != null) { + int value = extCsvData.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), csvColumn, buffer); + csvInfoBuilder.addSegment(value, value, geom, dist); + } + + if (shadowInfoBuilder != null) { + int shadowLevel = extShadowIndex.getEdgeValue(EdgeIteratorStateHelper.getOriginalEdge(edge), buffer); + shadowInfoBuilder.addSegment(shadowLevel, shadowLevel, geom, dist); + } + } + + @Override + public PointList processPoints(PointList points) { PointList result = points; - if (points.is3D()) - result = ElevationSmoother.smooth(points); + if (points.is3D()) + result = ElevationSmoother.smooth(points); - if (steepnessInfoBuilder != null) { - // compute steepness information only after elevation data is smoothed. - steepnessInfoBuilder.addPoints(result); - } + if (steepnessInfoBuilder != null) { + // compute steepness information only after elevation data is smoothed. + steepnessInfoBuilder.addPoints(result); + } - return result; - } + return result; + } - public String getSkippedExtraInfo() { - return skippedExtraInfo; - } + public String getSkippedExtraInfo() { + return skippedExtraInfo; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ORSPathProcessorFactory.java b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ORSPathProcessorFactory.java index 0e9fcbfb64..348dfa2803 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ORSPathProcessorFactory.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/ORSPathProcessorFactory.java @@ -5,9 +5,8 @@ import com.graphhopper.routing.util.PathProcessorFactory; import com.graphhopper.storage.GraphHopperStorage; import com.graphhopper.util.PMap; - -import org.heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersReader; import org.apache.log4j.Logger; +import org.heigit.ors.routing.graphhopper.extensions.reader.borders.CountryBordersReader; public class ORSPathProcessorFactory implements PathProcessorFactory { private static final Logger LOGGER = Logger.getLogger(ORSPathProcessorFactory.class.getName()); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/TollwayExtractor.java b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/TollwayExtractor.java index b0068d929b..5c636e5cc4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/TollwayExtractor.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/pathprocessors/TollwayExtractor.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.pathprocessors; @@ -21,56 +21,57 @@ import org.heigit.ors.routing.parameters.VehicleParameters; public class TollwayExtractor { - private VehicleParameters vehicleParams; - private final int profileType; - private final TollwaysGraphStorage storage; + private VehicleParameters vehicleParams; + private final int profileType; + private final TollwaysGraphStorage storage; - public TollwayExtractor(TollwaysGraphStorage storage, int profileType, ProfileParameters vehicleParams) { - this.storage = storage; - this.profileType = profileType; - if (vehicleParams instanceof VehicleParameters parameters) - this.vehicleParams = parameters; - } - /** - * return if a way is a tollway for the configured vehicle. - * - * @param edgeId The edgeId for which toll should be checked - * @see HeavyVehicleAttributes - */ - public int getValue(int edgeId) { - int value = storage.getEdgeValue(edgeId); + public TollwayExtractor(TollwaysGraphStorage storage, int profileType, ProfileParameters vehicleParams) { + this.storage = storage; + this.profileType = profileType; + if (vehicleParams instanceof VehicleParameters parameters) + this.vehicleParams = parameters; + } - switch (value) { - // toll=no - case TollwayType.NONE: - return 0; - // toll=yes - case TollwayType.GENERAL: - return 1; - default: - switch(profileType) { - // toll:motorcar - case RoutingProfileType.DRIVING_CAR: - return TollwayType.isSet(TollwayType.MOTORCAR, value) ? 1 : 0; + /** + * return if a way is a tollway for the configured vehicle. + * + * @param edgeId The edgeId for which toll should be checked + * @see HeavyVehicleAttributes + */ + public int getValue(int edgeId) { + int value = storage.getEdgeValue(edgeId); - case RoutingProfileType.DRIVING_HGV: - // toll:hgv - if (TollwayType.isSet(TollwayType.HGV, value)) - return 1; + switch (value) { + // toll=no + case TollwayType.NONE: + return 0; + // toll=yes + case TollwayType.GENERAL: + return 1; + default: + switch (profileType) { + // toll:motorcar + case RoutingProfileType.DRIVING_CAR: + return TollwayType.isSet(TollwayType.MOTORCAR, value) ? 1 : 0; - // check for weight specific toll tags even when weight is unset - double weight = vehicleParams ==null ? 0 : vehicleParams.getWeight(); - if ((weight == 0 && TollwayType.isNType(value)) - || (weight < 3.5 && TollwayType.isSet(TollwayType.N1, value)) - || (weight >= 3.5 && weight < 12 && TollwayType.isSet(TollwayType.N2, value)) - || (weight >= 12 && TollwayType.isSet(TollwayType.N3, value))) - return 1; - return 0; - default: - return 0; - } - } + case RoutingProfileType.DRIVING_HGV: + // toll:hgv + if (TollwayType.isSet(TollwayType.HGV, value)) + return 1; - } + // check for weight specific toll tags even when weight is unset + double weight = vehicleParams == null ? 0 : vehicleParams.getWeight(); + if ((weight == 0 && TollwayType.isNType(value)) + || (weight < 3.5 && TollwayType.isSet(TollwayType.N1, value)) + || (weight >= 3.5 && weight < 12 && TollwayType.isSet(TollwayType.N2, value)) + || (weight >= 12 && TollwayType.isSet(TollwayType.N3, value))) + return 1; + return 0; + default: + return 0; + } + } + + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/traffic/RoutingTrafficSpeedCalculator.java b/ors-engine/src/main/java/org/heigit/ors/routing/traffic/RoutingTrafficSpeedCalculator.java index aa5ed93ec3..b24399076b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/traffic/RoutingTrafficSpeedCalculator.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/traffic/RoutingTrafficSpeedCalculator.java @@ -6,7 +6,7 @@ import com.graphhopper.util.EdgeIteratorState; public class RoutingTrafficSpeedCalculator extends TrafficSpeedCalculator { - private double maxPossibleSpeed; + private final double maxPossibleSpeed; public RoutingTrafficSpeedCalculator(SpeedCalculator superSpeedCalculator, GraphHopperStorage graphHopperStorage, FlagEncoder flagEncoder) { super(superSpeedCalculator); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/traffic/TrafficSpeedCalculator.java b/ors-engine/src/main/java/org/heigit/ors/routing/traffic/TrafficSpeedCalculator.java index 77b4e75da7..84a5ff417d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/traffic/TrafficSpeedCalculator.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/traffic/TrafficSpeedCalculator.java @@ -22,7 +22,7 @@ public class TrafficSpeedCalculator extends AbstractAdjustedSpeedCalculator { private VehicleFlagEncoder vehicleFlagEncoder; private boolean isVehicle = false; private boolean isHGV = false; - private double HGVTrafficSpeedLimit = 80.0; + private final double HGVTrafficSpeedLimit = 80.0; public TrafficSpeedCalculator(SpeedCalculator superSpeedCalculator) { super(superSpeedCalculator); @@ -70,8 +70,7 @@ protected int getEdgeKey(EdgeIteratorState edge, boolean reverse) { int edgeKey; if (edge instanceof VirtualEdgeIteratorState iteratorState) { edgeKey = iteratorState.getOriginalEdgeKey(); - } - else { + } else { edgeKey = edge.getEdgeKey(); } if (reverse) diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/ElevationSmoother.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/ElevationSmoother.java index 0733edbd35..0197d3cb45 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/ElevationSmoother.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/ElevationSmoother.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.util; @@ -20,76 +20,77 @@ import java.util.LinkedList; public class ElevationSmoother { - private ElevationSmoother() {} - - public static PointList smooth(PointList points) { - int nSize = points.size(); - if (nSize <= 2) - return points; - - DistanceCalc distCalc = new DistanceCalc3D(); - final double MIN_DISTANCE = 10; - final int WINDOW_SIZE = 20; - - PointList newPoints = new PointList(nSize, true); - LinkedList values = new LinkedList<>(); - - double x0; - double y0; - double z0; - double x1; - double y1; - double z1; - double elevSum = 0.0; - - x0 = points.getLon(0); - y0 = points.getLat(0); - z0 = points.getEle(0); - - elevSum += z0; - values.addLast(z0); - - newPoints.add(y0, x0, z0); - - for (int i = 1; i < nSize; ++i) { - x1 = points.getLon(i); - y1 = points.getLat(i); - z1 = points.getEle(i); - - double dist = distCalc.calcDist(y0, x0, y1, x1); - if (dist > MIN_DISTANCE) { - int n = (int)Math.ceil(dist / MIN_DISTANCE); - - for (int j = 1; j < n; j++) { - double ele = z0 + j*(z1 -z0)/((double)(n-1)); - - if (values.size() == WINDOW_SIZE) { - elevSum -= values.getFirst(); - values.removeFirst(); - } - - elevSum += ele; - values.addLast(ele); - } - } else { - if (values.size() == WINDOW_SIZE) { - elevSum -= values.getFirst(); - values.removeFirst(); - } - - elevSum += z1; - values.addLast(z1); - } - - double ele = elevSum / values.size(); - - newPoints.add(y1, x1, ele); - - x0 = x1; - y0 = y1; - z0 = z1; - } - - return newPoints; - } + private ElevationSmoother() { + } + + public static PointList smooth(PointList points) { + int nSize = points.size(); + if (nSize <= 2) + return points; + + DistanceCalc distCalc = new DistanceCalc3D(); + final double MIN_DISTANCE = 10; + final int WINDOW_SIZE = 20; + + PointList newPoints = new PointList(nSize, true); + LinkedList values = new LinkedList<>(); + + double x0; + double y0; + double z0; + double x1; + double y1; + double z1; + double elevSum = 0.0; + + x0 = points.getLon(0); + y0 = points.getLat(0); + z0 = points.getEle(0); + + elevSum += z0; + values.addLast(z0); + + newPoints.add(y0, x0, z0); + + for (int i = 1; i < nSize; ++i) { + x1 = points.getLon(i); + y1 = points.getLat(i); + z1 = points.getEle(i); + + double dist = distCalc.calcDist(y0, x0, y1, x1); + if (dist > MIN_DISTANCE) { + int n = (int) Math.ceil(dist / MIN_DISTANCE); + + for (int j = 1; j < n; j++) { + double ele = z0 + j * (z1 - z0) / ((double) (n - 1)); + + if (values.size() == WINDOW_SIZE) { + elevSum -= values.getFirst(); + values.removeFirst(); + } + + elevSum += ele; + values.addLast(ele); + } + } else { + if (values.size() == WINDOW_SIZE) { + elevSum -= values.getFirst(); + values.removeFirst(); + } + + elevSum += z1; + values.addLast(z1); + } + + double ele = elevSum / values.size(); + + newPoints.add(y1, x1, ele); + + x0 = x1; + y0 = y1; + z0 = z1; + } + + return newPoints; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/HillIndexCalculator.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/HillIndexCalculator.java index 6deddb1173..367e4bc046 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/HillIndexCalculator.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/HillIndexCalculator.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.util; @@ -21,37 +21,37 @@ import java.util.List; public class HillIndexCalculator { - private final DistanceCalc distCalc; - private final List splits; - - public HillIndexCalculator() { - distCalc = new DistanceCalc3D(); - splits = new ArrayList<>(); - } - + private final DistanceCalc distCalc; + private final List splits; + + public HillIndexCalculator() { + distCalc = new DistanceCalc3D(); + splits = new ArrayList<>(); + } + // the formula for hillIndex is taken from http://www.roberts-1.com/bikehudson/r/m/hilliness/#grade - public byte getHillIndex(PointList points, boolean reverse) { - SteepnessUtil.computeRouteSplits(points, reverse, distCalc, splits); - - double totalVerticalClimb = 0.0; - double excessSteepClimb = 0.0; - double totalDistance = 0.0; - - for(RouteSplit split : splits) { - double gradient = split.gradient; - if (gradient > 0) { - double vc = split.verticalClimb *3.28084; - totalVerticalClimb += vc; - } - totalDistance += split.length *0.000621371; - } - - if (totalDistance == 0.0) { - return 0; - } - - int hillIndex = (int)(100*(totalVerticalClimb + excessSteepClimb)/(5280*totalDistance)); - - return (hillIndex >= 35) ? 35 : (byte)hillIndex; - } + public byte getHillIndex(PointList points, boolean reverse) { + SteepnessUtil.computeRouteSplits(points, reverse, distCalc, splits); + + double totalVerticalClimb = 0.0; + double excessSteepClimb = 0.0; + double totalDistance = 0.0; + + for (RouteSplit split : splits) { + double gradient = split.gradient; + if (gradient > 0) { + double vc = split.verticalClimb * 3.28084; + totalVerticalClimb += vc; + } + totalDistance += split.length * 0.000621371; + } + + if (totalDistance == 0.0) { + return 0; + } + + int hillIndex = (int) (100 * (totalVerticalClimb + excessSteepClimb) / (5280 * totalDistance)); + + return (hillIndex >= 35) ? 35 : (byte) hillIndex; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/SteepnessUtil.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/SteepnessUtil.java index 12c402a3ba..229455e340 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/SteepnessUtil.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/SteepnessUtil.java @@ -24,7 +24,7 @@ public static int getCategory(double value) { if (absValue < 1.0) res = 0; // 1-3%: Slightly uphill but not particularly challenging. A bit like riding into the wind. - else if (absValue >=1 && absValue < 4) + else if (absValue >= 1 && absValue < 4) res = 1; // 4-6%: A manageable gradient that can cause fatigue over long periods. else if (absValue >= 4 && absValue < 7) @@ -39,7 +39,7 @@ else if (absValue >= 10 && absValue < 16) else if (absValue >= 16) res = 5; - return res*((value > 0) ? 1 :-1); + return res * ((value > 0) ? 1 : -1); } public static void computeRouteSplits(PointList points, boolean reverse, DistanceCalc dc, List splits) { @@ -49,7 +49,7 @@ public static void computeRouteSplits(PointList points, boolean reverse, Distanc return; int nPoints = points.size(); - int i0 = reverse ? nPoints - 1 :0; + int i0 = reverse ? nPoints - 1 : 0; double maxAltitude = Double.MIN_VALUE; double minAltitude = Double.MAX_VALUE; double prevMinAltitude; @@ -93,12 +93,12 @@ public static void computeRouteSplits(PointList points, boolean reverse, Distanc if (maxAltitude - z1 > ELEVATION_THRESHOLD || z1 - minAltitude > ELEVATION_THRESHOLD) { boolean bApply = true; int elevSign = cumElev > 0 ? 1 : -1; - double gradient = elevSign*100*(prevMaxAltitude - prevMinAltitude) / splitLength; + double gradient = elevSign * 100 * (prevMaxAltitude - prevMinAltitude) / splitLength; if (Double.isNaN(gradient) || Math.abs(gradient) > 30) // possibly noise gradient = 0.0; if (prevGC != 0) { - double zn= Double.MIN_NORMAL; + double zn = Double.MIN_NORMAL; if (!reverse) { if (jj + 1 < nPoints) @@ -109,13 +109,13 @@ public static void computeRouteSplits(PointList points, boolean reverse, Distanc } if (zn != Double.MIN_VALUE) { - double elevGap = length/30; + double elevGap = length / 30; if ( - ( - elevSign > 0 && prevGC > 0 || prevGC < 0 - ) - && Math.abs(zn - z1) < elevGap) { - bApply = false; + ( + elevSign > 0 && prevGC > 0 || prevGC < 0 + ) + && Math.abs(zn - z1) < elevGap) { + bApply = false; } } } @@ -133,7 +133,7 @@ public static void computeRouteSplits(PointList points, boolean reverse, Distanc if (reverse) { split.start = iEnd; split.end = iStart; - splits.add(0,split); + splits.add(0, split); } else { split.start = iStart; split.end = iEnd; @@ -148,7 +148,7 @@ public static void computeRouteSplits(PointList points, boolean reverse, Distanc maxAltitude = Math.max(z0, z1); splitLength = 0.0; - cumElev= elevDiff; + cumElev = elevDiff; } } @@ -163,7 +163,7 @@ public static void computeRouteSplits(PointList points, boolean reverse, Distanc double elevDiff = maxAltitude - minAltitude; if (splits.isEmpty() && splitLength < 50 && elevDiff < ELEVATION_THRESHOLD) elevDiff = 0; - double gradient = (cumElev > 0 ? 1: -1)*100*elevDiff / splitLength; + double gradient = (cumElev > 0 ? 1 : -1) * 100 * elevDiff / splitLength; if (Math.abs(gradient) > 7 && maxAltitude < 100 && splitLength < 120) gradient = 0.0; // noise @@ -180,7 +180,7 @@ public static void computeRouteSplits(PointList points, boolean reverse, Distanc if (reverse) { lastSplit.start = iEnd; lastSplit.end = iStart; - splits.add(0,lastSplit); + splits.add(0, lastSplit); } else { lastSplit.start = iStart; lastSplit.end = iEnd; diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/WaySurfaceDescription.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/WaySurfaceDescription.java index 14ffeb7145..d04961e9d0 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/WaySurfaceDescription.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/WaySurfaceDescription.java @@ -9,7 +9,7 @@ public byte getWayType() { } public void setWayType(int wayType) { - this.wayType = (byte)wayType; + this.wayType = (byte) wayType; } public byte getSurfaceType() { @@ -17,7 +17,7 @@ public byte getSurfaceType() { } public void setSurfaceType(int surfaceType) { - this.surfaceType = (byte)surfaceType; + this.surfaceType = (byte) surfaceType; } public void reset() { diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableRouteExtraInfoBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableRouteExtraInfoBuilder.java index e14f766ae5..0667f7662f 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableRouteExtraInfoBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableRouteExtraInfoBuilder.java @@ -21,44 +21,45 @@ import java.util.List; public class AppendableRouteExtraInfoBuilder extends SimpleRouteExtraInfoBuilder { - private final ArrayList segmentParamsList; + private final ArrayList segmentParamsList; public AppendableRouteExtraInfoBuilder(RouteExtraInfo extraInfo) { - super(extraInfo); - segmentParamsList = new ArrayList<>(); - } + super(extraInfo); + segmentParamsList = new ArrayList<>(); + } + + @Override + public void addSegment(double value, long valueIndex, PointList geom, double dist) { + segmentParamsList.add(new SegmentParams(value, valueIndex, geom, dist)); + } - @Override - public void addSegment(double value, long valueIndex, PointList geom, double dist) { - segmentParamsList.add(new SegmentParams(value, valueIndex, geom, dist)); + public List getSegmentParamsList() { + return segmentParamsList; } - public List getSegmentParamsList() { - return segmentParamsList; - } + public void append(AppendableRouteExtraInfoBuilder more) { + this.segmentParamsList.addAll(more.getSegmentParamsList()); + } - public void append(AppendableRouteExtraInfoBuilder more) { - this.segmentParamsList.addAll(more.getSegmentParamsList()); - } + @Override + public void finish() { + for (Iterator it = segmentParamsList.iterator(); it.hasNext(); ) { + SegmentParams s = it.next(); + super.addSegment(s.value, s.valueIndex, s.geom, s.dist, !it.hasNext()); + } + } - @Override - public void finish() { - for (Iterator it = segmentParamsList.iterator(); it.hasNext(); ){ - SegmentParams s = it.next(); - super.addSegment(s.value, s.valueIndex, s.geom, s.dist, !it.hasNext()); - } - } + private static class SegmentParams { + double value; + long valueIndex; + PointList geom; + double dist; - private static class SegmentParams { - double value; - long valueIndex; - PointList geom; - double dist; - SegmentParams(double value, long valueIndex, PointList geom, double dist) { - this.value = value; - this.valueIndex = valueIndex; - this.geom = geom; - this.dist = dist; - } - } + SegmentParams(double value, long valueIndex, PointList geom, double dist) { + this.value = value; + this.valueIndex = valueIndex; + this.geom = geom; + this.dist = dist; + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableSteepnessExtraInfoBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableSteepnessExtraInfoBuilder.java index 1e23025073..cacb9ffece 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableSteepnessExtraInfoBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/AppendableSteepnessExtraInfoBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.util.extrainfobuilders; @@ -21,32 +21,32 @@ import java.util.List; public class AppendableSteepnessExtraInfoBuilder extends SteepnessExtraInfoBuilder { - private final ArrayList segmentPointLists; + private final ArrayList segmentPointLists; public AppendableSteepnessExtraInfoBuilder(RouteExtraInfo extraInfo) { - super(extraInfo); - segmentPointLists = new ArrayList<>(); - } - - public List getSegmentPointLists() { - return segmentPointLists; - } - - public void append(AppendableSteepnessExtraInfoBuilder more) { - this.segmentPointLists.addAll(more.getSegmentPointLists()); - } - - @Override - public void addPoints(PointList geom) { - this.segmentPointLists.add(geom); - } - - @Override - public void finish() { - for (Iterator it = segmentPointLists.iterator(); it.hasNext(); ){ - PointList s = it.next(); - super.addSegment(0, 0, null, 0, !it.hasNext()); - super.addPoints(s); - } - } + super(extraInfo); + segmentPointLists = new ArrayList<>(); + } + + public List getSegmentPointLists() { + return segmentPointLists; + } + + public void append(AppendableSteepnessExtraInfoBuilder more) { + this.segmentPointLists.addAll(more.getSegmentPointLists()); + } + + @Override + public void addPoints(PointList geom) { + this.segmentPointLists.add(geom); + } + + @Override + public void finish() { + for (Iterator it = segmentPointLists.iterator(); it.hasNext(); ) { + PointList s = it.next(); + super.addSegment(0, 0, null, 0, !it.hasNext()); + super.addPoints(s); + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/RouteExtraInfoBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/RouteExtraInfoBuilder.java index 149ae60518..a29d7f2193 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/RouteExtraInfoBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/RouteExtraInfoBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.util.extrainfobuilders; @@ -18,13 +18,13 @@ public abstract class RouteExtraInfoBuilder { protected RouteExtraInfo extraInfo; - + RouteExtraInfoBuilder(RouteExtraInfo extraInfo) { - if (extraInfo == null) - throw new NullPointerException("extraInfo"); - this.extraInfo = extraInfo; + if (extraInfo == null) + throw new NullPointerException("extraInfo"); + this.extraInfo = extraInfo; } - + public abstract void addSegment(double value, long valueIndex, PointList geom, double dist, boolean lastEdge); public abstract void addSegment(double value, long valueIndex, PointList geom, double dist); diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SimpleRouteExtraInfoBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SimpleRouteExtraInfoBuilder.java index f2f020a53c..ce50ec127c 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SimpleRouteExtraInfoBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SimpleRouteExtraInfoBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.util.extrainfobuilders; @@ -18,52 +18,52 @@ import org.heigit.ors.routing.RouteSegmentItem; public class SimpleRouteExtraInfoBuilder extends RouteExtraInfoBuilder { - private int prevIndex = 0; - private int segmentLength = 0; - private long prevValueIndex = -1; - private double prevValue = Double.MAX_VALUE; - private double segmentDist = 0; - + private int prevIndex = 0; + private int segmentLength = 0; + private long prevValueIndex = -1; + private double prevValue = Double.MAX_VALUE; + private double segmentDist = 0; + public SimpleRouteExtraInfoBuilder(RouteExtraInfo extraInfo) { - super(extraInfo); - } + super(extraInfo); + } - public void addSegment(double value, long valueIndex, PointList geom, double dist, boolean lastEdge) { - int nPoints = geom.size() - 1; - if ((prevValue != Double.MAX_VALUE && value != prevValue) || (lastEdge)) { - RouteSegmentItem item = null; - if (lastEdge) { - if (value != prevValue) { - if (prevValueIndex != -1) { - item = new RouteSegmentItem(prevIndex, prevIndex + segmentLength, prevValueIndex, segmentDist); - extraInfo.add(item); - } - item = new RouteSegmentItem(prevIndex + segmentLength, prevIndex + segmentLength + nPoints, valueIndex, dist); - extraInfo.add(item); - } else { - item = new RouteSegmentItem(prevIndex, prevIndex + segmentLength + nPoints, valueIndex, segmentDist + dist); - extraInfo.add(item); - } - } else { - item = new RouteSegmentItem(prevIndex, prevIndex + segmentLength, prevValueIndex, segmentDist); - prevIndex += segmentLength; - segmentDist = dist; - segmentLength = nPoints; - extraInfo.add(item); - } - } else { - segmentLength += nPoints; - segmentDist += dist; - } - prevValue = value; - prevValueIndex = valueIndex; + public void addSegment(double value, long valueIndex, PointList geom, double dist, boolean lastEdge) { + int nPoints = geom.size() - 1; + if ((prevValue != Double.MAX_VALUE && value != prevValue) || (lastEdge)) { + RouteSegmentItem item = null; + if (lastEdge) { + if (value != prevValue) { + if (prevValueIndex != -1) { + item = new RouteSegmentItem(prevIndex, prevIndex + segmentLength, prevValueIndex, segmentDist); + extraInfo.add(item); + } + item = new RouteSegmentItem(prevIndex + segmentLength, prevIndex + segmentLength + nPoints, valueIndex, dist); + extraInfo.add(item); + } else { + item = new RouteSegmentItem(prevIndex, prevIndex + segmentLength + nPoints, valueIndex, segmentDist + dist); + extraInfo.add(item); + } + } else { + item = new RouteSegmentItem(prevIndex, prevIndex + segmentLength, prevValueIndex, segmentDist); + prevIndex += segmentLength; + segmentDist = dist; + segmentLength = nPoints; + extraInfo.add(item); + } + } else { + segmentLength += nPoints; + segmentDist += dist; + } + prevValue = value; + prevValueIndex = valueIndex; } - public void addSegment(double value, long valueIndex, PointList geom, double dist) { - throw new UnsupportedOperationException("SimpleRouteExtraInfoBuilder does not support method addSegment without lastEdge flag."); - } - - public void finish() { - throw new UnsupportedOperationException("SimpleRouteExtraInfoBuilder does not support method finish."); - } + public void addSegment(double value, long valueIndex, PointList geom, double dist) { + throw new UnsupportedOperationException("SimpleRouteExtraInfoBuilder does not support method addSegment without lastEdge flag."); + } + + public void finish() { + throw new UnsupportedOperationException("SimpleRouteExtraInfoBuilder does not support method finish."); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SteepnessExtraInfoBuilder.java b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SteepnessExtraInfoBuilder.java index c349f251f4..51003156ae 100644 --- a/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SteepnessExtraInfoBuilder.java +++ b/ors-engine/src/main/java/org/heigit/ors/routing/util/extrainfobuilders/SteepnessExtraInfoBuilder.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.routing.util.extrainfobuilders; @@ -20,149 +20,149 @@ import org.heigit.ors.routing.util.SteepnessUtil; public class SteepnessExtraInfoBuilder extends RouteExtraInfoBuilder { - private boolean firstSegment = true; - private double x0; - private double y0; - private double z0; - private double cumElevation = 0.0; - private double maxAltitude = Double.MIN_VALUE; - private double minAltitude = Double.MAX_VALUE; - private double splitLength = 0.0; - private int prevGradientCat = 0; - private int pointsCount = 0; - private RouteSegmentItem prevSegmentItem; - private final DistanceCalc3D distCalc; - private boolean lastEdge; - + private boolean firstSegment = true; + private double x0; + private double y0; + private double z0; + private double cumElevation = 0.0; + private double maxAltitude = Double.MIN_VALUE; + private double minAltitude = Double.MAX_VALUE; + private double splitLength = 0.0; + private int prevGradientCat = 0; + private int pointsCount = 0; + private RouteSegmentItem prevSegmentItem; + private final DistanceCalc3D distCalc; + private boolean lastEdge; + public SteepnessExtraInfoBuilder(RouteExtraInfo extraInfo) { - super(extraInfo); - distCalc = new DistanceCalc3D(); - } + super(extraInfo); + distCalc = new DistanceCalc3D(); + } + + public void addSegment(double value, long valueIndex, PointList geom, double dist, boolean lastEdge) { + this.lastEdge = lastEdge; + } + + public void addSegment(double value, long valueIndex, PointList geom, double dist) { + throw new UnsupportedOperationException("SimpleRouteExtraInfoBuilder does not support method addSegment without lastEdge flag."); + } + + public void addPoints(PointList geom) { + int nPoints = geom.size() - 1; + if (nPoints == 0) + return; + + int j0 = 0; + + if (firstSegment) { + j0 = 1; + + x0 = geom.getLon(0); + y0 = geom.getLat(0); + z0 = geom.getEle(0); + + maxAltitude = z0; + minAltitude = z0; + pointsCount++; + + firstSegment = false; + } + + double elevDiff; + for (int j = j0; j < nPoints; ++j) { + double x1 = geom.getLon(j); + double y1 = geom.getLat(j); + double z1 = geom.getEle(j); + + elevDiff = z1 - z0; + cumElevation += elevDiff; + double segLength = distCalc.calcDist(y0, x0, z0, y1, x1, z1); + + double prevMinAltitude = minAltitude; + double prevMaxAltitude = maxAltitude; + if (z1 > maxAltitude) + maxAltitude = z1; + if (z1 < minAltitude) + minAltitude = z1; + + if ((prevMaxAltitude - z1 > SteepnessUtil.ELEVATION_THRESHOLD || z1 - prevMinAltitude > SteepnessUtil.ELEVATION_THRESHOLD) && splitLength > 30) { + boolean bApply = true; + int elevSign = (cumElevation - elevDiff) > 0 ? 1 : -1; + double gradient = elevSign * 100 * (prevMaxAltitude - prevMinAltitude) / splitLength; - public void addSegment(double value, long valueIndex, PointList geom, double dist, boolean lastEdge) { - this.lastEdge = lastEdge; + if (prevGradientCat != 0) { + double zn = Double.MIN_NORMAL; + + if (j + 1 < nPoints) + zn = geom.getEle(j + 1); + + if (zn != Double.MIN_VALUE) { + double elevGap = segLength / 30; + if (( + elevSign > 0 && prevGradientCat > 0 || prevGradientCat < 0 + ) + && Math.abs(zn - z1) < elevGap) + bApply = false; + } + } + + if (bApply) { + int gradientCat = SteepnessUtil.getCategory(gradient); + int startIndex = prevSegmentItem != null ? prevSegmentItem.getTo() : 0; + + if (prevGradientCat == gradientCat && prevSegmentItem != null) { + prevSegmentItem.setTo(prevSegmentItem.getTo() + pointsCount); + prevSegmentItem.setDistance(prevSegmentItem.getDistance() + splitLength); + } else { + + RouteSegmentItem item = new RouteSegmentItem(startIndex, startIndex + pointsCount, gradientCat, splitLength); + extraInfo.add(item); + prevSegmentItem = item; + } + + pointsCount = 0; + prevGradientCat = gradientCat; + minAltitude = Math.min(z0, z1); + maxAltitude = Math.max(z0, z1); + splitLength = 0.0; + + cumElevation = elevDiff; + } + } + + splitLength += segLength; + + x0 = x1; + y0 = y1; + z0 = z1; + + pointsCount++; + } + + if (lastEdge && splitLength > 0) { + elevDiff = maxAltitude - minAltitude; + if (extraInfo.isEmpty() && splitLength < 50 && elevDiff < SteepnessUtil.ELEVATION_THRESHOLD) + elevDiff = 0; + + double gradient = (cumElevation > 0 ? 1 : -1) * 100 * elevDiff / splitLength; + int gradientCat = SteepnessUtil.getCategory(gradient); + + if (prevSegmentItem != null && (prevGradientCat == gradientCat || splitLength < 30)) { + prevSegmentItem.setTo(prevSegmentItem.getTo() + pointsCount); + } else { + int startIndex = prevSegmentItem != null ? prevSegmentItem.getTo() : 0; + + RouteSegmentItem item = new RouteSegmentItem(startIndex, startIndex + pointsCount, gradientCat, splitLength); + extraInfo.add(item); + + prevSegmentItem = item; + prevGradientCat = gradientCat; + pointsCount = 0; + } + } } - public void addSegment(double value, long valueIndex, PointList geom, double dist) { - throw new UnsupportedOperationException("SimpleRouteExtraInfoBuilder does not support method addSegment without lastEdge flag."); - } - - public void addPoints(PointList geom) { - int nPoints = geom.size() - 1; - if (nPoints == 0) - return; - - int j0 = 0; - - if (firstSegment) { - j0 = 1; - - x0 = geom.getLon(0); - y0 = geom.getLat(0); - z0 = geom.getEle(0); - - maxAltitude = z0; - minAltitude = z0; - pointsCount++; - - firstSegment = false; - } - - double elevDiff; - for (int j = j0; j < nPoints; ++j) { - double x1 = geom.getLon(j); - double y1 = geom.getLat(j); - double z1 = geom.getEle(j); - - elevDiff = z1 - z0; - cumElevation += elevDiff; - double segLength = distCalc.calcDist(y0, x0, z0, y1, x1, z1); - - double prevMinAltitude = minAltitude; - double prevMaxAltitude = maxAltitude; - if (z1 > maxAltitude) - maxAltitude = z1; - if (z1 < minAltitude) - minAltitude = z1; - - if ((prevMaxAltitude - z1 > SteepnessUtil.ELEVATION_THRESHOLD || z1 - prevMinAltitude > SteepnessUtil.ELEVATION_THRESHOLD) && splitLength > 30) { - boolean bApply = true; - int elevSign = (cumElevation - elevDiff) > 0 ? 1 : -1; - double gradient = elevSign*100*(prevMaxAltitude - prevMinAltitude) / splitLength; - - if (prevGradientCat != 0 ) { - double zn= Double.MIN_NORMAL; - - if (j + 1 < nPoints) - zn = geom.getEle(j + 1); - - if (zn != Double.MIN_VALUE) { - double elevGap = segLength/30; - if (( - elevSign > 0 && prevGradientCat > 0 || prevGradientCat < 0 - ) - && Math.abs(zn - z1) < elevGap) - bApply = false; - } - } - - if (bApply) { - int gradientCat = SteepnessUtil.getCategory(gradient); - int startIndex = prevSegmentItem != null ? prevSegmentItem.getTo() : 0; - - if (prevGradientCat == gradientCat && prevSegmentItem != null) { - prevSegmentItem.setTo(prevSegmentItem.getTo() + pointsCount); - prevSegmentItem.setDistance(prevSegmentItem.getDistance() + splitLength); - } else { - - RouteSegmentItem item = new RouteSegmentItem(startIndex, startIndex + pointsCount, gradientCat, splitLength); - extraInfo.add(item); - prevSegmentItem = item; - } - - pointsCount = 0; - prevGradientCat = gradientCat; - minAltitude = Math.min(z0, z1); - maxAltitude = Math.max(z0, z1); - splitLength = 0.0; - - cumElevation = elevDiff; - } - } - - splitLength += segLength; - - x0 = x1; - y0 = y1; - z0 = z1; - - pointsCount++; - } - - if (lastEdge && splitLength > 0) { - elevDiff = maxAltitude - minAltitude; - if (extraInfo.isEmpty() && splitLength < 50 && elevDiff < SteepnessUtil.ELEVATION_THRESHOLD) - elevDiff = 0; - - double gradient = (cumElevation > 0 ? 1: -1)*100* elevDiff / splitLength; - int gradientCat = SteepnessUtil.getCategory(gradient); - - if (prevSegmentItem != null && (prevGradientCat == gradientCat || splitLength < 30)) { - prevSegmentItem.setTo(prevSegmentItem.getTo() + pointsCount); - } else { - int startIndex = prevSegmentItem != null ? prevSegmentItem.getTo() : 0; - - RouteSegmentItem item = new RouteSegmentItem(startIndex, startIndex + pointsCount, gradientCat, splitLength); - extraInfo.add(item); - - prevSegmentItem = item; - prevGradientCat = gradientCat; - pointsCount = 0; - } - } - } - - public void finish() { - // do nothing - } + public void finish() { + // do nothing + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/ArraysUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/ArraysUtility.java index e99149066d..7272e8bb84 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/ArraysUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/ArraysUtility.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; @@ -17,41 +17,42 @@ import org.heigit.ors.exceptions.ParameterValueException; public class ArraysUtility { - private ArraysUtility() {} - - public static int[] parseIntArray(String strArray, String elemName, int errorCode) throws Exception { - if (Helper.isEmpty(strArray)) - return new int[0]; - - String value = null; - try { - String[] array = strArray.split(","); - int[] res = new int[array.length]; - for (int i = 0; i < array.length; i++) { - value = array[i].trim(); - res[i] = Integer.parseInt(value); - } - return res; - } catch(Exception ex) { - throw new ParameterValueException(errorCode, elemName, value); - } - } - - public static double[] parseDoubleArray(String strArray, String elemName, String separator, int errorCode) throws Exception { - if (Helper.isEmpty(strArray)) - return new double[0]; - - String value = null; - try { - String[] array = strArray.split(separator); - double[] res = new double[array.length]; - for (int i = 0; i < array.length; i++) { - value = array[i].trim(); - res[i] = Double.parseDouble(value); - } - return res; - } catch(Exception ex) { - throw new ParameterValueException(errorCode, elemName, value); - } - } + private ArraysUtility() { + } + + public static int[] parseIntArray(String strArray, String elemName, int errorCode) throws Exception { + if (Helper.isEmpty(strArray)) + return new int[0]; + + String value = null; + try { + String[] array = strArray.split(","); + int[] res = new int[array.length]; + for (int i = 0; i < array.length; i++) { + value = array[i].trim(); + res[i] = Integer.parseInt(value); + } + return res; + } catch (Exception ex) { + throw new ParameterValueException(errorCode, elemName, value); + } + } + + public static double[] parseDoubleArray(String strArray, String elemName, String separator, int errorCode) throws Exception { + if (Helper.isEmpty(strArray)) + return new double[0]; + + String value = null; + try { + String[] array = strArray.split(separator); + double[] res = new double[array.length]; + for (int i = 0; i < array.length; i++) { + value = array[i].trim(); + res[i] = Double.parseDouble(value); + } + return res; + } catch (Exception ex) { + throw new ParameterValueException(errorCode, elemName, value); + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/CSVUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/CSVUtility.java index 9a21f84c95..566a109911 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/CSVUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/CSVUtility.java @@ -32,7 +32,8 @@ public class CSVUtility { private static final char DEFAULT_QUOTE = '"'; private static final boolean HAS_HEADER = true; - private CSVUtility() {} + private CSVUtility() { + } public static List> readFile(String file) { return readFile(file, HAS_HEADER); @@ -41,9 +42,9 @@ public static List> readFile(String file) { /** * Read data from CSV file using the provided filename, seperator, quote character and whether there is a header * - * @param file CSV file to read from - * @param header Whether to ignore the first row of the CSV - * @return An ArrayList (rows) of ArrayLists (columns values) + * @param file CSV file to read from + * @param header Whether to ignore the first row of the CSV + * @return An ArrayList (rows) of ArrayLists (columns values) */ public static List> readFile(String file, boolean header) { // Open the CSV file @@ -51,10 +52,10 @@ public static List> readFile(String file, boolean header) { List> lines = new ArrayList<>(); boolean headerRead = false; - try (BufferedReader br = new BufferedReader(new FileReader(file))){ + try (BufferedReader br = new BufferedReader(new FileReader(file))) { while ((ln = br.readLine()) != null) { - if(header && lines.isEmpty() && !headerRead) { - headerRead=true; + if (header && lines.isEmpty() && !headerRead) { + headerRead = true; continue; } @@ -74,9 +75,9 @@ private static ArrayList parseLine(String csvLine) { /** * Parse a line of text read from a CSV file. The line is split into values. * - * @param csvLine The line of the CSV file - * @param separator The seperator between values - * @param customQuote The character enclosing strings + * @param csvLine The line of the CSV file + * @param separator The seperator between values + * @param customQuote The character enclosing strings * @return */ private static ArrayList parseLine(String csvLine, char separator, char customQuote) { diff --git a/ors-engine/src/main/java/org/heigit/ors/util/CoordTools.java b/ors-engine/src/main/java/org/heigit/ors/util/CoordTools.java index 1ecf5cd4f9..326dc0d3d5 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/CoordTools.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/CoordTools.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; @@ -25,50 +25,50 @@ * Description:Class for some Operations with Coordinates - * (CoordinateTools)
    *

    - * + * *

    * Copyright: Copyright (c) 2008 by Pascal Neis *

    - * + * * @author Pascal Neis, neis@geographie.uni-bonn.de - * * @version 1.0 2006-05-01 */ public class CoordTools { - private static final double R = 6371000; - private static final double R2 = 2 * R; - private static final double DEG_TO_RAD = 0.017453292519943295769236907684886; - private static final double DEG_TO_RAD_HALF = 0.017453292519943295769236907684886 / 2.0; + private static final double R = 6371000; + private static final double R2 = 2 * R; + private static final double DEG_TO_RAD = 0.017453292519943295769236907684886; + private static final double DEG_TO_RAD_HALF = 0.017453292519943295769236907684886 / 2.0; - private CoordTools() {} + private CoordTools() { + } - public static double calcDistHaversine(double lon0, double lat0, double lon1, double lat1) { - double sinDLat = sin(DEG_TO_RAD_HALF * (lat1 - lat0)); - double sinDLon = sin(DEG_TO_RAD_HALF * (lon1 - lon0)); - double c = sinDLat * sinDLat + sinDLon * sinDLon * cos(DEG_TO_RAD * lat0) * cos(DEG_TO_RAD * lat1); + public static double calcDistHaversine(double lon0, double lat0, double lon1, double lat1) { + double sinDLat = sin(DEG_TO_RAD_HALF * (lat1 - lat0)); + double sinDLon = sin(DEG_TO_RAD_HALF * (lon1 - lon0)); + double c = sinDLat * sinDLat + sinDLon * sinDLon * cos(DEG_TO_RAD * lat0) * cos(DEG_TO_RAD * lat1); - return R2 * asin(sqrt(c)); - } + return R2 * asin(sqrt(c)); + } - public static Coordinate[] parse(String value, String separator, boolean is3D, boolean inverseXY) { - String[] coordValues = value.split(separator); - Coordinate[] coords = new Coordinate[coordValues.length]; + public static Coordinate[] parse(String value, String separator, boolean is3D, boolean inverseXY) { + String[] coordValues = value.split(separator); + Coordinate[] coords = new Coordinate[coordValues.length]; - for (int i = 0; i < coordValues.length; i++) { - String[] locations = coordValues[i].split(","); - if (inverseXY) { - if (is3D && locations.length == 3) - coords[i] = new Coordinate(Double.parseDouble(locations[1]), Double.parseDouble(locations[0]), Double.parseDouble(locations[2])); - else - coords[i] = new Coordinate(Double.parseDouble(locations[1]), Double.parseDouble(locations[0])); - } else { - if (is3D && locations.length == 3) - coords[i] = new Coordinate(Double.parseDouble(locations[0]), Double.parseDouble(locations[1]), Double.parseDouble(locations[2])); - else - coords[i] = new Coordinate(Double.parseDouble(locations[0]), Double.parseDouble(locations[1])); - } - } + for (int i = 0; i < coordValues.length; i++) { + String[] locations = coordValues[i].split(","); + if (inverseXY) { + if (is3D && locations.length == 3) + coords[i] = new Coordinate(Double.parseDouble(locations[1]), Double.parseDouble(locations[0]), Double.parseDouble(locations[2])); + else + coords[i] = new Coordinate(Double.parseDouble(locations[1]), Double.parseDouble(locations[0])); + } else { + if (is3D && locations.length == 3) + coords[i] = new Coordinate(Double.parseDouble(locations[0]), Double.parseDouble(locations[1]), Double.parseDouble(locations[2])); + else + coords[i] = new Coordinate(Double.parseDouble(locations[0]), Double.parseDouble(locations[1])); + } + } - return coords; - } + return coords; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/DebugUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/DebugUtility.java index 54c91d1773..78a0326ea8 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/DebugUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/DebugUtility.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; @@ -18,30 +18,31 @@ public class DebugUtility { - private static final boolean IS_DEBUG; - private static final Map listMap = new HashMap(); - static { - IS_DEBUG = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString() - .contains("-agentlib:jdwp"); - } - - private DebugUtility() {} - - public static boolean isDebug() - { - return IS_DEBUG; - } - - public static void setList(String name, final long[] array) { - listMap.put(name, array); - } - - public static boolean listContains(String name, final long v) { - long[] array = (long[])listMap.get(name); - for (long i : array){ - if(i == v) - return true; - } - return false; - } + private static final boolean IS_DEBUG; + private static final Map listMap = new HashMap(); + + static { + IS_DEBUG = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString() + .contains("-agentlib:jdwp"); + } + + private DebugUtility() { + } + + public static boolean isDebug() { + return IS_DEBUG; + } + + public static void setList(String name, final long[] array) { + listMap.put(name, array); + } + + public static boolean listContains(String name, final long v) { + long[] array = (long[]) listMap.get(name); + for (long i : array) { + if (i == v) + return true; + } + return false; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/DistanceUnitUtil.java b/ors-engine/src/main/java/org/heigit/ors/util/DistanceUnitUtil.java index d6504d4dc0..90498d760d 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/DistanceUnitUtil.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/DistanceUnitUtil.java @@ -17,35 +17,36 @@ import org.heigit.ors.exceptions.StatusCodeException; public class DistanceUnitUtil { - private DistanceUnitUtil() {} + private DistanceUnitUtil() { + } - public static DistanceUnit getFromString(String value, DistanceUnit defaultValue) { - return switch (value) { - case "m", "meters" -> DistanceUnit.METERS; - case "km", "kilometers" -> DistanceUnit.KILOMETERS; - case "mi", "miles" -> DistanceUnit.MILES; - default -> defaultValue; - }; - } + public static DistanceUnit getFromString(String value, DistanceUnit defaultValue) { + return switch (value) { + case "m", "meters" -> DistanceUnit.METERS; + case "km", "kilometers" -> DistanceUnit.KILOMETERS; + case "mi", "miles" -> DistanceUnit.MILES; + default -> defaultValue; + }; + } - public static String toString( DistanceUnit unit) { - return switch (unit) { - case METERS -> "m"; - case KILOMETERS -> "km"; - case MILES -> "mi"; - default -> ""; - }; - } + public static String toString(DistanceUnit unit) { + return switch (unit) { + case METERS -> "m"; + case KILOMETERS -> "km"; + case MILES -> "mi"; + default -> ""; + }; + } - public static double convert(double value, DistanceUnit unitsFrom, DistanceUnit unitsTo) throws StatusCodeException { - if (unitsFrom == DistanceUnit.METERS) { - return switch (unitsTo) { - case KILOMETERS -> value / 1000.0; - case MILES -> value * 0.000621371192; - case METERS -> value; - default -> value; - }; - } - throw new StatusCodeException(501, "Conversion not implemented."); - } + public static double convert(double value, DistanceUnit unitsFrom, DistanceUnit unitsTo) throws StatusCodeException { + if (unitsFrom == DistanceUnit.METERS) { + return switch (unitsTo) { + case KILOMETERS -> value / 1000.0; + case MILES -> value * 0.000621371192; + case METERS -> value; + default -> value; + }; + } + throw new StatusCodeException(501, "Conversion not implemented."); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/DoubleFormatUtil.java b/ors-engine/src/main/java/org/heigit/ors/util/DoubleFormatUtil.java index 5ae88a35ec..a38ff6472b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/DoubleFormatUtil.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/DoubleFormatUtil.java @@ -42,7 +42,7 @@ *
  • 0.00000001 should be rendered as "0.00000001" *
  • 0.000000001 should be rendered as "0" * - * + *

    * Originally authored by Julien Aymé. */ public final class DoubleFormatUtil { @@ -54,10 +54,10 @@ private DoubleFormatUtil() { * Rounds the given source value at the given precision * and writes the rounded value into the given target * - * @param source the source value to round - * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) + * @param source the source value to round + * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) * @param precision the precision to round at (use if abs(source) < 1.0) - * @param target the buffer to write to + * @param target the buffer to write to */ public static void formatDouble(double source, int decimals, int precision, StringBuilder target) { int scale = (Math.abs(source) >= 1.0) ? decimals : precision; @@ -75,10 +75,10 @@ public static void formatDouble(double source, int decimals, int precision, Stri * This method internally uses the String representation of the source value, * in order to avoid any double precision computation error. * - * @param source the source value to round - * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) + * @param source the source value to round + * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) * @param precision the precision to round at (use if abs(source) < 1.0) - * @param target the buffer to write to + * @param target the buffer to write to */ public static void formatDoublePrecise(double source, int decimals, int precision, StringBuilder target) { if (isRoundedToZero(source, decimals, precision)) { @@ -183,8 +183,8 @@ public static void formatDoublePrecise(double source, int decimals, int precisio /** * Returns true if the given source value will be rounded to zero * - * @param source the source value to round - * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) + * @param source the source value to round + * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) * @param precision the precision to round at (use if abs(source) < 1.0) * @return true if the source value will be rounded to zero */ @@ -198,6 +198,7 @@ private static boolean isRoundedToZero(double source, int decimals, int precisio */ private static final long[] POWERS_OF_TEN_LONG = new long[19]; private static final double[] POWERS_OF_TEN_DOUBLE = new double[30]; + static { POWERS_OF_TEN_LONG[0] = 1L; for (int i = 1; i < POWERS_OF_TEN_LONG.length; i++) { @@ -228,9 +229,9 @@ private static double tenPowDouble(int n) { * Helper method to do the custom rounding used within formatDoublePrecise * * @param target the buffer to write to - * @param scale the expected rounding scale - * @param intP the source integer part - * @param decP the source decimal part, truncated to scale + 1 digit + * @param scale the expected rounding scale + * @param intP the source integer part + * @param decP the source decimal part, truncated to scale + 1 digit */ private static void format(StringBuilder target, int scale, long intP, long decP) { if (decP != 0L) { @@ -271,10 +272,10 @@ private static void format(StringBuilder target, int scale, long intP, long decP * This method internally uses double precision computation and rounding, * so the result may not be accurate (see formatDouble method for conditions). * - * @param source the source value to round - * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) + * @param source the source value to round + * @param decimals the decimals to round at (use if abs(source) ≥ 1.0) * @param precision the precision to round at (use if abs(source) < 1.0) - * @param target the buffer to write to + * @param target the buffer to write to */ public static void formatDoubleFast(double source, int decimals, int precision, StringBuilder target) { if (isRoundedToZero(source, decimals, precision)) { @@ -348,7 +349,7 @@ public static int getExponant(double value) { * of the double for a fast rounding * * @param source the source to round - * @param scale the scale to round at + * @param scale the scale to round at * @return true if the rounding will potentially use too many digits */ private static boolean tooManyDigitsUsed(double source, int scale) { @@ -362,7 +363,7 @@ private static boolean tooManyDigitsUsed(double source, int scale) { * of a rounding value for the given scale. * * @param source the source to round - * @param scale the scale to round at + * @param scale the scale to round at * @return true if the source will be potentially rounded at the scale */ private static boolean tooCloseToRound(double source, int scale) { diff --git a/ors-engine/src/main/java/org/heigit/ors/util/ErrorLoggingUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/ErrorLoggingUtility.java index 18a0ff9d8a..9481e6bcf2 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/ErrorLoggingUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/ErrorLoggingUtility.java @@ -3,7 +3,8 @@ import org.apache.log4j.Logger; public class ErrorLoggingUtility { - private ErrorLoggingUtility() {} + private ErrorLoggingUtility() { + } public static void logMissingConfigParameter(Class originalClass, String missingConfigParameter) { final Logger logger = Logger.getLogger(originalClass.getName()); diff --git a/ors-engine/src/main/java/org/heigit/ors/util/FileUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/FileUtility.java index 8b715baa88..0eb517c73b 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/FileUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/FileUtility.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; @@ -29,118 +29,120 @@ import static com.graphhopper.util.Helper.toLowerCase; public class FileUtility { - private static final Logger LOGGER = Logger.getLogger(FileUtility.class.getName()); - private FileUtility() {} - - public static boolean isAbsolutePath(String path) { - Path path2 = Paths.get(path); - return path2.isAbsolute(); - } - - public static String readFile(String fileName) throws IOException { - File file = new File(fileName); - FileInputStream fis = new FileInputStream(file); - String result = StreamUtility.readStream(fis); - fis.close(); - - return result; - } - - public static String readResource(String resourcePath) throws IOException { - URL resource = FileUtility.class.getResource(resourcePath); - InputStream ris = resource.openStream(); - String result = StreamUtility.readStream(ris); - ris.close(); - - return result; - } - - public static void makeDirectory(String directory) throws Exception { - File dir = new File(directory); - if (!dir.exists()) { - try { - FileUtils.forceMkdir(dir); - } catch (SecurityException se) { - // handle it - } - - if (!dir.exists()) - throw new Exception("Unable to create directory - " + directory); - } - } - - public static String getMd5OfFile(String filePath) { - StringBuilder returnVal = new StringBuilder(); - try (InputStream input = new FileInputStream(filePath)) { - byte[] buffer = new byte[1024]; - MessageDigest md5Hash = MessageDigest.getInstance("MD5"); - int numRead = 0; - while (numRead != -1) { - numRead = input.read(buffer); - if (numRead > 0) { - md5Hash.update(buffer, 0, numRead); - } - } - byte [] md5Bytes = md5Hash.digest(); - for (int i=0; i < md5Bytes.length; i++) { - returnVal.append(Integer.toString( ( md5Bytes[i] & 0xff ) + 0x100, 16).substring(1)); - } - } catch(Exception e) { - LOGGER.error(e.getMessage()); - } - return returnVal.toString().toUpperCase(); - } - - public static String getFileName(URL extUrl) { - // URL: - // "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg" - String filename = ""; - // PATH: - // /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg - String path = extUrl.getPath(); - // Checks for both forward and/or backslash - // NOTE:**While backslashes are not supported in URL's - // most browsers will autoreplace them with forward slashes - // So technically if you're parsing an html page you could run into - // a backslash , so i'm accounting for them here - String[] pathContents = path.split("[\\\\/]"); - if (pathContents != null) { - int pathContentsLength = pathContents.length; - LOGGER.info("Path Contents Length: " + pathContentsLength); - for (int i = 0; i < pathContents.length; i++) { - LOGGER.info("Path " + i + ": " + pathContents[i]); - } - // lastPart: s659629384_752969_4472.jpg - String lastPart = pathContents[pathContentsLength - 1]; - String[] lastPartContents = lastPart.split("\\."); - if (lastPartContents != null && lastPartContents.length > 1) { - int lastPartContentLength = lastPartContents.length; - LOGGER.info("Last Part Length: " + lastPartContentLength); - // filenames can contain . , so we assume everything before - // the last . is the name, everything after the last . is the - // extension - StringBuilder name = new StringBuilder(); - for (int i = 0; i < lastPartContentLength; i++) { - LOGGER.info("Last Part " + i + ": " + lastPartContents[i]); - if (i < (lastPartContents.length - 1)) { - name.append(lastPartContents[i]); - if (i < (lastPartContentLength - 2)) { - name.append("."); - } - } - } - String extension = lastPartContents[lastPartContentLength - 1]; - filename = name + "." + extension; - LOGGER.info("Name: " + name); - LOGGER.info("Extension: " + extension); - LOGGER.info("Filename: " + filename); - } - } - return filename; - } - - public static String weightingToFileName(Weighting w) { - return toLowerCase(w.toString()).replaceAll("\\|", "_"); - } + private static final Logger LOGGER = Logger.getLogger(FileUtility.class.getName()); + + private FileUtility() { + } + + public static boolean isAbsolutePath(String path) { + Path path2 = Paths.get(path); + return path2.isAbsolute(); + } + + public static String readFile(String fileName) throws IOException { + File file = new File(fileName); + FileInputStream fis = new FileInputStream(file); + String result = StreamUtility.readStream(fis); + fis.close(); + + return result; + } + + public static String readResource(String resourcePath) throws IOException { + URL resource = FileUtility.class.getResource(resourcePath); + InputStream ris = resource.openStream(); + String result = StreamUtility.readStream(ris); + ris.close(); + + return result; + } + + public static void makeDirectory(String directory) throws Exception { + File dir = new File(directory); + if (!dir.exists()) { + try { + FileUtils.forceMkdir(dir); + } catch (SecurityException se) { + // handle it + } + + if (!dir.exists()) + throw new Exception("Unable to create directory - " + directory); + } + } + + public static String getMd5OfFile(String filePath) { + StringBuilder returnVal = new StringBuilder(); + try (InputStream input = new FileInputStream(filePath)) { + byte[] buffer = new byte[1024]; + MessageDigest md5Hash = MessageDigest.getInstance("MD5"); + int numRead = 0; + while (numRead != -1) { + numRead = input.read(buffer); + if (numRead > 0) { + md5Hash.update(buffer, 0, numRead); + } + } + byte[] md5Bytes = md5Hash.digest(); + for (int i = 0; i < md5Bytes.length; i++) { + returnVal.append(Integer.toString((md5Bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + return returnVal.toString().toUpperCase(); + } + + public static String getFileName(URL extUrl) { + // URL: + // "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg" + String filename = ""; + // PATH: + // /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg + String path = extUrl.getPath(); + // Checks for both forward and/or backslash + // NOTE:**While backslashes are not supported in URL's + // most browsers will autoreplace them with forward slashes + // So technically if you're parsing an html page you could run into + // a backslash , so i'm accounting for them here + String[] pathContents = path.split("[\\\\/]"); + if (pathContents != null) { + int pathContentsLength = pathContents.length; + LOGGER.info("Path Contents Length: " + pathContentsLength); + for (int i = 0; i < pathContents.length; i++) { + LOGGER.info("Path " + i + ": " + pathContents[i]); + } + // lastPart: s659629384_752969_4472.jpg + String lastPart = pathContents[pathContentsLength - 1]; + String[] lastPartContents = lastPart.split("\\."); + if (lastPartContents != null && lastPartContents.length > 1) { + int lastPartContentLength = lastPartContents.length; + LOGGER.info("Last Part Length: " + lastPartContentLength); + // filenames can contain . , so we assume everything before + // the last . is the name, everything after the last . is the + // extension + StringBuilder name = new StringBuilder(); + for (int i = 0; i < lastPartContentLength; i++) { + LOGGER.info("Last Part " + i + ": " + lastPartContents[i]); + if (i < (lastPartContents.length - 1)) { + name.append(lastPartContents[i]); + if (i < (lastPartContentLength - 2)) { + name.append("."); + } + } + } + String extension = lastPartContents[lastPartContentLength - 1]; + filename = name + "." + extension; + LOGGER.info("Name: " + name); + LOGGER.info("Extension: " + extension); + LOGGER.info("Filename: " + filename); + } + } + return filename; + } + + public static String weightingToFileName(Weighting w) { + return toLowerCase(w.toString()).replaceAll("\\|", "_"); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/FormatUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/FormatUtility.java index ac4968ed12..e6c5e55261 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/FormatUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/FormatUtility.java @@ -13,51 +13,52 @@ */ package org.heigit.ors.util; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.common.DistanceUnit; +import org.locationtech.jts.geom.Coordinate; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Locale; public class FormatUtility { - private FormatUtility() {} - - private static final ThreadLocal< NumberFormat > nfCoordRound = ThreadLocal.withInitial(() -> { - NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); - nf.setMaximumFractionDigits(7); - nf.setMinimumFractionDigits(7); - nf.setRoundingMode(RoundingMode.HALF_UP); - return nf; - }); - - /** - * @param coord Coordinate - * @return result String - */ - public static String formatCoordinate(Coordinate coord) { - return nfCoordRound.get().format(coord.x) + " " + nfCoordRound.get().format(coord.y); - } - - public static double roundToDecimals(double d, int c) { - double denom = Math.pow(10 , c); - return Math.round (d * denom) / denom; - } - - public static int getUnitDecimals(DistanceUnit unit) { - if (unit == DistanceUnit.METERS) - return 1; - else if (unit == DistanceUnit.KILOMETERS || unit == DistanceUnit.MILES) - return 3; - - return 1; - } - - public static double roundToDecimalsForUnits(double d, DistanceUnit unit) { - return roundToDecimals(d, getUnitDecimals(unit)); - } - - public static void unload(){ - nfCoordRound.remove(); - } + private FormatUtility() { + } + + private static final ThreadLocal nfCoordRound = ThreadLocal.withInitial(() -> { + NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); + nf.setMaximumFractionDigits(7); + nf.setMinimumFractionDigits(7); + nf.setRoundingMode(RoundingMode.HALF_UP); + return nf; + }); + + /** + * @param coord Coordinate + * @return result String + */ + public static String formatCoordinate(Coordinate coord) { + return nfCoordRound.get().format(coord.x) + " " + nfCoordRound.get().format(coord.y); + } + + public static double roundToDecimals(double d, int c) { + double denom = Math.pow(10, c); + return Math.round(d * denom) / denom; + } + + public static int getUnitDecimals(DistanceUnit unit) { + if (unit == DistanceUnit.METERS) + return 1; + else if (unit == DistanceUnit.KILOMETERS || unit == DistanceUnit.MILES) + return 3; + + return 1; + } + + public static double roundToDecimalsForUnits(double d, DistanceUnit unit) { + return roundToDecimals(d, getUnitDecimals(unit)); + } + + public static void unload() { + nfCoordRound.remove(); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/FrechetDistance.java b/ors-engine/src/main/java/org/heigit/ors/util/FrechetDistance.java index 4d322b6087..68df04f322 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/FrechetDistance.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/FrechetDistance.java @@ -10,367 +10,367 @@ public class FrechetDistance { - static double delta = 0.01; - double[][] a; - double[][] b; - double[][] c; - double[][] d; - Point2D[] pl1; - Point2D[] pl2; - int pLength; - int qLength; - static GeometricShapeFactory gsf = new GeometricShapeFactory(); - static GeometryFactory gf = new GeometryFactory(); - - /** - * P and Q are two polylines - * - * @param p - * @param q - */ - public FrechetDistance(Point2D[] p, Point2D[] q) { - pl1 = p; - pl2 = q; - pLength = p.length; - qLength = q.length; - int pL = p.length; - int qL = q.length; - a = new double[pL][qL]; - b = new double[pL][qL]; - c = new double[pL][qL]; - d = new double[pL][qL]; + static double delta = 0.01; + double[][] a; + double[][] b; + double[][] c; + double[][] d; + Point2D[] pl1; + Point2D[] pl2; + int pLength; + int qLength; + static GeometricShapeFactory gsf = new GeometricShapeFactory(); + static GeometryFactory gf = new GeometryFactory(); + + /** + * P and Q are two polylines + * + * @param p + * @param q + */ + public FrechetDistance(Point2D[] p, Point2D[] q) { + pl1 = p; + pl2 = q; + pLength = p.length; + qLength = q.length; + int pL = p.length; + int qL = q.length; + a = new double[pL][qL]; + b = new double[pL][qL]; + c = new double[pL][qL]; + d = new double[pL][qL]; + } + + /** + * @param epsilon + * @return true if the Frechet distance is <= epsilon + */ + public boolean isFrechet(double epsilon) { + // check first pair of segments + if (Line2D.ptSegDist(pl1[0].getX(), pl1[0].getY(), pl1[1].getX(), + pl1[1].getY(), pl2[0].getX(), pl2[0].getY()) > epsilon + && Line2D.ptSegDist(pl1[0].getX(), pl1[0].getY(), + pl1[1].getX(), pl1[1].getY(), pl2[1].getX(), + pl2[1].getY()) > epsilon) { + return false; + } + if (Line2D.ptSegDist(pl2[0].getX(), pl2[0].getY(), pl2[1].getX(), + pl2[1].getY(), pl1[0].getX(), pl1[0].getY()) > epsilon + && Line2D.ptSegDist(pl2[0].getX(), pl2[0].getY(), + pl2[1].getX(), pl1[2].getY(), pl1[1].getX(), + pl1[1].getY()) > epsilon) { + return false; } - /** - * @param epsilon - * @return true if the Frechet distance is <= epsilon - */ - public boolean isFrechet(double epsilon) { - // check first pair of segments - if (Line2D.ptSegDist(pl1[0].getX(), pl1[0].getY(), pl1[1].getX(), - pl1[1].getY(), pl2[0].getX(), pl2[0].getY()) > epsilon - && Line2D.ptSegDist(pl1[0].getX(), pl1[0].getY(), - pl1[1].getX(), pl1[1].getY(), pl2[1].getX(), - pl2[1].getY()) > epsilon) { - return false; - } - if (Line2D.ptSegDist(pl2[0].getX(), pl2[0].getY(), pl2[1].getX(), - pl2[1].getY(), pl1[0].getX(), pl1[0].getY()) > epsilon - && Line2D.ptSegDist(pl2[0].getX(), pl2[0].getY(), - pl2[1].getX(), pl1[2].getY(), pl1[1].getX(), - pl1[1].getY()) > epsilon) { - return false; - } - - // check last pair of segments - if (Line2D.ptSegDist(pl1[pLength - 2].getX(), pl1[pLength - 2].getY(), - pl1[pLength - 1].getX(), pl1[pLength - 1].getY(), - pl2[qLength - 1].getX(), pl2[qLength - 1].getY()) > epsilon - && Line2D.ptSegDist(pl1[pLength - 2].getX(), - pl1[pLength - 2].getY(), pl1[pLength - 1].getX(), - pl1[pLength - 1].getY(), pl2[qLength - 2].getX(), - pl2[qLength - 2].getY()) > epsilon) { - return false; - } - if (Line2D.ptSegDist(pl2[qLength - 2].getX(), pl2[qLength - 2].getY(), - pl2[qLength - 1].getX(), pl2[qLength - 1].getY(), - pl1[pLength - 2].getX(), pl1[pLength - 2].getY()) > epsilon - && Line2D.ptSegDist(pl2[qLength - 2].getX(), - pl2[qLength - 2].getY(), pl2[qLength - 1].getX(), - pl2[qLength - 1].getY(), pl1[pLength - 1].getX(), - pl1[pLength - 1].getY()) > epsilon) { - return false; - } - - LineString tempLsQ; - LineString tempLsP; - Coordinate p1; - Coordinate p2; - Coordinate q1; - Coordinate q2; - Polygon tempCircle; - Geometry tempGeom; - - for (int i = 0; i < pl1.length - 1; i++) { - for (int j = 0; j < pl2.length - 1; j++) { - - p1 = new Coordinate(pl1[i].getX(), pl1[i].getY()); - p2 = new Coordinate(pl1[i + 1].getX(), pl1[i + 1].getY()); - q1 = new Coordinate(pl2[j].getX(), pl2[j].getY()); - q2 = new Coordinate(pl2[j + 1].getX(), pl2[j + 1].getY()); - - if (Line2D.ptSegDist(pl2[j].getX(), pl2[j].getY(), - pl2[j + 1].getX(), pl2[j + 1].getY(), pl1[i].getX(), - pl1[i].getY()) > epsilon) { - a[i][j] = b[i][j] = -1; - } else { - // make line string out of j's two end points - - tempLsQ = gf.createLineString(new Coordinate[] { q1, q2 }); - - // make circle with i's first end point - - gsf.setCentre(p1); - gsf.setSize(2 * epsilon); - tempCircle = gsf.createCircle(); - - if (tempCircle.contains(tempLsQ)) { - a[i][j] = 0; - b[i][j] = 1; - } else { - // collapse the circle and the line - tempGeom = tempCircle.intersection(tempLsQ); - int numCoords = tempGeom.getCoordinates().length; - - if (numCoords == 2) { - // 2 points - Coordinate[] intersections = tempGeom - .getCoordinates(); - a[i][j] = getProportion(intersections[0], tempLsQ); - b[i][j] = getProportion(intersections[1], tempLsQ); - } else if (numCoords == 1) { - // 1 point - Coordinate intersection = tempGeom.getCoordinate(); - if (p1.distance(q1) < p1 - .distance(q2)) { - a[i][j] = 0; - b[i][j] = getProportion(intersection, tempLsQ); - } else { - a[i][j] = getProportion(intersection, tempLsQ); - b[i][j] = 1; - } - } - } - } - - // fill up c_ij and d_ij - double val1 = Line2D.ptSegDist(pl1[i].getX(), pl1[i].getY(), - pl1[i + 1].getX(), pl1[i + 1].getY(), pl2[j].getX(), - pl2[j].getY()) ; - - if (val1 > epsilon) { - c[i][j] = d[i][j] = -1; - }else{ - tempLsP = gf.createLineString(new Coordinate[] { p1, p2 }); - gsf.setCentre(q1); - gsf.setSize(2 * epsilon+delta); - tempCircle = gsf.createCircle(); - if (tempCircle.contains(tempLsP)) { - c[i][j] = 0; - d[i][j] = 1; - } else { - // collapse the circle and the line - tempGeom = tempCircle.intersection(tempLsP); - - int numCoords = tempGeom.getCoordinates().length; - if (numCoords == 1) { - //1 point - Coordinate intersect = tempGeom.getCoordinate(); - if (q1.distance(p1) < q1.distance(p2)) { - c[i][j] = 0; - d[i][j] = getProportion(intersect, tempLsP); - } else { - c[i][j] = getProportion(intersect, tempLsP); - d[i][j] = 1; - } - } else { - Coordinate[] intersections = tempGeom - .getCoordinates(); - c[i][j] = getProportion(intersections[0], tempLsP); - d[i][j] = getProportion(intersections[1], tempLsP); - } - } - } - } - } + // check last pair of segments + if (Line2D.ptSegDist(pl1[pLength - 2].getX(), pl1[pLength - 2].getY(), + pl1[pLength - 1].getX(), pl1[pLength - 1].getY(), + pl2[qLength - 1].getX(), pl2[qLength - 1].getY()) > epsilon + && Line2D.ptSegDist(pl1[pLength - 2].getX(), + pl1[pLength - 2].getY(), pl1[pLength - 1].getX(), + pl1[pLength - 1].getY(), pl2[qLength - 2].getX(), + pl2[qLength - 2].getY()) > epsilon) { + return false; + } + if (Line2D.ptSegDist(pl2[qLength - 2].getX(), pl2[qLength - 2].getY(), + pl2[qLength - 1].getX(), pl2[qLength - 1].getY(), + pl1[pLength - 2].getX(), pl1[pLength - 2].getY()) > epsilon + && Line2D.ptSegDist(pl2[qLength - 2].getX(), + pl2[qLength - 2].getY(), pl2[qLength - 1].getX(), + pl2[qLength - 1].getY(), pl1[pLength - 1].getX(), + pl1[pLength - 1].getY()) > epsilon) { + return false; + } - // determine B^R_i,1 - boolean flag = true; - for (int i = 0; i < pl1.length; i++) { - if (flag && c[i][0] == -1 && d[i][0] == -1) { - flag = false; - } else if (!flag) { - c[i][0] = d[i][0] = -1; + LineString tempLsQ; + LineString tempLsP; + Coordinate p1; + Coordinate p2; + Coordinate q1; + Coordinate q2; + Polygon tempCircle; + Geometry tempGeom; + + for (int i = 0; i < pl1.length - 1; i++) { + for (int j = 0; j < pl2.length - 1; j++) { + + p1 = new Coordinate(pl1[i].getX(), pl1[i].getY()); + p2 = new Coordinate(pl1[i + 1].getX(), pl1[i + 1].getY()); + q1 = new Coordinate(pl2[j].getX(), pl2[j].getY()); + q2 = new Coordinate(pl2[j + 1].getX(), pl2[j + 1].getY()); + + if (Line2D.ptSegDist(pl2[j].getX(), pl2[j].getY(), + pl2[j + 1].getX(), pl2[j + 1].getY(), pl1[i].getX(), + pl1[i].getY()) > epsilon) { + a[i][j] = b[i][j] = -1; + } else { + // make line string out of j's two end points + + tempLsQ = gf.createLineString(new Coordinate[]{q1, q2}); + + // make circle with i's first end point + + gsf.setCentre(p1); + gsf.setSize(2 * epsilon); + tempCircle = gsf.createCircle(); + + if (tempCircle.contains(tempLsQ)) { + a[i][j] = 0; + b[i][j] = 1; + } else { + // collapse the circle and the line + tempGeom = tempCircle.intersection(tempLsQ); + int numCoords = tempGeom.getCoordinates().length; + + if (numCoords == 2) { + // 2 points + Coordinate[] intersections = tempGeom + .getCoordinates(); + a[i][j] = getProportion(intersections[0], tempLsQ); + b[i][j] = getProportion(intersections[1], tempLsQ); + } else if (numCoords == 1) { + // 1 point + Coordinate intersection = tempGeom.getCoordinate(); + if (p1.distance(q1) < p1 + .distance(q2)) { + a[i][j] = 0; + b[i][j] = getProportion(intersection, tempLsQ); + } else { + a[i][j] = getProportion(intersection, tempLsQ); + b[i][j] = 1; + } } + } } - flag = true; - // determine L^R_1,j - for (int j = 1; j < pl2.length; j++) { - if (flag && a[0][j] == -1 && b[0][j] == -1) { - flag = false; - } else if (!flag) { - a[0][j] = b[0][j] = -1; + // fill up c_ij and d_ij + double val1 = Line2D.ptSegDist(pl1[i].getX(), pl1[i].getY(), + pl1[i + 1].getX(), pl1[i + 1].getY(), pl2[j].getX(), + pl2[j].getY()); + + if (val1 > epsilon) { + c[i][j] = d[i][j] = -1; + } else { + tempLsP = gf.createLineString(new Coordinate[]{p1, p2}); + gsf.setCentre(q1); + gsf.setSize(2 * epsilon + delta); + tempCircle = gsf.createCircle(); + if (tempCircle.contains(tempLsP)) { + c[i][j] = 0; + d[i][j] = 1; + } else { + // collapse the circle and the line + tempGeom = tempCircle.intersection(tempLsP); + + int numCoords = tempGeom.getCoordinates().length; + if (numCoords == 1) { + //1 point + Coordinate intersect = tempGeom.getCoordinate(); + if (q1.distance(p1) < q1.distance(p2)) { + c[i][j] = 0; + d[i][j] = getProportion(intersect, tempLsP); + } else { + c[i][j] = getProportion(intersect, tempLsP); + d[i][j] = 1; + } + } else { + Coordinate[] intersections = tempGeom + .getCoordinates(); + c[i][j] = getProportion(intersections[0], tempLsP); + d[i][j] = getProportion(intersections[1], tempLsP); } + } } + } + } - // TODO: the complicated loop to compute L^R_(i+1),j and B^R_i,(j+1) - // cannot enter the upper right cell - return a[pLength - 1][qLength - 1] != -1 - || b[pLength - 1][qLength - 1] != -1 - || c[pLength - 1][qLength - 1] != -1 - || d[pLength - 1][qLength - 1] != -1; + // determine B^R_i,1 + boolean flag = true; + for (int i = 0; i < pl1.length; i++) { + if (flag && c[i][0] == -1 && d[i][0] == -1) { + flag = false; + } else if (!flag) { + c[i][0] = d[i][0] = -1; + } } - private double getProportion(Coordinate coord, LineString ls) { - // coord is a point in line ls - Coordinate[] ends = ls.getCoordinates(); - return coord.distance(ends[0]) / ls.getLength(); + flag = true; + // determine L^R_1,j + for (int j = 1; j < pl2.length; j++) { + if (flag && a[0][j] == -1 && b[0][j] == -1) { + flag = false; + } else if (!flag) { + a[0][j] = b[0][j] = -1; + } } - public Double[] computeCriticalValues() { - ArrayList list = new ArrayList<>(); + // TODO: the complicated loop to compute L^R_(i+1),j and B^R_i,(j+1) + // cannot enter the upper right cell + return a[pLength - 1][qLength - 1] != -1 + || b[pLength - 1][qLength - 1] != -1 + || c[pLength - 1][qLength - 1] != -1 + || d[pLength - 1][qLength - 1] != -1; + } + + private double getProportion(Coordinate coord, LineString ls) { + // coord is a point in line ls + Coordinate[] ends = ls.getCoordinates(); + return coord.distance(ends[0]) / ls.getLength(); + } + + public Double[] computeCriticalValues() { + ArrayList list = new ArrayList<>(); + + // distances between starting and ending points + list.add(pl1[0].distance(pl2[0])); + list.add(pl1[pLength - 1].distance(pl2[qLength - 1])); + + // distances between vertices of one curve and edges of the other curve + for (int i = 0; i < pLength; i++) { + for (int j = 0; j < qLength - 1; j++) { + list.add(Line2D.ptSegDist(pl2[j].getX(), pl2[j].getY(), pl2[j + 1].getX(), pl2[j + 1].getY(), pl1[i].getX(), pl1[i].getY())); + } + } - // distances between starting and ending points - list.add(pl1[0].distance(pl2[0])); - list.add(pl1[pLength - 1].distance(pl2[qLength - 1])); + for (int j = 0; j < qLength; j++) { + for (int i = 0; i < pLength - 1; i++) { + list.add(Line2D.ptSegDist(pl1[i].getX(), pl1[i].getY(), + pl1[i + 1].getX(), pl1[i + 1].getY(), pl2[j].getX(), + pl2[j].getY())); + } + } - // distances between vertices of one curve and edges of the other curve - for (int i = 0; i < pLength; i++) { - for (int j = 0; j < qLength - 1; j++) { - list.add(Line2D.ptSegDist(pl2[j].getX(), pl2[j].getY(), pl2[j + 1].getX(), pl2[j + 1].getY(), pl1[i].getX(), pl1[i].getY())); - } + // convert into coordinate array + Coordinate[] pCurve = new Coordinate[pl1.length]; + Coordinate[] qCurve = new Coordinate[pl2.length]; + for (int i = 0; i < pLength; i++) { + pCurve[i] = new Coordinate(pl1[i].getX(), pl1[i].getY()); + } + for (int i = 0; i < qLength; i++) { + qCurve[i] = new Coordinate(pl2[i].getX(), pl2[i].getY()); + } + // common distance of two vertices of one curve to the intersection + // point of their bisector with some edge of the other + + LineString ls; + LineString temp; + LineSegment lseg; + Coordinate c1; + Coordinate midPoint; + Coordinate c2; + Coordinate intersect = null; + for (int i = 0; i < pLength - 2; i++) { + for (int j = i + 2; j < pLength; j++) { + // comp seg between i and j + // comp bisector and intersection point with q + // comp the distance + lseg = new LineSegment(pCurve[i], pCurve[j]); + midPoint = lseg.midPoint(); + double origSlope = getSlope(pCurve[i].x, pCurve[i].y, + pCurve[j].x, pCurve[j].y); + double bisectSlope = 0; + if (origSlope != Double.MAX_VALUE) { + if (origSlope == 0) { + bisectSlope = Double.MAX_VALUE; + } else { + bisectSlope = -1 / origSlope; + } } - for (int j = 0; j < qLength; j++) { - for (int i = 0; i < pLength - 1; i++) { - list.add(Line2D.ptSegDist(pl1[i].getX(), pl1[i].getY(), - pl1[i + 1].getX(), pl1[i + 1].getY(), pl2[j].getX(), - pl2[j].getY())); - } + // linear func: y-midPoint.y = bisectSlope*(x-midpoint.x) + double step = qCurve[0].distance(midPoint); + c1 = new Coordinate(midPoint.x - step, bisectSlope * (-step) + + midPoint.y); + c2 = new Coordinate(midPoint.x + step, bisectSlope * step + + midPoint.y); + // (c1, midPoint, c2) is the bisector linestring of the + // linesegment(i,j) + ls = gf.createLineString(new Coordinate[]{c1, midPoint, c2}); + temp = gf.createLineString(qCurve); + if (ls.intersects(temp)) { + intersect = ls.intersection(temp).getCoordinate(); } - - // convert into coordinate array - Coordinate[] pCurve = new Coordinate[pl1.length]; - Coordinate[] qCurve = new Coordinate[pl2.length]; - for (int i = 0; i < pLength; i++) { - pCurve[i] = new Coordinate(pl1[i].getX(), pl1[i].getY()); + if (intersect != null) { + list.add(intersect.distance(pCurve[i])); } - for (int i = 0; i < qLength; i++) { - qCurve[i] = new Coordinate(pl2[i].getX(), pl2[i].getY()); + } + } + + for (int i = 0; i < qLength - 2; i++) { + for (int j = i + 2; j < qLength; j++) { + lseg = new LineSegment(qCurve[i], qCurve[j]); + midPoint = lseg.midPoint(); + double origSlope = getSlope(qCurve[i].x, qCurve[i].y, + qCurve[j].x, qCurve[j].y); + double bisectSlope = 0; + if (origSlope != Double.MAX_VALUE) { + if (origSlope == 0) { + bisectSlope = Double.MAX_VALUE; + } else { + bisectSlope = -1 / origSlope; + } } - // common distance of two vertices of one curve to the intersection - // point of their bisector with some edge of the other - - LineString ls; - LineString temp; - LineSegment lseg; - Coordinate c1; - Coordinate midPoint; - Coordinate c2; - Coordinate intersect = null; - for (int i = 0; i < pLength - 2; i++) { - for (int j = i + 2; j < pLength; j++) { - // comp seg between i and j - // comp bisector and intersection point with q - // comp the distance - lseg = new LineSegment(pCurve[i], pCurve[j]); - midPoint = lseg.midPoint(); - double origSlope = getSlope(pCurve[i].x, pCurve[i].y, - pCurve[j].x, pCurve[j].y); - double bisectSlope = 0; - if (origSlope != Double.MAX_VALUE) { - if (origSlope == 0) { - bisectSlope = Double.MAX_VALUE; - } else { - bisectSlope = -1 / origSlope; - } - } - - // linear func: y-midPoint.y = bisectSlope*(x-midpoint.x) - double step = qCurve[0].distance(midPoint); - c1 = new Coordinate(midPoint.x - step, bisectSlope * (-step) - + midPoint.y); - c2 = new Coordinate(midPoint.x + step, bisectSlope * step - + midPoint.y); - // (c1, midPoint, c2) is the bisector linestring of the - // linesegment(i,j) - ls = gf.createLineString(new Coordinate[] { c1, midPoint, c2 }); - temp = gf.createLineString(qCurve); - if (ls.intersects(temp)) { - intersect = ls.intersection(temp).getCoordinate(); - } - if (intersect != null) { - list.add(intersect.distance(pCurve[i])); - } - } + // linear func: y-midPoint.y = bisectSlope*(x-midpoint.x) + double step = pCurve[0].distance(midPoint); + if (bisectSlope == Double.MAX_VALUE) { + // vertical line + c1 = new Coordinate(midPoint.x, midPoint.y - step); + c2 = new Coordinate(midPoint.x, midPoint.y + step); + } else { + c1 = new Coordinate(midPoint.x - step, bisectSlope + * (-step) + midPoint.y); + c2 = new Coordinate(midPoint.x + step, bisectSlope * step + + midPoint.y); } + ls = gf.createLineString(new Coordinate[]{c1, midPoint, c2}); + temp = gf.createLineString(pCurve); - for (int i = 0; i < qLength - 2; i++) { - for (int j = i + 2; j < qLength; j++) { - lseg = new LineSegment(qCurve[i], qCurve[j]); - midPoint = lseg.midPoint(); - double origSlope = getSlope(qCurve[i].x, qCurve[i].y, - qCurve[j].x, qCurve[j].y); - double bisectSlope = 0; - if (origSlope != Double.MAX_VALUE) { - if (origSlope == 0) { - bisectSlope = Double.MAX_VALUE; - } else { - bisectSlope = -1 / origSlope; - } - } - // linear func: y-midPoint.y = bisectSlope*(x-midpoint.x) - double step = pCurve[0].distance(midPoint); - if (bisectSlope == Double.MAX_VALUE) { - // vertical line - c1 = new Coordinate(midPoint.x, midPoint.y - step); - c2 = new Coordinate(midPoint.x, midPoint.y + step); - } else { - c1 = new Coordinate(midPoint.x - step, bisectSlope - * (-step) + midPoint.y); - c2 = new Coordinate(midPoint.x + step, bisectSlope * step - + midPoint.y); - } - ls = gf.createLineString(new Coordinate[] { c1, midPoint, c2 }); - temp = gf.createLineString(pCurve); - - if (ls.intersects(temp)) { - intersect = ls.intersection(temp).getCoordinate(); - } - if (intersect != null) { - list.add(intersect.distance(qCurve[i])); - } - } + if (ls.intersects(temp)) { + intersect = ls.intersection(temp).getCoordinate(); } - return list.toArray(new Double[0]); - } - - public double computeFrechetDistance() { - Double[] cv = computeCriticalValues(); - Arrays.sort(cv); - - int index = binarySearch(cv); - return cv[index]; - } - - private double getSlope(double x1, double y1, double x2, double y2) { - if ((x2 - x1) == 0) - return Double.MAX_VALUE; - else - return (y2 - y1) / (x2 - x1); - - } - - /** - * Performs the standard binary search using two comparisons per level. - * - * @return index where item is found, or NOT_FOUND. - */ - public int binarySearch(Double[] a) { - int low = 0; - int high = a.length - 1; - int mid = 0; - - while (low <= high) { - mid = (low + high) / 2; - if (!isFrechet(a[mid])) { - low = mid + 1; - } else { - high = mid - 1; - } + if (intersect != null) { + list.add(intersect.distance(qCurve[i])); } - return mid; + } + } + return list.toArray(new Double[0]); + } + + public double computeFrechetDistance() { + Double[] cv = computeCriticalValues(); + Arrays.sort(cv); + + int index = binarySearch(cv); + return cv[index]; + } + + private double getSlope(double x1, double y1, double x2, double y2) { + if ((x2 - x1) == 0) + return Double.MAX_VALUE; + else + return (y2 - y1) / (x2 - x1); + + } + + /** + * Performs the standard binary search using two comparisons per level. + * + * @return index where item is found, or NOT_FOUND. + */ + public int binarySearch(Double[] a) { + int low = 0; + int high = a.length - 1; + int mid = 0; + + while (low <= high) { + mid = (low + high) / 2; + if (!isFrechet(a[mid])) { + low = mid + 1; + } else { + high = mid - 1; + } } + return mid; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/GeomUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/GeomUtility.java index be1cc4bbf0..3da9dafcfc 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/GeomUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/GeomUtility.java @@ -17,11 +17,11 @@ import com.graphhopper.util.DistanceCalcEarth; import com.graphhopper.util.PointList; import com.graphhopper.util.shapes.BBox; -import org.locationtech.jts.geom.*; import org.geotools.geometry.jts.JTS; import org.geotools.referencing.CRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.heigit.ors.exceptions.InternalServerException; +import org.locationtech.jts.geom.*; import org.opengis.geometry.MismatchedDimensionException; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; @@ -32,180 +32,180 @@ public class GeomUtility { - private static final GeometryFactory geometryFactory = new GeometryFactory(); - - private static MathTransform transformWgs84Sphericalmercator = null;// CRS.findMathTransform(DefaultGeographicCRS.WGS84, - - private GeomUtility() {} - - public static LineString createLinestring(Coordinate[] coords) - { - return geometryFactory.createLineString(coords); - } - - /** - * Creates the correct bbox from a Graphhopper pointlist. Instead of using the > or < operators to compare double - * values this function uses the Math library which is more accurate and precise and creates correct bboxes even if - * the coordinates only differ in some small extend. - * @param pointList the points to consider - * @return Returns a graphhopper bounding box - */ - public static BBox calculateBoundingBox(PointList pointList) { - if (pointList == null || pointList.size() <= 0) { - return new BBox(0, 0, 0, 0); - } else { - double minLon = Double.MAX_VALUE; - double maxLon = -Double.MAX_VALUE; - double minLat = Double.MAX_VALUE; - double maxLat = -Double.MAX_VALUE; - double minEle = Double.MAX_VALUE; - double maxEle = -Double.MAX_VALUE; - for (int i = 0; i < pointList.size(); ++i) { - minLon = Math.min(minLon, pointList.getLon(i)); - maxLon = Math.max(maxLon, pointList.getLon(i)); - minLat = Math.min(minLat, pointList.getLat(i)); - maxLat = Math.max(maxLat, pointList.getLat(i)); - if (pointList.is3D()) { - minEle = Math.min(minEle, pointList.getEle(i)); - maxEle = Math.max(maxEle, pointList.getEle(i)); - } - } - if (pointList.is3D()) { - return new BBox(minLon, maxLon, minLat, maxLat, minEle, maxEle); - } else { - return new BBox(minLon, maxLon, minLat, maxLat); - } - } - } - - /** - * Takes an array of bounding boxes and calculates a bounding box that covers them all. - * - * @param boundingBoxes array of bounding boxes - * @return A graphhopper bounding box that covers all provided bounding boxes - */ - public static BBox generateBoundingFromMultiple(BBox[] boundingBoxes) { - double minLon = Double.MAX_VALUE; - double maxLon = -Double.MAX_VALUE; - double minLat = Double.MAX_VALUE; - double maxLat = -Double.MAX_VALUE; - double minEle = Double.MAX_VALUE; - double maxEle = -Double.MAX_VALUE; - - for(BBox bbox : boundingBoxes) { - minLon = Math.min(minLon, bbox.minLon); - maxLon = Math.max(maxLon, bbox.maxLon); - minLat = Math.min(minLat, bbox.minLat); - maxLat = Math.max(maxLat, bbox.maxLat); - if(!Double.isNaN(bbox.minEle)) - minEle = Math.min(minEle, bbox.minEle); - if(!Double.isNaN(bbox.maxEle)) - maxEle = Math.max(maxEle, bbox.maxEle); - } - - if(minEle != Double.MAX_VALUE && maxEle != Double.MAX_VALUE) - return new BBox(minLon, maxLon, minLat, maxLat, minEle, maxEle); - else - return new BBox(minLon, maxLon, minLat, maxLat); - } - - public static double getLength(Geometry geom, boolean inMeters) throws Exception { - if (!(geom instanceof LineString ls)) - throw new Exception("Specified geometry type is not supported."); + private static final GeometryFactory geometryFactory = new GeometryFactory(); + + private static MathTransform transformWgs84Sphericalmercator = null;// CRS.findMathTransform(DefaultGeographicCRS.WGS84, + + private GeomUtility() { + } + + public static LineString createLinestring(Coordinate[] coords) { + return geometryFactory.createLineString(coords); + } + + /** + * Creates the correct bbox from a Graphhopper pointlist. Instead of using the > or < operators to compare double + * values this function uses the Math library which is more accurate and precise and creates correct bboxes even if + * the coordinates only differ in some small extend. + * + * @param pointList the points to consider + * @return Returns a graphhopper bounding box + */ + public static BBox calculateBoundingBox(PointList pointList) { + if (pointList == null || pointList.size() <= 0) { + return new BBox(0, 0, 0, 0); + } else { + double minLon = Double.MAX_VALUE; + double maxLon = -Double.MAX_VALUE; + double minLat = Double.MAX_VALUE; + double maxLat = -Double.MAX_VALUE; + double minEle = Double.MAX_VALUE; + double maxEle = -Double.MAX_VALUE; + for (int i = 0; i < pointList.size(); ++i) { + minLon = Math.min(minLon, pointList.getLon(i)); + maxLon = Math.max(maxLon, pointList.getLon(i)); + minLat = Math.min(minLat, pointList.getLat(i)); + maxLat = Math.max(maxLat, pointList.getLat(i)); + if (pointList.is3D()) { + minEle = Math.min(minEle, pointList.getEle(i)); + maxEle = Math.max(maxEle, pointList.getEle(i)); + } + } + if (pointList.is3D()) { + return new BBox(minLon, maxLon, minLat, maxLat, minEle, maxEle); + } else { + return new BBox(minLon, maxLon, minLat, maxLat); + } + } + } + + /** + * Takes an array of bounding boxes and calculates a bounding box that covers them all. + * + * @param boundingBoxes array of bounding boxes + * @return A graphhopper bounding box that covers all provided bounding boxes + */ + public static BBox generateBoundingFromMultiple(BBox[] boundingBoxes) { + double minLon = Double.MAX_VALUE; + double maxLon = -Double.MAX_VALUE; + double minLat = Double.MAX_VALUE; + double maxLat = -Double.MAX_VALUE; + double minEle = Double.MAX_VALUE; + double maxEle = -Double.MAX_VALUE; + + for (BBox bbox : boundingBoxes) { + minLon = Math.min(minLon, bbox.minLon); + maxLon = Math.max(maxLon, bbox.maxLon); + minLat = Math.min(minLat, bbox.minLat); + maxLat = Math.max(maxLat, bbox.maxLat); + if (!Double.isNaN(bbox.minEle)) + minEle = Math.min(minEle, bbox.minEle); + if (!Double.isNaN(bbox.maxEle)) + maxEle = Math.max(maxEle, bbox.maxEle); + } + + if (minEle != Double.MAX_VALUE && maxEle != Double.MAX_VALUE) + return new BBox(minLon, maxLon, minLat, maxLat, minEle, maxEle); + else + return new BBox(minLon, maxLon, minLat, maxLat); + } + + public static double getLength(Geometry geom, boolean inMeters) throws Exception { + if (!(geom instanceof LineString ls)) + throw new Exception("Specified geometry type is not supported."); if (ls.getNumPoints() == 0) - return 0.0; - - if (inMeters) { - double length = 0.0; - DistanceCalc dc = new DistanceCalcEarth(); - - Coordinate c0 = ls.getCoordinateN(0); - for (int i = 1; i < ls.getNumPoints(); ++i) { - Coordinate c1 = ls.getCoordinateN(i); - length += dc.calcDist(c0.y, c0.x, c1.y, c1.x); - c0 = c1; - } - - return length; - } - else - return ls.getLength(); - } - - public static double metresToDegrees(double metres) { - // One degree latitude is approximately 111,139 metres on a spherical earth - return metres / 111139; - } - - public static double getArea(Geometry geom, boolean inMeters) throws InternalServerException { - try { - if (inMeters) { - if (geom instanceof Polygon poly) { - - // https://gis.stackexchange.com/questions/265481/geotools-unexpected-result-reprojecting-bounding-box-to-epsg3035 - System.setProperty("org.geotools.referencing.forceXY", "true"); + return 0.0; + + if (inMeters) { + double length = 0.0; + DistanceCalc dc = new DistanceCalcEarth(); + + Coordinate c0 = ls.getCoordinateN(0); + for (int i = 1; i < ls.getNumPoints(); ++i) { + Coordinate c1 = ls.getCoordinateN(i); + length += dc.calcDist(c0.y, c0.x, c1.y, c1.x); + c0 = c1; + } + + return length; + } else + return ls.getLength(); + } + + public static double metresToDegrees(double metres) { + // One degree latitude is approximately 111,139 metres on a spherical earth + return metres / 111139; + } + + public static double getArea(Geometry geom, boolean inMeters) throws InternalServerException { + try { + if (inMeters) { + if (geom instanceof Polygon poly) { + + // https://gis.stackexchange.com/questions/265481/geotools-unexpected-result-reprojecting-bounding-box-to-epsg3035 + System.setProperty("org.geotools.referencing.forceXY", "true"); CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:4326"); - String mollweideProj = "PROJCS[\"World_Mollweide\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Mollweide\"],PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",0],UNIT[\"Meter\",1],AUTHORITY[\"EPSG\",\"54009\"]]"; - - CoordinateReferenceSystem targetCRS = CRS.parseWKT(mollweideProj); - - MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS); - Geometry targetGeometry = JTS.transform(poly, transform); - - return targetGeometry.getArea(); - } else { - if (transformWgs84Sphericalmercator == null) { - String wkt = "PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],AUTHORITY[\"EPSG\",\"3857\"]]"; - CoordinateReferenceSystem crs = CRS.parseWKT(wkt);// CRS.decode("EPSG:3857") - transformWgs84Sphericalmercator = CRS.findMathTransform(DefaultGeographicCRS.WGS84, crs, true); - } - - Geometry transformedGeometry = JTS.transform(geom, transformWgs84Sphericalmercator); - return transformedGeometry.getArea(); - } - } else { - return geom.getArea(); - } - } catch (NoSuchAuthorityCodeException e) { - throw new InternalServerException("Could not set CRS authority (getting area of feature)"); - } catch (FactoryException fe) { - throw new InternalServerException("Problem setting up Geometry (getting area of feature)"); - } catch (MismatchedDimensionException e) { - throw new InternalServerException("Problem with feature dimensions (getting area of feature)"); - } catch (TransformException e) { - throw new InternalServerException("Could not transform features (getting area of feature)"); - } + String mollweideProj = "PROJCS[\"World_Mollweide\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Mollweide\"],PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",0],UNIT[\"Meter\",1],AUTHORITY[\"EPSG\",\"54009\"]]"; + + CoordinateReferenceSystem targetCRS = CRS.parseWKT(mollweideProj); + + MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS); + Geometry targetGeometry = JTS.transform(poly, transform); + + return targetGeometry.getArea(); + } else { + if (transformWgs84Sphericalmercator == null) { + String wkt = "PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],AUTHORITY[\"EPSG\",\"3857\"]]"; + CoordinateReferenceSystem crs = CRS.parseWKT(wkt);// CRS.decode("EPSG:3857") + transformWgs84Sphericalmercator = CRS.findMathTransform(DefaultGeographicCRS.WGS84, crs, true); + } + + Geometry transformedGeometry = JTS.transform(geom, transformWgs84Sphericalmercator); + return transformedGeometry.getArea(); + } + } else { + return geom.getArea(); + } + } catch (NoSuchAuthorityCodeException e) { + throw new InternalServerException("Could not set CRS authority (getting area of feature)"); + } catch (FactoryException fe) { + throw new InternalServerException("Problem setting up Geometry (getting area of feature)"); + } catch (MismatchedDimensionException e) { + throw new InternalServerException("Problem with feature dimensions (getting area of feature)"); + } catch (TransformException e) { + throw new InternalServerException("Could not transform features (getting area of feature)"); + } } - public static double calculateMaxExtent(Geometry geom) throws InternalServerException { - try { - // https://gis.stackexchange.com/questions/265481/geotools-unexpected-result-reprojecting-bounding-box-to-epsg3035 - System.setProperty("org.geotools.referencing.forceXY", "true"); + public static double calculateMaxExtent(Geometry geom) throws InternalServerException { + try { + // https://gis.stackexchange.com/questions/265481/geotools-unexpected-result-reprojecting-bounding-box-to-epsg3035 + System.setProperty("org.geotools.referencing.forceXY", "true"); - Polygon poly = (Polygon) geom; + Polygon poly = (Polygon) geom; - CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:4326"); + CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:4326"); - String mollweideProj = "PROJCS[\"World_Mollweide\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Mollweide\"],PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",0],UNIT[\"Meter\",1],AUTHORITY[\"EPSG\",\"54009\"]]"; + String mollweideProj = "PROJCS[\"World_Mollweide\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Mollweide\"],PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",0],UNIT[\"Meter\",1],AUTHORITY[\"EPSG\",\"54009\"]]"; - CoordinateReferenceSystem targetCRS = CRS.parseWKT(mollweideProj); + CoordinateReferenceSystem targetCRS = CRS.parseWKT(mollweideProj); - MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS); - Geometry targetGeometry = JTS.transform(poly, transform); + MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS); + Geometry targetGeometry = JTS.transform(poly, transform); - Envelope envelope = targetGeometry.getEnvelopeInternal(); - return Math.max(envelope.getHeight(), envelope.getWidth()); - } catch (NoSuchAuthorityCodeException e) { - throw new InternalServerException("Could not set CRS authority (getting area of feature)"); - } catch (FactoryException fe) { - throw new InternalServerException("Problem setting up Geometry (getting area of feature)"); - } catch (MismatchedDimensionException e) { - throw new InternalServerException("Problem with feature dimensions (getting area of feature)"); - } catch (TransformException e) { - throw new InternalServerException("Could not transform features (getting area of feature)"); - } - } + Envelope envelope = targetGeometry.getEnvelopeInternal(); + return Math.max(envelope.getHeight(), envelope.getWidth()); + } catch (NoSuchAuthorityCodeException e) { + throw new InternalServerException("Could not set CRS authority (getting area of feature)"); + } catch (FactoryException fe) { + throw new InternalServerException("Problem setting up Geometry (getting area of feature)"); + } catch (MismatchedDimensionException e) { + throw new InternalServerException("Problem with feature dimensions (getting area of feature)"); + } catch (TransformException e) { + throw new InternalServerException("Could not transform features (getting area of feature)"); + } + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/HTTPUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/HTTPUtility.java index 0b90473e1b..b7882e2aec 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/HTTPUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/HTTPUtility.java @@ -1,15 +1,15 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; @@ -23,26 +23,27 @@ import java.net.URLConnection; public final class HTTPUtility { - private HTTPUtility() {} + private HTTPUtility() { + } - public static String getResponse(String req, int timeOut, String userAgent, String encoding) throws IOException { - URL url = new URL(req); - URLConnection conn = url.openConnection(); - if (!Helper.isEmpty(userAgent)) - conn.setRequestProperty("User-Agent", userAgent); - if (timeOut > 0) - conn.setReadTimeout(timeOut); - // conn.setRequestProperty("Accept-Language", "de,de-de;q=0.8,en;q=0.5,en-us;q=0.3") - InputStream is = conn.getInputStream(); - BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding)); - String line = ""; - StringBuilder sb = new StringBuilder(); - while ((line = br.readLine()) != null) { - sb.append(line); - } - br.close(); - is.close(); - - return sb.toString(); - } + public static String getResponse(String req, int timeOut, String userAgent, String encoding) throws IOException { + URL url = new URL(req); + URLConnection conn = url.openConnection(); + if (!Helper.isEmpty(userAgent)) + conn.setRequestProperty("User-Agent", userAgent); + if (timeOut > 0) + conn.setReadTimeout(timeOut); + // conn.setRequestProperty("Accept-Language", "de,de-de;q=0.8,en;q=0.5,en-us;q=0.3") + InputStream is = conn.getInputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding)); + String line = ""; + StringBuilder sb = new StringBuilder(); + while ((line = br.readLine()) != null) { + sb.append(line); + } + br.close(); + is.close(); + + return sb.toString(); + } } \ No newline at end of file diff --git a/ors-engine/src/main/java/org/heigit/ors/util/PolylineEncoder.java b/ors-engine/src/main/java/org/heigit/ors/util/PolylineEncoder.java index 6d88a32209..2a103b7fb9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/PolylineEncoder.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/PolylineEncoder.java @@ -1,63 +1,62 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; import org.locationtech.jts.geom.Coordinate; public class PolylineEncoder { - private PolylineEncoder() {} - - public static String encode(final Coordinate[] coords, boolean includeElevation, StringBuilder buffer) { - long lat; - long lon; - long prevLat = 0; - long prevLon = 0; - long elev = 0; - long prevEle = 0; - - buffer.setLength(0); - - for (final Coordinate c : coords) { - lat = Math.round(c.y * 1e5); - lon = Math.round(c.x * 1e5); - - encode(lat - prevLat, buffer); - encode(lon - prevLon, buffer); - - if (includeElevation) - { - elev = (long)Math.floor(c.z * 100); - encode(elev - prevEle, buffer); - prevEle = elev; - } - - prevLat = lat; - prevLon = lon; - } - - return buffer.toString(); - } - - private static void encode(long v, StringBuilder buffer) { - v = v < 0 ? ~(v << 1) : v << 1; - - while (v >= 0x20) - { - buffer.append(Character.toChars((int) ((0x20 | (v & 0x1f)) + 63))); - v >>= 5; - } - - buffer.append(Character.toChars((int) (v + 63))); - } + private PolylineEncoder() { + } + + public static String encode(final Coordinate[] coords, boolean includeElevation, StringBuilder buffer) { + long lat; + long lon; + long prevLat = 0; + long prevLon = 0; + long elev = 0; + long prevEle = 0; + + buffer.setLength(0); + + for (final Coordinate c : coords) { + lat = Math.round(c.y * 1e5); + lon = Math.round(c.x * 1e5); + + encode(lat - prevLat, buffer); + encode(lon - prevLon, buffer); + + if (includeElevation) { + elev = (long) Math.floor(c.z * 100); + encode(elev - prevEle, buffer); + prevEle = elev; + } + + prevLat = lat; + prevLon = lon; + } + + return buffer.toString(); + } + + private static void encode(long v, StringBuilder buffer) { + v = v < 0 ? ~(v << 1) : v << 1; + + while (v >= 0x20) { + buffer.append(Character.toChars((int) ((0x20 | (v & 0x1f)) + 63))); + v >>= 5; + } + + buffer.append(Character.toChars((int) (v + 63))); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/RuntimeUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/RuntimeUtility.java index 92cd555667..85d009eaef 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/RuntimeUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/RuntimeUtility.java @@ -1,65 +1,66 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; -import java.text.DecimalFormat; - import org.apache.log4j.Logger; +import java.text.DecimalFormat; + public class RuntimeUtility { - private RuntimeUtility() {} + private RuntimeUtility() { + } - public static void clearMemory(Logger logger) { - logger.info("====> Recycling garbage..."); - printRAMInfo("Before: ", logger); - Runtime.getRuntime().gc(); - printRAMInfo("After: ", logger); - logger.info("========================================================================"); - } + public static void clearMemory(Logger logger) { + logger.info("====> Recycling garbage..."); + printRAMInfo("Before: ", logger); + Runtime.getRuntime().gc(); + printRAMInfo("After: ", logger); + logger.info("========================================================================"); + } + + public static void printRAMInfo(String hint, Logger logger) { + logger.info(hint + "Total - " + getMemorySize(Runtime.getRuntime().totalMemory()) + ", Free - " + + getMemorySize(Runtime.getRuntime().freeMemory()) + ", Max: " + getMemorySize(Runtime.getRuntime().maxMemory()) + + ", Used - " + + getMemorySize(Runtime.getRuntime().totalMemory() - (Runtime.getRuntime().freeMemory()))); + } - public static void printRAMInfo(String hint, Logger logger) { - logger.info(hint + "Total - " + getMemorySize(Runtime.getRuntime().totalMemory()) + ", Free - " - + getMemorySize(Runtime.getRuntime().freeMemory()) + ", Max: " + getMemorySize(Runtime.getRuntime().maxMemory()) - + ", Used - " - + getMemorySize(Runtime.getRuntime().totalMemory() -(Runtime.getRuntime().freeMemory()))); - } - - public static String getMemorySize(long size) { + public static String getMemorySize(long size) { String hrSize = null; double b = size; - double k = size/1024.0; - double m = ((size/1024.0)/1024.0); - double g = (((size/1024.0)/1024.0)/1024.0); - double t = ((((size/1024.0)/1024.0)/1024.0)/1024.0); + double k = size / 1024.0; + double m = ((size / 1024.0) / 1024.0); + double g = (((size / 1024.0) / 1024.0) / 1024.0); + double t = ((((size / 1024.0) / 1024.0) / 1024.0) / 1024.0); DecimalFormat dec1 = new DecimalFormat("0.00"); DecimalFormat dec2 = new DecimalFormat("0"); - if (t>1) { + if (t > 1) { hrSize = isDouble(t) ? dec1.format(t).concat(" TB") : dec2.format(t).concat(" TB"); - } else if (g>1) { + } else if (g > 1) { hrSize = isDouble(g) ? dec1.format(g).concat(" GB") : dec2.format(g).concat(" GB"); - } else if (m>1) { + } else if (m > 1) { hrSize = isDouble(m) ? dec1.format(m).concat(" MB") : dec2.format(m).concat(" MB"); - } else if (k>1) { + } else if (k > 1) { hrSize = isDouble(k) ? dec1.format(k).concat(" KB") : dec2.format(k).concat(" KB"); } else { hrSize = isDouble(b) ? dec1.format(b).concat(" B") : dec2.format(b).concat(" B"); } return hrSize; } - - private static boolean isDouble(double value) { + + private static boolean isDouble(double value) { return value % 1 != 0; } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/StackTraceUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/StackTraceUtility.java index d60eee4110..51e802af03 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/StackTraceUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/StackTraceUtility.java @@ -1,58 +1,62 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; import org.apache.log4j.Logger; -import java.io.*; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; /** -* Simple utilities to return the stack trace of an -* exception as a String. -*/ + * Simple utilities to return the stack trace of an + * exception as a String. + */ public final class StackTraceUtility { - private static final Logger LOGGER = Logger.getLogger(StackTraceUtility.class.getName()); - - public static String getStackTrace(Throwable aThrowable) { - final Writer result = new StringWriter(); - final PrintWriter printWriter = new PrintWriter(result); - aThrowable.printStackTrace(printWriter); - return result.toString(); - } - - /** - * Defines a custom format for the stack trace as String. - */ - public static String getCustomStackTrace(Throwable aThrowable) { - //add the class name and any message passed to constructor - final StringBuilder result = new StringBuilder( "BOO-BOO: " ); - result.append(aThrowable.toString()); - final String NEW_LINE = System.getProperty("line.separator"); - result.append(NEW_LINE); - - //add each element of the stack trace - for (StackTraceElement element : aThrowable.getStackTrace() ){ - result.append( element ); - result.append( NEW_LINE ); + private static final Logger LOGGER = Logger.getLogger(StackTraceUtility.class.getName()); + + public static String getStackTrace(Throwable aThrowable) { + final Writer result = new StringWriter(); + final PrintWriter printWriter = new PrintWriter(result); + aThrowable.printStackTrace(printWriter); + return result.toString(); + } + + /** + * Defines a custom format for the stack trace as String. + */ + public static String getCustomStackTrace(Throwable aThrowable) { + //add the class name and any message passed to constructor + final StringBuilder result = new StringBuilder("BOO-BOO: "); + result.append(aThrowable.toString()); + final String NEW_LINE = System.getProperty("line.separator"); + result.append(NEW_LINE); + + //add each element of the stack trace + for (StackTraceElement element : aThrowable.getStackTrace()) { + result.append(element); + result.append(NEW_LINE); + } + return result.toString(); + } + + /** + * Demonstrate output. + */ + public static void main(String... aArguments) { + final Throwable throwable = new IllegalArgumentException("Blah"); + LOGGER.info(getStackTrace(throwable)); + LOGGER.info(getCustomStackTrace(throwable)); } - return result.toString(); - } - - /** Demonstrate output. */ - public static void main (String... aArguments){ - final Throwable throwable = new IllegalArgumentException("Blah"); - LOGGER.info(getStackTrace(throwable)); - LOGGER.info(getCustomStackTrace(throwable)); - } } \ No newline at end of file diff --git a/ors-engine/src/main/java/org/heigit/ors/util/StreamUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/StreamUtility.java index ecd1911278..fa32485df4 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/StreamUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/StreamUtility.java @@ -1,27 +1,22 @@ /* This file is part of Openrouteservice. * - * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the - * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 + * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. - * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. - * You should have received a copy of the GNU Lesser General Public License along with this library; - * if not, see . + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; - import com.graphhopper.util.Helper; +import java.io.*; + /** *

    * Title: StreamUtility @@ -29,71 +24,67 @@ *

    * Description:
    *

    - * + * *

    * Copyright: Copyright (c) 2014 by Maxim Rylov *

    - * + * * @author Maxim Rylov, maxim.rylov@geog.uni-heidelberg.de - * * @version 1.0 2014-05-15 */ public class StreamUtility { - private StreamUtility() {} + private StreamUtility() { + } + + public static String readStream(InputStream stream, int bufferSize) throws IOException { + return readStream(stream, bufferSize, null); + } - public static String readStream(InputStream stream, int bufferSize) throws IOException { - return readStream(stream, bufferSize, null); - } + /** + * @param stream InputStream + * @param bufferSize int + * @return result String + * @throws IOException + */ + public static String readStream(InputStream stream, int bufferSize, String encoding) throws IOException { + StringWriter sw = new StringWriter(); + int bytesRead; - /** - * - * - * @param stream - * InputStream - * @param bufferSize - * int - * @return result String - * @throws IOException - */ - public static String readStream(InputStream stream, int bufferSize, String encoding) throws IOException { - StringWriter sw = new StringWriter(); - int bytesRead; + if (!Helper.isEmpty(encoding)) { + BufferedReader br = new BufferedReader(new InputStreamReader(stream, encoding), bufferSize); + String str; + while ((str = br.readLine()) != null) { + sw.write(str); + } + } else { + byte[] buffer = new byte[bufferSize]; - if (!Helper.isEmpty(encoding)) { - BufferedReader br = new BufferedReader(new InputStreamReader(stream, encoding), bufferSize); - String str; - while ((str = br.readLine()) != null) { - sw.write(str); - } - } else { - byte[] buffer = new byte[bufferSize]; + while ((bytesRead = stream.read(buffer)) != -1) { + sw.write(new String(buffer, 0, bytesRead)); + } + } - while ((bytesRead = stream.read(buffer)) != -1) { - sw.write(new String(buffer, 0, bytesRead)); - } - } + return sw.toString(); + } - return sw.toString(); - } + public static byte[] toByteArray(InputStream stream, int bufferSize) throws IOException { + byte[] buffer = new byte[bufferSize]; + ByteArrayOutputStream os = new ByteArrayOutputStream(); + int bytesRead; + while ((bytesRead = stream.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } - public static byte[] toByteArray(InputStream stream, int bufferSize) throws IOException { - byte[] buffer = new byte[bufferSize]; - ByteArrayOutputStream os = new ByteArrayOutputStream(); - int bytesRead; - while ((bytesRead = stream.read(buffer)) != -1) { - os.write(buffer, 0, bytesRead); - } + os.flush(); - os.flush(); + return os.toByteArray(); + } - return os.toByteArray(); - } + public static String readStream(InputStream stream) throws IOException { + return readStream(stream, 8192); + } - public static String readStream(InputStream stream) throws IOException { - return readStream(stream, 8192); - } - - public static String readStream(InputStream stream, String encoding) throws IOException { - return readStream(stream, 8192, encoding); - } + public static String readStream(InputStream stream, String encoding) throws IOException { + return readStream(stream, 8192, encoding); + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/StringUtility.java b/ors-engine/src/main/java/org/heigit/ors/util/StringUtility.java index 5b17231e0c..34d3d10996 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/StringUtility.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/StringUtility.java @@ -18,117 +18,116 @@ public class StringUtility { - private StringUtility() {} + private StringUtility() { + } - public static boolean isEmpty( String str ) - { + public static boolean isEmpty(String str) { return str == null || str.trim().length() == 0; } - public static String substring(String str, char pattern) { - int pos1 = -1; - int pos2 = -1; - for (int j = 0; j < str.length(); j++) { - if (str.charAt(j) == pattern) { - if (pos1 == -1) - pos1 = j; - else { - pos2 = j; - break; - } - } - } - if (pos1 != -1 && pos2 != -1) - return str.substring(pos1 + 1, pos2); - else - return null; - } - - public static boolean containsDigit(String s) { - if (s != null && !s.isEmpty()) { - for ( int i = 0; i < s.length(); ++i ) { - char ch = s.charAt(i); - if ((ch >= '0' && ch <= '9' )) - return true; - } - } - return false; - } - - public static String trimQuotes(String str) - { - return trim(str, '"'); - } - - public static String trim(String str, char ch) { - if (str == null) - return null; - String result = str; - int firstChar = str.indexOf(ch); - int lastChar = str.lastIndexOf(ch); - int length = str.length(); - if (firstChar == 0 && lastChar == length - 1) - result = result.substring(1, length - 1); - - return result; - } - - public static String arrayToString(double[] array, String separator) { - int length = array.length; - if (length == 0) return ""; - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < length; ++i) { - sb.append(array[i]); - if (i < length -1 ) - sb.append(separator); - } - return sb.toString(); - } - - public static String combine(String[] values, String separator) { - if (values == null) - return null; - StringBuilder result = new StringBuilder(); - int n = values.length; - for (int i = 0 ; i < n; ++i) { - result.append(values[i]).append(i < n - 1 ? separator : ""); - } - return result.toString(); - } - - public static String decodeRequestString(String inputString) throws UnsupportedEncodingException { - if (inputString.startsWith("REQUEST=")) { - inputString = inputString.substring(8); - } - if (inputString.startsWith("xml=")) { - inputString = inputString.substring(4); - } else if (inputString.startsWith("---")) { - int iIndexStart = inputString.indexOf("= '0' && ch <= '9')) + return true; + } + } + return false; + } + + public static String trimQuotes(String str) { + return trim(str, '"'); + } + + public static String trim(String str, char ch) { + if (str == null) + return null; + String result = str; + int firstChar = str.indexOf(ch); + int lastChar = str.lastIndexOf(ch); + int length = str.length(); + if (firstChar == 0 && lastChar == length - 1) + result = result.substring(1, length - 1); + + return result; + } + + public static String arrayToString(double[] array, String separator) { + int length = array.length; + if (length == 0) return ""; + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < length; ++i) { + sb.append(array[i]); + if (i < length - 1) + sb.append(separator); + } + return sb.toString(); + } + + public static String combine(String[] values, String separator) { + if (values == null) + return null; + StringBuilder result = new StringBuilder(); + int n = values.length; + for (int i = 0; i < n; ++i) { + result.append(values[i]).append(i < n - 1 ? separator : ""); + } + return result.toString(); + } + + public static String decodeRequestString(String inputString) throws UnsupportedEncodingException { + if (inputString.startsWith("REQUEST=")) { + inputString = inputString.substring(8); + } + if (inputString.startsWith("xml=")) { + inputString = inputString.substring(4); + } else if (inputString.startsWith("---")) { + int iIndexStart = inputString.indexOf(". + * You should have received a copy of the GNU Lesser General Public License along with this library; + * if not, see . */ package org.heigit.ors.util; public final class TimeUtility { - private TimeUtility() {} + private TimeUtility() { + } - public static String getElapsedTime(long startTime, boolean addSeconds) { - return getElapsedTime(startTime, System.currentTimeMillis(), addSeconds); - } - - public static String getElapsedTime(long startTime, long endTime, boolean addSeconds) { - long time = endTime - startTime; - double handlingTimeSeconds = (double) time / 1000; - String res = Double.toString(handlingTimeSeconds).replace(",", "."); - if (addSeconds) - res += "s"; - return res; - } + public static String getElapsedTime(long startTime, boolean addSeconds) { + return getElapsedTime(startTime, System.currentTimeMillis(), addSeconds); + } + + public static String getElapsedTime(long startTime, long endTime, boolean addSeconds) { + long time = endTime - startTime; + double handlingTimeSeconds = (double) time / 1000; + String res = Double.toString(handlingTimeSeconds).replace(",", "."); + if (addSeconds) + res += "s"; + return res; + } } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/UnitsConverter.java b/ors-engine/src/main/java/org/heigit/ors/util/UnitsConverter.java index c438a7e4ee..e6e1f24ec9 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/UnitsConverter.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/UnitsConverter.java @@ -4,14 +4,14 @@ * http://www.giscience.uni-hd.de * http://www.heigit.org * - * under one or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information regarding copyright - * ownership. The GIScience licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except in compliance + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. The GIScience licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,31 +21,31 @@ package org.heigit.ors.util; public class UnitsConverter { - private UnitsConverter() {} + private UnitsConverter() { + } - public static double sqMetersToSqMiles(double value) { - return value * 3.86102e-7; + public static double sqMetersToSqMiles(double value) { + return value * 3.86102e-7; } - public static double sqMetersToSqKilometers(double value) { - return value * 1e-6; + public static double sqMetersToSqKilometers(double value) { + return value * 1e-6; } public static double metersToKilometers(double value) { - return value * 0.001; + return value * 0.001; } - public static double metersToMiles(double value) - { - return value * 0.000621371; + public static double metersToMiles(double value) { + return value * 0.000621371; } /** * Convert a OSM width value to a decimal value in metres. In osm the width could be stored in many different units * and so this method attempts to convert them all to metres. * - * @param unprocessedLinearValue The obtained width tag value - * @return The width value converted to metres + * @param unprocessedLinearValue The obtained width tag value + * @return The width value converted to metres */ public static double convertOSMDistanceTagToMeters(String unprocessedLinearValue) { double processedLinearValue = -1d; @@ -65,11 +65,11 @@ public static double convertOSMDistanceTagToMeters(String unprocessedLinearValue if (unprocessedLinearValue.contains(" ")) { // we are working with a specified unit String[] split = unprocessedLinearValue.split(" "); - if(split.length == 2) { + if (split.length == 2) { try { processedLinearValue = Double.parseDouble(split[0]); - switch(split[1]) { + switch (split[1]) { case "m": // do nothing as already in metres break; @@ -96,7 +96,7 @@ public static double convertOSMDistanceTagToMeters(String unprocessedLinearValue } else if (unprocessedLinearValue.contains("'") && unprocessedLinearValue.contains("\"")) { // Working with feet and inches String[] split = unprocessedLinearValue.split("'"); - if(split.length == 2) { + if (split.length == 2) { split[1] = split[1].replace("\"", ""); try { processedLinearValue = Double.parseDouble(split[0]) * 12d; // 12 inches to a foot @@ -119,7 +119,7 @@ public static double convertOSMDistanceTagToMeters(String unprocessedLinearValue } // If the processedLinearValue is still -1, then it could be that they have used an invalid tag, so just try and parse the most common mistakes - if(processedLinearValue == -1d) { + if (processedLinearValue == -1d) { // Be careful of the order as 3cm ends in both cm and m, so we should check for cm first try { if (unprocessedLinearValue.endsWith("cm")) { @@ -132,7 +132,7 @@ public static double convertOSMDistanceTagToMeters(String unprocessedLinearValue if (split.length == 2) { processedLinearValue = Double.parseDouble(split[0]) / 0.001f; } - }else if (unprocessedLinearValue.endsWith("nmi")) { + } else if (unprocessedLinearValue.endsWith("nmi")) { String[] split = unprocessedLinearValue.split("nmi"); if (split.length == 2) { processedLinearValue = Double.parseDouble(split[0]) / 0.000539957; @@ -155,7 +155,7 @@ public static double convertOSMDistanceTagToMeters(String unprocessedLinearValue } // If the value is more than three, we need more bits in the encoder to store it, so we can just cap to 3 - if(processedLinearValue > 3) + if (processedLinearValue > 3) processedLinearValue = 3; return processedLinearValue; @@ -165,14 +165,13 @@ public static double convertOSMDistanceTagToMeters(String unprocessedLinearValue * Convert the String representation of an incline into a %age incline value. in OSM the tag value could already * be a %age value, or it could be written as "up", "down", "steep" etc. in which case an incline value is assumed * - * @param unprocessedInclineValue The value obtained from the incline tag - * @param declineToIncline If true, always return a positive value, otherwise decline slopes are returned as negative values - * @return a percentage incline value + * @param unprocessedInclineValue The value obtained from the incline tag + * @param declineToIncline If true, always return a positive value, otherwise decline slopes are returned as negative values + * @return a percentage incline value */ public static int convertOSMInclineValueToPercentage(String unprocessedInclineValue, boolean declineToIncline) { - if (unprocessedInclineValue != null) - { + if (unprocessedInclineValue != null) { double v = 0d; boolean isDegree = false; try { @@ -199,7 +198,7 @@ public static int convertOSMInclineValueToPercentage(String unprocessedInclineVa v = 0; } - if(declineToIncline && v < 0) { + if (declineToIncline && v < 0) { v = v * -1.0; } diff --git a/ors-engine/src/main/java/org/heigit/ors/util/mockuputil/RoutingRequestMockup.java b/ors-engine/src/main/java/org/heigit/ors/util/mockuputil/RoutingRequestMockup.java index 4beadffeb5..debfbadb9e 100644 --- a/ors-engine/src/main/java/org/heigit/ors/util/mockuputil/RoutingRequestMockup.java +++ b/ors-engine/src/main/java/org/heigit/ors/util/mockuputil/RoutingRequestMockup.java @@ -25,11 +25,11 @@ package org.heigit.ors.util.mockuputil; -import org.locationtech.jts.geom.Coordinate; import org.heigit.ors.common.DistanceUnit; import org.heigit.ors.routing.RouteInstructionsFormat; import org.heigit.ors.routing.RoutingRequest; import org.heigit.ors.routing.pathprocessors.BordersExtractor; +import org.locationtech.jts.geom.Coordinate; /** * This is a {@link org.heigit.ors.routing.RoutingRequest} Mockup-Class, used in junit tests and wherever needed. diff --git a/ors-engine/src/main/java/org/opensphere/geometry/algorithm/ConcaveHullOpenSphere.java b/ors-engine/src/main/java/org/opensphere/geometry/algorithm/ConcaveHullOpenSphere.java index e6d9c94d66..cb08b98731 100644 --- a/ors-engine/src/main/java/org/opensphere/geometry/algorithm/ConcaveHullOpenSphere.java +++ b/ors-engine/src/main/java/org/opensphere/geometry/algorithm/ConcaveHullOpenSphere.java @@ -1,7 +1,7 @@ /* * This file is part of the OpenSphere project which aims to * develop geospatial algorithms. - * + * * Copyright (C) 2012 Eric Grosso * * This library is free software; you can redistribute it and/or @@ -20,26 +20,11 @@ * * For more information, contact: * Eric Grosso, eric.grosso.os@gmail.com - * + * */ package org.opensphere.geometry.algorithm; -import java.util.*; -import java.util.Map.Entry; - -import org.opensphere.geometry.triangulation.model.Edge; -import org.opensphere.geometry.triangulation.model.Triangle; -import org.opensphere.geometry.triangulation.model.Vertex; - -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.Geometry; -import org.locationtech.jts.geom.GeometryCollection; -import org.locationtech.jts.geom.GeometryFactory; -import org.locationtech.jts.geom.LineSegment; -import org.locationtech.jts.geom.LineString; -import org.locationtech.jts.geom.LinearRing; -import org.locationtech.jts.geom.Point; -import org.locationtech.jts.geom.Polygon; +import org.locationtech.jts.geom.*; import org.locationtech.jts.geom.impl.CoordinateArraySequence; import org.locationtech.jts.operation.linemerge.LineMerger; import org.locationtech.jts.triangulate.ConformingDelaunayTriangulationBuilder; @@ -47,6 +32,12 @@ import org.locationtech.jts.triangulate.quadedge.QuadEdgeSubdivision; import org.locationtech.jts.triangulate.quadedge.QuadEdgeTriangle; import org.locationtech.jts.util.UniqueCoordinateArrayFilter; +import org.opensphere.geometry.triangulation.model.Edge; +import org.opensphere.geometry.triangulation.model.Triangle; +import org.opensphere.geometry.triangulation.model.Vertex; + +import java.util.*; +import java.util.Map.Entry; /** * Computes a concave hull of a {@link Geometry} which is a concave @@ -61,7 +52,6 @@ * set of points in the plane". * * @author Eric Grosso - * */ public class ConcaveHullOpenSphere { @@ -97,7 +87,7 @@ public ConcaveHullOpenSphere(Geometry geometry, double threshold) { */ // Modification by Maxim Rylov: Added convertGeometryCollection parameter public ConcaveHullOpenSphere(GeometryCollection geometries, double threshold, boolean convertGeometryCollection) { - this.geometries = convertGeometryCollection ? transformIntoPointGeometryCollection(geometries): geometries; + this.geometries = convertGeometryCollection ? transformIntoPointGeometryCollection(geometries) : geometries; this.threshold = threshold; this.geomFactory = geometries.getFactory(); } @@ -140,7 +130,7 @@ private static GeometryCollection transformIntoPointGeometryCollection(GeometryC CoordinateArraySequence cs = new CoordinateArraySequence(c); geometries[i] = new Point(cs, gc.getFactory()); } - + return new GeometryCollection(geometries, gc.getFactory()); } @@ -175,6 +165,7 @@ private static class QuadEdgeLineSegment { private final QuadEdge qe; private final LineSegment ls; private final double length; + public QuadEdgeLineSegment(QuadEdge qe) { this.qe = qe; this.ls = qe.toLineSegment(); diff --git a/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Edge.java b/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Edge.java index e9663c354b..b7606019c5 100644 --- a/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Edge.java +++ b/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Edge.java @@ -1,7 +1,7 @@ /* * This file is part of the OpenSphere project which aims to * develop geospatial algorithms. - * + * * Copyright (C) 2012 Eric Grosso * * This library is free software; you can redistribute it and/or @@ -20,353 +20,331 @@ * * For more information, contact: * Eric Grosso, eric.grosso.os@gmail.com - * + * */ package org.opensphere.geometry.triangulation.model; +import org.locationtech.jts.geom.LineSegment; + import java.util.ArrayList; import java.util.List; -import org.locationtech.jts.geom.LineSegment; - /** * Edge. - * - * @author Eric Grosso * + * @author Eric Grosso */ public class Edge { - /** ID of the edge */ - private int id; - - /** Geometry of the edge */ - private LineSegment geometry; - - /** Indicator to know if the edge is a border edge - * of the triangulation framework */ - private boolean border; - - /** Origin vertex of the edge */ - private Vertex oV; - - /** End vertex of the edge */ - private Vertex eV; - - /** Triangles in relationship with this edge */ - private List triangles = new ArrayList<>(); - - /** Edges in relationship with this edge */ - private List incidentEdges = new ArrayList<>(); - - - /** - * Default constructor. - */ - public Edge() { - // - } - - /** - * Constructor. - * - * @param id - * ID of the edge - */ - public Edge(int id) { - this.id = id; - } - - /** - * Constructor. - * - * @param id - * ID of the edge - * @param geometry - * geometry of the edge (segment) - */ - public Edge(int id, LineSegment geometry) { - this.id = id; - this.geometry = geometry; - } - - /** - * Constructor. - * - * @param id - * ID of the edge - * @param border - * defines if the edge is a border edge - * or not in the triangulation framework - */ - public Edge(int id, boolean border) { - this.id = id; - this.border = border; - } - - /** - * Constructor. - * - * @param id - * ID of the edge - * @param geometry - * geometry of the edge (segment) - * @param border - * defines if the edge is a border edge - * or not in the triangulation framework - */ - public Edge(int id, LineSegment geometry, boolean border) { - this.id = id; - this.geometry = geometry; - this.border = border; - } - - /** - * Constructor. - * - * @param id - * ID of the edge - * @param geometry - * geometry of the edge (segment) - * @param oV - * origin vertex - * @param eV - * end vertex - * @param border - * defines if the edge is a border edge - * or not in the triangulation framework - */ - public Edge(int id, LineSegment geometry, Vertex oV, Vertex eV, boolean border) { - this.id = id; - this.geometry = geometry; - this.oV = oV; - this.eV = eV; - this.border = border; - } - - - /** - * Returns the ID of the edge. - * - * @return - * the ID of the edge - */ - public int getId() { - return this.id; - } - - /** - * Defines the ID of the edge. - * - * @param id - * ID of the edge - */ - public void setId(int id) { - this.id = id; - } - - /** - * Returns the geometry of the edge. - * - * @return - * the geometry of the edge - */ - public LineSegment getGeometry() { - return this.geometry; - } - - /** - * Defines the geometry of the edge. - * - * @param geometry - * geometry of the edge (segment) - */ - public void setGeometry(LineSegment geometry) { - this.geometry = geometry; - } - - /** - * Returns true if the edge is a border edge - * of the triangulation framework, false otherwise. - * - * @return - * true if the edge is a border edge, - * false otherwise - */ - public boolean isBorder() { - return this.border; - } - - /** - * Defines the indicator to know if the edge - * is a border edge of the triangulation framework. - * - * @param border - * true if the edge is a border edge, - * false otherwise - */ - public void setBorder(boolean border) { - this.border = border; - } - - /** - * Returns the origin vertex of the edge. - * - * @return - * the origin vertex of the edge - */ - public Vertex getOV() { - return this.oV; - } - - /** - * Defines the origin vertex of the edge. - * - * @param oV - * origin vertex of the edge - */ - public void setOV(Vertex oV) { - this.oV = oV; - } - - /** - * Returns the end vertex of the edge. - * - * @return - * the end vertex of the edge - */ - public Vertex getEV() { - return this.eV; - } - - /** - * Defines the end vertex of the edge. - * - * @param eV - * end vertex of the edge - */ - public void setEV(Vertex eV) { - this.eV = eV; - } - - /** - * Returns the triangles in relationship with the edge. - * - * @return - * the triangles in relationship with the edge - */ - public List getTriangles() { - return this.triangles; - } - - /** - * Defines the triangles in relationship with the edge. - * - * @param triangles - * the triangles in relationship with the edge - */ - public void setTriangles(List triangles) { - this.triangles = triangles; - } - - /** - * Returns the edges in relationship with the edge. - * - * @return - * the edges in relationship with the edge - */ - public List getIncidentEdges() { - return this.incidentEdges; - } - - /** - * Defines the edges in relationship with the edge. - * - * @param edges - * the edges in relationship with the edge - */ - public void setIncidentEdges(List edges) { - this.incidentEdges = edges; - } - - /** - * Add a triangle in relationship with the edge. - * - * @return - * true if added, false otherwise - */ - public boolean addTriangle(Triangle triangle) { - return getTriangles().add(triangle); - } - - /** - * Add triangles in relationship with the edge. - * - * @return - * true if added, false otherwise - */ - public boolean addTriangles(List triangles) { - return getTriangles().addAll(triangles); - } - - /** - * Remove a triangle in relationship with the edge. - * - * @return - * true if removed, false otherwise - */ - public boolean removeTriangle(Triangle triangle) { - return getTriangles().remove(triangle); - } - - /** - * Remove triangles in relationship with the edge. - * - * @return - * true if removed, false otherwise - */ - public boolean removeTriangles(List triangles) { - return getTriangles().removeAll(triangles); - } - - /** - * Add an incident edge in relationship with the edge. - * - * @return - * true if added, false otherwise - */ - public boolean addIncidentEdge(Edge edge) { - return getIncidentEdges().add(edge); - } - - /** - * Add incident edges in relationship with the edge. - * - * @return - * true if added, false otherwise - */ - public boolean addIncidentEdges(List edges) { - return getIncidentEdges().addAll(edges); - } - - /** - * Remove an incident edge in relationship with the edge. - * - * @return - * true if removed, false otherwise - */ - public boolean removeIncidentEdge(Edge edge) { - return getIncidentEdges().remove(edge); - } - - /** - * Remove incident edges in relationship with the edge. - * - * @return - * true if removed, false otherwise - */ - public boolean removeAllIncidentEdges(List edges) { - return getIncidentEdges().removeAll(edges); - } + /** + * ID of the edge + */ + private int id; + + /** + * Geometry of the edge + */ + private LineSegment geometry; + + /** + * Indicator to know if the edge is a border edge + * of the triangulation framework + */ + private boolean border; + + /** + * Origin vertex of the edge + */ + private Vertex oV; + + /** + * End vertex of the edge + */ + private Vertex eV; + + /** + * Triangles in relationship with this edge + */ + private List triangles = new ArrayList<>(); + + /** + * Edges in relationship with this edge + */ + private List incidentEdges = new ArrayList<>(); + + + /** + * Default constructor. + */ + public Edge() { + // + } + + /** + * Constructor. + * + * @param id ID of the edge + */ + public Edge(int id) { + this.id = id; + } + + /** + * Constructor. + * + * @param id ID of the edge + * @param geometry geometry of the edge (segment) + */ + public Edge(int id, LineSegment geometry) { + this.id = id; + this.geometry = geometry; + } + + /** + * Constructor. + * + * @param id ID of the edge + * @param border defines if the edge is a border edge + * or not in the triangulation framework + */ + public Edge(int id, boolean border) { + this.id = id; + this.border = border; + } + + /** + * Constructor. + * + * @param id ID of the edge + * @param geometry geometry of the edge (segment) + * @param border defines if the edge is a border edge + * or not in the triangulation framework + */ + public Edge(int id, LineSegment geometry, boolean border) { + this.id = id; + this.geometry = geometry; + this.border = border; + } + + /** + * Constructor. + * + * @param id ID of the edge + * @param geometry geometry of the edge (segment) + * @param oV origin vertex + * @param eV end vertex + * @param border defines if the edge is a border edge + * or not in the triangulation framework + */ + public Edge(int id, LineSegment geometry, Vertex oV, Vertex eV, boolean border) { + this.id = id; + this.geometry = geometry; + this.oV = oV; + this.eV = eV; + this.border = border; + } + + + /** + * Returns the ID of the edge. + * + * @return the ID of the edge + */ + public int getId() { + return this.id; + } + + /** + * Defines the ID of the edge. + * + * @param id ID of the edge + */ + public void setId(int id) { + this.id = id; + } + + /** + * Returns the geometry of the edge. + * + * @return the geometry of the edge + */ + public LineSegment getGeometry() { + return this.geometry; + } + + /** + * Defines the geometry of the edge. + * + * @param geometry geometry of the edge (segment) + */ + public void setGeometry(LineSegment geometry) { + this.geometry = geometry; + } + + /** + * Returns true if the edge is a border edge + * of the triangulation framework, false otherwise. + * + * @return true if the edge is a border edge, + * false otherwise + */ + public boolean isBorder() { + return this.border; + } + + /** + * Defines the indicator to know if the edge + * is a border edge of the triangulation framework. + * + * @param border true if the edge is a border edge, + * false otherwise + */ + public void setBorder(boolean border) { + this.border = border; + } + + /** + * Returns the origin vertex of the edge. + * + * @return the origin vertex of the edge + */ + public Vertex getOV() { + return this.oV; + } + + /** + * Defines the origin vertex of the edge. + * + * @param oV origin vertex of the edge + */ + public void setOV(Vertex oV) { + this.oV = oV; + } + + /** + * Returns the end vertex of the edge. + * + * @return the end vertex of the edge + */ + public Vertex getEV() { + return this.eV; + } + + /** + * Defines the end vertex of the edge. + * + * @param eV end vertex of the edge + */ + public void setEV(Vertex eV) { + this.eV = eV; + } + + /** + * Returns the triangles in relationship with the edge. + * + * @return the triangles in relationship with the edge + */ + public List getTriangles() { + return this.triangles; + } + + /** + * Defines the triangles in relationship with the edge. + * + * @param triangles the triangles in relationship with the edge + */ + public void setTriangles(List triangles) { + this.triangles = triangles; + } + + /** + * Returns the edges in relationship with the edge. + * + * @return the edges in relationship with the edge + */ + public List getIncidentEdges() { + return this.incidentEdges; + } + + /** + * Defines the edges in relationship with the edge. + * + * @param edges the edges in relationship with the edge + */ + public void setIncidentEdges(List edges) { + this.incidentEdges = edges; + } + + /** + * Add a triangle in relationship with the edge. + * + * @return true if added, false otherwise + */ + public boolean addTriangle(Triangle triangle) { + return getTriangles().add(triangle); + } + + /** + * Add triangles in relationship with the edge. + * + * @return true if added, false otherwise + */ + public boolean addTriangles(List triangles) { + return getTriangles().addAll(triangles); + } + + /** + * Remove a triangle in relationship with the edge. + * + * @return true if removed, false otherwise + */ + public boolean removeTriangle(Triangle triangle) { + return getTriangles().remove(triangle); + } + + /** + * Remove triangles in relationship with the edge. + * + * @return true if removed, false otherwise + */ + public boolean removeTriangles(List triangles) { + return getTriangles().removeAll(triangles); + } + + /** + * Add an incident edge in relationship with the edge. + * + * @return true if added, false otherwise + */ + public boolean addIncidentEdge(Edge edge) { + return getIncidentEdges().add(edge); + } + + /** + * Add incident edges in relationship with the edge. + * + * @return true if added, false otherwise + */ + public boolean addIncidentEdges(List edges) { + return getIncidentEdges().addAll(edges); + } + + /** + * Remove an incident edge in relationship with the edge. + * + * @return true if removed, false otherwise + */ + public boolean removeIncidentEdge(Edge edge) { + return getIncidentEdges().remove(edge); + } + + /** + * Remove incident edges in relationship with the edge. + * + * @return true if removed, false otherwise + */ + public boolean removeAllIncidentEdges(List edges) { + return getIncidentEdges().removeAll(edges); + } } \ No newline at end of file diff --git a/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Triangle.java b/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Triangle.java index 4400077ebd..2143671f7a 100644 --- a/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Triangle.java +++ b/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Triangle.java @@ -1,7 +1,7 @@ /* * This file is part of the OpenSphere project which aims to * develop geospatial algorithms. - * + * * Copyright (C) 2012 Eric Grosso * * This library is free software; you can redistribute it and/or @@ -20,7 +20,7 @@ * * For more information, contact: * Eric Grosso, eric.grosso.os@gmail.com - * + * */ package org.opensphere.geometry.triangulation.model; @@ -29,222 +29,210 @@ /** * Triangle. - * - * @author Eric Grosso * + * @author Eric Grosso */ public class Triangle { - /** ID of the triangle */ - private int id; - - /** Indicator to know if the triangle is a border triangle - * of the triangulation framework */ - private boolean border; - - /** Edges which compose the triangle */ - private List edges = new ArrayList<>(); - - /** Neighbour triangles of this triangle */ - private List neighbours = new ArrayList<>(); - - // vertices... - - /** - * Default constructor. - */ - public Triangle() { - // - } - - /** - * Constructor. - * - * @param id - * ID of the triangle - */ - public Triangle(int id) { - this.id = id; - } - - /** - * Constructor. - * - * @param id - * ID of the triangle - * @param border - * defines if the triangle is a border triangle - * or not in the triangulation framework - */ - public Triangle(int id, boolean border) { - this.id = id; - this.border = border; - } - - /** - * Returns the ID of the triangle. - * - * @return - * the ID of the triangle - */ - public int getId() { - return this.id; - } - - /** - * Defines the ID of the triangle. - * - * @param id - * ID of the triangle - */ - public void setId(int id) { - this.id = id; - } - - /** - * Returns true if the triangle is a border triangle - * of the triangulation framework, false otherwise. - * - * @return - * true if the triangle is a border triangle, - * false otherwise - */ - public boolean isBorder() { - return this.border; - } - - /** - * Defines the indicator to know if the triangle - * is a border triangle of the triangulation framework. - * - * @param border - * true if the triangle is a border triangle, - * false otherwise - */ - public void setBorder(boolean border) { - this.border = border; - } - - /** - * Returns the edges which compose the triangle. - * - * @return - * the edges of the triangle which compose the triangle - */ - public List getEdges() { - return this.edges; - } - - /** - * Defines the edges which compose the triangle. - * - * @param edges - * the edges which compose the triangle - */ - public void setEdges(List edges) { - this.edges = edges; - } - - /** - * Returns the neighbour triangles of the triangle. - * - * @return - * the neighbour triangles of the triangle - */ - public List getNeighbours() { - return this.neighbours; - } - - /** - * Defines the neighbour triangles of the triangle. - * - * @param neighbours - * the neighbour triangles of the triangle - */ - public void setNeighbours(List neighbours) { - this.neighbours = neighbours; - } - - - /** - * Add an edge to the triangle. - * - * @return - * true if added, false otherwise - */ - public boolean addEdge(Edge edge) { - return getEdges().add(edge); - } - - /** - * Add edges to the triangle. - * - * @return - * true if added, false otherwise - */ - public boolean addEdges(List edges) { - return getEdges().addAll(edges); - } - - /** - * Remove an edge of the triangle. - * - * @return - * true if removed, false otherwise - */ - public boolean removeEdge(Edge edge) { - return getEdges().remove(edge); - } - - /** - * Remove edges of the triangle. - * - * @return - * true if removed, false otherwise - */ - public boolean removeEdges(List edges) { - return getEdges().removeAll(edges); - } - - - /** - * Add a neighbour triangle to the triangle. - * - * @return - * true if added, false otherwise - */ - public boolean addNeighbour(Triangle triangle) { - return getNeighbours().add(triangle); - } - - /** - * Add neighbour triangles to the triangle. - * - * @return - * true if added, false otherwise - */ - public boolean addNeighbours(List triangles) { - return getNeighbours().addAll(triangles); - } - - /** - * Remove a neighbour triangle of the triangle. - * - * @return - * true if removed, false otherwise - */ - public boolean removeNeighbour(Triangle triangle) { - return getNeighbours().remove(triangle); - } - - /** - * Remove neighbour triangles of the triangle. - * - * @return - * true if removed, false otherwise - */ - public boolean removeNeighbours(List triangles) { - return getNeighbours().removeAll(triangles); - } + /** + * ID of the triangle + */ + private int id; + + /** + * Indicator to know if the triangle is a border triangle + * of the triangulation framework + */ + private boolean border; + + /** + * Edges which compose the triangle + */ + private List edges = new ArrayList<>(); + + /** + * Neighbour triangles of this triangle + */ + private List neighbours = new ArrayList<>(); + + // vertices... + + /** + * Default constructor. + */ + public Triangle() { + // + } + + /** + * Constructor. + * + * @param id ID of the triangle + */ + public Triangle(int id) { + this.id = id; + } + + /** + * Constructor. + * + * @param id ID of the triangle + * @param border defines if the triangle is a border triangle + * or not in the triangulation framework + */ + public Triangle(int id, boolean border) { + this.id = id; + this.border = border; + } + + /** + * Returns the ID of the triangle. + * + * @return the ID of the triangle + */ + public int getId() { + return this.id; + } + + /** + * Defines the ID of the triangle. + * + * @param id ID of the triangle + */ + public void setId(int id) { + this.id = id; + } + + /** + * Returns true if the triangle is a border triangle + * of the triangulation framework, false otherwise. + * + * @return true if the triangle is a border triangle, + * false otherwise + */ + public boolean isBorder() { + return this.border; + } + + /** + * Defines the indicator to know if the triangle + * is a border triangle of the triangulation framework. + * + * @param border true if the triangle is a border triangle, + * false otherwise + */ + public void setBorder(boolean border) { + this.border = border; + } + + /** + * Returns the edges which compose the triangle. + * + * @return the edges of the triangle which compose the triangle + */ + public List getEdges() { + return this.edges; + } + + /** + * Defines the edges which compose the triangle. + * + * @param edges the edges which compose the triangle + */ + public void setEdges(List edges) { + this.edges = edges; + } + + /** + * Returns the neighbour triangles of the triangle. + * + * @return the neighbour triangles of the triangle + */ + public List getNeighbours() { + return this.neighbours; + } + + /** + * Defines the neighbour triangles of the triangle. + * + * @param neighbours the neighbour triangles of the triangle + */ + public void setNeighbours(List neighbours) { + this.neighbours = neighbours; + } + + + /** + * Add an edge to the triangle. + * + * @return true if added, false otherwise + */ + public boolean addEdge(Edge edge) { + return getEdges().add(edge); + } + + /** + * Add edges to the triangle. + * + * @return true if added, false otherwise + */ + public boolean addEdges(List edges) { + return getEdges().addAll(edges); + } + + /** + * Remove an edge of the triangle. + * + * @return true if removed, false otherwise + */ + public boolean removeEdge(Edge edge) { + return getEdges().remove(edge); + } + + /** + * Remove edges of the triangle. + * + * @return true if removed, false otherwise + */ + public boolean removeEdges(List edges) { + return getEdges().removeAll(edges); + } + + + /** + * Add a neighbour triangle to the triangle. + * + * @return true if added, false otherwise + */ + public boolean addNeighbour(Triangle triangle) { + return getNeighbours().add(triangle); + } + + /** + * Add neighbour triangles to the triangle. + * + * @return true if added, false otherwise + */ + public boolean addNeighbours(List triangles) { + return getNeighbours().addAll(triangles); + } + + /** + * Remove a neighbour triangle of the triangle. + * + * @return true if removed, false otherwise + */ + public boolean removeNeighbour(Triangle triangle) { + return getNeighbours().remove(triangle); + } + + /** + * Remove neighbour triangles of the triangle. + * + * @return true if removed, false otherwise + */ + public boolean removeNeighbours(List triangles) { + return getNeighbours().removeAll(triangles); + } } \ No newline at end of file diff --git a/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Vertex.java b/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Vertex.java index c6c23313e0..48a6767578 100644 --- a/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Vertex.java +++ b/ors-engine/src/main/java/org/opensphere/geometry/triangulation/model/Vertex.java @@ -1,7 +1,7 @@ /* * This file is part of the OpenSphere project which aims to * develop geospatial algorithms. - * + * * Copyright (C) 2012 Eric Grosso * * This library is free software; you can redistribute it and/or @@ -20,7 +20,7 @@ * * For more information, contact: * Eric Grosso, eric.grosso.os@gmail.com - * + * */ package org.opensphere.geometry.triangulation.model; @@ -28,145 +28,136 @@ /** * Vertex. - * - * @author Eric Grosso * + * @author Eric Grosso */ public class Vertex { - /** ID of the vertex */ - private int id; - - /** Coordinate of the vertex */ - private Coordinate coordinate; - - /** Indicator to know if the vertex is a border vertex - * of the triangulation framework */ - private boolean border; - - /** - * Default constructor. - */ - public Vertex() { - // - } - - /** - * Constructor. - * - * @param id - * ID of the vertex - */ - public Vertex(int id) { - this.id = id; - } - - /** - * Constructor. - * - * @param id - * ID of the vertex - * @param coordinate - * coordinate of the vertex - */ - public Vertex(int id, Coordinate coordinate) { - this.id = id; - this.setCoordinate(coordinate); - } - - /** - * Constructor. - * - * @param id - * ID of the vertex - * @param border - * defines if the vertex is a border vertex - * or not in the triangulation framework - */ - public Vertex(int id, boolean border) { - this.id = id; - this.border = border; - } - - /** - * Constructor. - * - * @param id - * ID of the vertex - * @param coordinate - * coordinate of the vertex - * @param border - * defines if the vertex is a border vertex - * or not in the triangulation framework - */ - public Vertex(int id, Coordinate coordinate, boolean border) { - this.id = id; - this.border = border; - this.setCoordinate(coordinate); - } - - /** - * Returns the ID of the vertex. - * - * @return - * the ID of the vertex - */ - public int getId() { - return this.id; - } - - /** - * Defines the ID of the vertex. - * - * @param id - * the ID of the vertex - */ - public void setId(int id) { - this.id = id; - } - - /** - * Returns the coordinate of the vertex. - * - * @return - * the coordinate of the vertex - */ - public Coordinate getCoordinate() { - return this.coordinate; - } - - /** - * Defines the coordinate of the vertex. - * - * @param c - * the coordinate of the vertex - */ - public void setCoordinate(Coordinate c) { - this.coordinate = c; - } - - /** - * Returns true if the vertex is a border vertex - * of the triangulation framework, false otherwise. - * - * @return - * true if the vertex is a border vertex, - * false otherwise - */ - public boolean isBorder() { - return this.border; - } - - /** - * Defines the indicator to know if the edge - * is a border edge of the triangulation framework. - * - * @param border - * true if the edge is a border edge, - * false otherwise - */ - public void setBorder(boolean border) { - this.border = border; - } + /** + * ID of the vertex + */ + private int id; + + /** + * Coordinate of the vertex + */ + private Coordinate coordinate; + + /** + * Indicator to know if the vertex is a border vertex + * of the triangulation framework + */ + private boolean border; + + /** + * Default constructor. + */ + public Vertex() { + // + } + + /** + * Constructor. + * + * @param id ID of the vertex + */ + public Vertex(int id) { + this.id = id; + } + + /** + * Constructor. + * + * @param id ID of the vertex + * @param coordinate coordinate of the vertex + */ + public Vertex(int id, Coordinate coordinate) { + this.id = id; + this.setCoordinate(coordinate); + } + + /** + * Constructor. + * + * @param id ID of the vertex + * @param border defines if the vertex is a border vertex + * or not in the triangulation framework + */ + public Vertex(int id, boolean border) { + this.id = id; + this.border = border; + } + + /** + * Constructor. + * + * @param id ID of the vertex + * @param coordinate coordinate of the vertex + * @param border defines if the vertex is a border vertex + * or not in the triangulation framework + */ + public Vertex(int id, Coordinate coordinate, boolean border) { + this.id = id; + this.border = border; + this.setCoordinate(coordinate); + } + + /** + * Returns the ID of the vertex. + * + * @return the ID of the vertex + */ + public int getId() { + return this.id; + } + + /** + * Defines the ID of the vertex. + * + * @param id the ID of the vertex + */ + public void setId(int id) { + this.id = id; + } + + /** + * Returns the coordinate of the vertex. + * + * @return the coordinate of the vertex + */ + public Coordinate getCoordinate() { + return this.coordinate; + } + + /** + * Defines the coordinate of the vertex. + * + * @param c the coordinate of the vertex + */ + public void setCoordinate(Coordinate c) { + this.coordinate = c; + } + + /** + * Returns true if the vertex is a border vertex + * of the triangulation framework, false otherwise. + * + * @return true if the vertex is a border vertex, + * false otherwise + */ + public boolean isBorder() { + return this.border; + } + + /** + * Defines the indicator to know if the edge + * is a border edge of the triangulation framework. + * + * @param border true if the edge is a border edge, + * false otherwise + */ + public void setBorder(boolean border) { + this.border = border; + } } \ No newline at end of file diff --git a/ors-engine/src/main/resources/resources/locales/ors_cs-CZ.resources b/ors-engine/src/main/resources/resources/locales/ors_cs-CZ.resources index 0e2e161f0c..5ebbfe5092 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_cs-CZ.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_cs-CZ.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1.", - "2": "2.", - "3": "3.", - "4": "4.", - "5": "5.", - "6": "6.", - "7": "7.", - "8": "8.", - "9": "9.", - "10": "10." - }, - "directions": { - "north": "sever", - "northeast": "severovýchod", - "east": "východ", - "southeast": "jihovýchod", - "south": "jih", - "southwest": "jihozápad", - "west": "západ", - "northwest": "severozápad" - }, - "turn_maneuvers": { - "left": "vlevo", - "right": "vpravo", - "sharp_left": "ostře vlevo", - "sharp_right": "ostře vpravo", - "slight_left": "mírně vlevo", - "slight_right": "mírně vpravo", - "straight": "přímo", - "uturn": "otočit zpět" - }, - "actions": { - "arrive": { - "default": { - "default": "Dorazil jste do cíle", - "name": "Dorazil do {way_name}" + "instructions": { + "numerals": { + "1": "1.", + "2": "2.", + "3": "3.", + "4": "4.", + "5": "5.", + "6": "6.", + "7": "7.", + "8": "8.", + "9": "9.", + "10": "10." }, - "left": { - "default": "Dorazil jste do cíle, nalevo", - "name": "dorazil jste do {way_name}, nalevo" + "directions": { + "north": "sever", + "northeast": "severovýchod", + "east": "východ", + "southeast": "jihovýchod", + "south": "jih", + "southwest": "jihozápad", + "west": "západ", + "northwest": "severozápad" }, - "right": { - "default": "Dorazil jste do cíle, napravo", - "name": "Dorazil jste do {way_name}, napravo" + "turn_maneuvers": { + "left": "vlevo", + "right": "vpravo", + "sharp_left": "ostře vlevo", + "sharp_right": "ostře vpravo", + "slight_left": "mírně vlevo", + "slight_right": "mírně vpravo", + "straight": "přímo", + "uturn": "otočit zpět" }, - "straight": { - "default": "Dorazil jste do cíle, rovně před vámi", - "name": "Dorazil jste do {way_name}, rovně před vámi" + "actions": { + "arrive": { + "default": { + "default": "Dorazil jste do cíle", + "name": "Dorazil do {way_name}" + }, + "left": { + "default": "Dorazil jste do cíle, nalevo", + "name": "dorazil jste do {way_name}, nalevo" + }, + "right": { + "default": "Dorazil jste do cíle, napravo", + "name": "Dorazil jste do {way_name}, napravo" + }, + "straight": { + "default": "Dorazil jste do cíle, rovně před vámi", + "name": "Dorazil jste do {way_name}, rovně před vámi" + } + }, + "depart": { + "default": { + "default": "Jeďte {direction}", + "name": "Jeďte {direction} na {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Na kruhovém objezdu sjeďte na {exit_number} sjezdu", + "name": "Na kruhovém objezdu sjeďte na {exit_number} sjezdu na {way_name}" + }, + "default": { + "default": "Vjeďte na kruhový objezd", + "name": "Vjeďte na kruhová objezd a sjeďte na {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Zahněte {turn_maneuver}", + "name": "Zahněte {turn_maneuver} na {way_name}" + } + }, + "continue": { + "default": { + "default": "Jeďte dál {turn_maneuver}", + "name": "Jeďte dál {turn_maneuver} na {way_name}" + }, + "uturn": { + "default": "Otočte se", + "name": "Otočte se na {way_name}" + } + }, + "keep": { + "default": { + "default": "Pokračujte {turn_maneuver}", + "name": "Pokračujte {turn_maneuver} na {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Jeďte {direction}", - "name": "Jeďte {direction} na {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Na kruhovém objezdu sjeďte na {exit_number} sjezdu", - "name": "Na kruhovém objezdu sjeďte na {exit_number} sjezdu na {way_name}" - }, - "default": { - "default": "Vjeďte na kruhový objezd", - "name": "Vjeďte na kruhová objezd a sjeďte na {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Zahněte {turn_maneuver}", - "name": "Zahněte {turn_maneuver} na {way_name}" - } - }, - "continue": { - "default": { - "default": "Jeďte dál {turn_maneuver}", - "name": "Jeďte dál {turn_maneuver} na {way_name}" - }, - "uturn": { - "default": "Otočte se", - "name": "Otočte se na {way_name}" - } - }, - "keep": { - "default": { - "default": "Pokračujte {turn_maneuver}", - "name": "Pokračujte {turn_maneuver} na {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_de-DE.resources b/ors-engine/src/main/resources/resources/locales/ors_de-DE.resources index 9f68298b80..b20f158cb7 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_de-DE.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_de-DE.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "erste", - "2": "zweite", - "3": "dritte", - "4": "vierte", - "5": "fünfte", - "6": "sechste", - "7": "siebte", - "8": "achte", - "9": "neunte", - "10": "zehnte" - }, - "directions": { - "north": "nördlich", - "northeast": "nordöstlich", - "east": "östlich", - "southeast": "südöstlich", - "south": "südlich", - "southwest": "südwestlich", - "west": "westlich", - "northwest": "nordwestlich" - }, - "turn_maneuvers": { - "left": "links", - "right": "rechts", - "sharp_left": "scharf links", - "sharp_right": "scharf rechts", - "slight_left": "leicht links", - "slight_right": "leicht rechts", - "straight": "geradeaus", - "uturn": "Kehrtwendung" - }, - "actions": { - "arrive": { - "default": { - "default": "Ziel erreicht", - "name": "Sie erreichen {way_name}" + "instructions": { + "numerals": { + "1": "erste", + "2": "zweite", + "3": "dritte", + "4": "vierte", + "5": "fünfte", + "6": "sechste", + "7": "siebte", + "8": "achte", + "9": "neunte", + "10": "zehnte" }, - "left": { - "default": "Ziel erreicht (links)", - "name": "Sie erreichen {way_name} (links)" + "directions": { + "north": "nördlich", + "northeast": "nordöstlich", + "east": "östlich", + "southeast": "südöstlich", + "south": "südlich", + "southwest": "südwestlich", + "west": "westlich", + "northwest": "nordwestlich" }, - "right": { - "default": "Ziel erreicht (rechts)", - "name": "Sie erreichen {way_name} (rechts)" + "turn_maneuvers": { + "left": "links", + "right": "rechts", + "sharp_left": "scharf links", + "sharp_right": "scharf rechts", + "slight_left": "leicht links", + "slight_right": "leicht rechts", + "straight": "geradeaus", + "uturn": "Kehrtwendung" }, - "straight": { - "default": "Ziel erreicht (geradeaus)", - "name": "Sie erreichen {way_name} (geradeaus)" + "actions": { + "arrive": { + "default": { + "default": "Ziel erreicht", + "name": "Sie erreichen {way_name}" + }, + "left": { + "default": "Ziel erreicht (links)", + "name": "Sie erreichen {way_name} (links)" + }, + "right": { + "default": "Ziel erreicht (rechts)", + "name": "Sie erreichen {way_name} (rechts)" + }, + "straight": { + "default": "Ziel erreicht (geradeaus)", + "name": "Sie erreichen {way_name} (geradeaus)" + } + }, + "depart": { + "default": { + "default": "Weiter {direction}", + "name": "Weiter {direction} auf {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Fahren Sie in den Kreisverkehr und nehmen die {exit_number} Ausfahrt", + "name": "Fahren Sie in den Kreisverkehr und verlassen ihn an der {exit_number} Ausfahrt in {way_name}" + }, + "default": { + "default": "Fahren Sie in den Kreisverkehr", + "name": "Fahren Sie in den Kreisverkehr und verlassen ihn in {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Biegen Sie {turn_maneuver} ab", + "name": "Biegen Sie {turn_maneuver} auf {way_name} ab" + } + }, + "continue": { + "default": { + "default": "Weiter {turn_maneuver}", + "name": "Weiter {turn_maneuver} auf {way_name}" + }, + "uturn": { + "default": "Eine Kehrtwendung vollziehen", + "name": "Eine Kehrtwendung auf {way_name} vollziehen" + } + }, + "keep": { + "default": { + "default": "{turn_maneuver} halten", + "name": "{turn_maneuver} halten auf {way_name}" + } + }, + "pt": { + "start": { + "default": "Einsteigen in {name}", + "headsign": "Einsteigen in {name} nach {headsign}" + }, + "transfer": { + "default": "Umsteigen in {name}", + "headsign": "Umsteigen in {name} nach {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Weiter {direction}", - "name": "Weiter {direction} auf {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Fahren Sie in den Kreisverkehr und nehmen die {exit_number} Ausfahrt", - "name": "Fahren Sie in den Kreisverkehr und verlassen ihn an der {exit_number} Ausfahrt in {way_name}" - }, - "default": { - "default": "Fahren Sie in den Kreisverkehr", - "name": "Fahren Sie in den Kreisverkehr und verlassen ihn in {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Biegen Sie {turn_maneuver} ab", - "name": "Biegen Sie {turn_maneuver} auf {way_name} ab" - } - }, - "continue": { - "default": { - "default": "Weiter {turn_maneuver}", - "name": "Weiter {turn_maneuver} auf {way_name}" - }, - "uturn": { - "default": "Eine Kehrtwendung vollziehen", - "name": "Eine Kehrtwendung auf {way_name} vollziehen" - } - }, - "keep": { - "default": { - "default": "{turn_maneuver} halten", - "name": "{turn_maneuver} halten auf {way_name}" - } - }, - "pt": { - "start": { - "default": "Einsteigen in {name}", - "headsign": "Einsteigen in {name} nach {headsign}" - }, - "transfer": { - "default": "Umsteigen in {name}", - "headsign": "Umsteigen in {name} nach {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_en-US.resources b/ors-engine/src/main/resources/resources/locales/ors_en-US.resources index 29f8b735f5..d97a770d86 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_en-US.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_en-US.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1st", - "2": "2nd", - "3": "3rd", - "4": "4th", - "5": "5th", - "6": "6th", - "7": "7th", - "8": "8th", - "9": "9th", - "10": "10th" - }, - "directions": { - "north": "north", - "northeast": "northeast", - "east": "east", - "southeast": "southeast", - "south": "south", - "southwest": "southwest", - "west": "west", - "northwest": "northwest" - }, - "turn_maneuvers": { - "left": "left", - "right": "right", - "sharp_left": "sharp left", - "sharp_right": "sharp right", - "slight_left": "slight left", - "slight_right": "slight right", - "straight": "straight", - "uturn": "U-turn" - }, - "actions": { - "arrive": { - "default": { - "default": "Arrive at your destination", - "name": "Arrive at {way_name}" + "instructions": { + "numerals": { + "1": "1st", + "2": "2nd", + "3": "3rd", + "4": "4th", + "5": "5th", + "6": "6th", + "7": "7th", + "8": "8th", + "9": "9th", + "10": "10th" }, - "left": { - "default": "Arrive at your destination, on the left", - "name": "Arrive at {way_name}, on the left" + "directions": { + "north": "north", + "northeast": "northeast", + "east": "east", + "southeast": "southeast", + "south": "south", + "southwest": "southwest", + "west": "west", + "northwest": "northwest" }, - "right": { - "default": "Arrive at your destination, on the right", - "name": "Arrive at {way_name}, on the right" + "turn_maneuvers": { + "left": "left", + "right": "right", + "sharp_left": "sharp left", + "sharp_right": "sharp right", + "slight_left": "slight left", + "slight_right": "slight right", + "straight": "straight", + "uturn": "U-turn" }, - "straight": { - "default": "Arrive at your destination, straight ahead", - "name": "Arrive at {way_name}, straight ahead" + "actions": { + "arrive": { + "default": { + "default": "Arrive at your destination", + "name": "Arrive at {way_name}" + }, + "left": { + "default": "Arrive at your destination, on the left", + "name": "Arrive at {way_name}, on the left" + }, + "right": { + "default": "Arrive at your destination, on the right", + "name": "Arrive at {way_name}, on the right" + }, + "straight": { + "default": "Arrive at your destination, straight ahead", + "name": "Arrive at {way_name}, straight ahead" + } + }, + "depart": { + "default": { + "default": "Head {direction}", + "name": "Head {direction} on {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Enter the roundabout and take the {exit_number} exit", + "name": "Enter the roundabout and take the {exit_number} exit onto {way_name}" + }, + "default": { + "default": "Enter the roundabout", + "name": "Enter the roundabout and exit onto {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Turn {turn_maneuver}", + "name": "Turn {turn_maneuver} onto {way_name}" + } + }, + "continue": { + "default": { + "default": "Continue {turn_maneuver}", + "name": "Continue {turn_maneuver} onto {way_name}" + }, + "uturn": { + "default": "Make a U-turn", + "name": "Make a U-turn onto {way_name}" + } + }, + "keep": { + "default": { + "default": "Keep {turn_maneuver}", + "name": "Keep {turn_maneuver} onto {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Head {direction}", - "name": "Head {direction} on {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Enter the roundabout and take the {exit_number} exit", - "name": "Enter the roundabout and take the {exit_number} exit onto {way_name}" - }, - "default": { - "default": "Enter the roundabout", - "name": "Enter the roundabout and exit onto {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Turn {turn_maneuver}", - "name": "Turn {turn_maneuver} onto {way_name}" - } - }, - "continue": { - "default": { - "default": "Continue {turn_maneuver}", - "name": "Continue {turn_maneuver} onto {way_name}" - }, - "uturn": { - "default": "Make a U-turn", - "name": "Make a U-turn onto {way_name}" - } - }, - "keep": { - "default": { - "default": "Keep {turn_maneuver}", - "name": "Keep {turn_maneuver} onto {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_eo-EO.resources b/ors-engine/src/main/resources/resources/locales/ors_eo-EO.resources index f922d8de9c..df822cb65d 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_eo-EO.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_eo-EO.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "unue", - "2": "dua", - "3": "tria", - "4": "kvara", - "5": "kvina", - "6": "sesa", - "7": "sepa", - "8": "oka", - "9": "naŭa", - "10": "deka" - }, - "directions": { - "north": "nordo", - "northeast": "nordoriento", - "east": "oriento", - "southeast": "sudoriento", - "south": "sudo", - "southwest": "sudokcidento", - "west": "okcidento", - "northwest": "nordokcidento" - }, - "turn_maneuvers": { - "left": "maldekstre", - "right": "dekstre", - "sharp_left": "akra maldekstre", - "sharp_right": "akra dekstre", - "slight_left": "iomete maldekstre", - "slight_right": "iomete dekstre", - "straight": "rekte", - "uturn": "U-turno" - }, - "actions": { - "arrive": { - "default": { - "default": "Alvenis ĉe via destino", - "name": "Alvenu ĉe {way_name}" + "instructions": { + "numerals": { + "1": "unue", + "2": "dua", + "3": "tria", + "4": "kvara", + "5": "kvina", + "6": "sesa", + "7": "sepa", + "8": "oka", + "9": "naŭa", + "10": "deka" }, - "left": { - "default": "Alvenis ĉe via destino, maldekstre", - "name": "Alvenu ĉe {way_name}, maldekstre" + "directions": { + "north": "nordo", + "northeast": "nordoriento", + "east": "oriento", + "southeast": "sudoriento", + "south": "sudo", + "southwest": "sudokcidento", + "west": "okcidento", + "northwest": "nordokcidento" }, - "right": { - "default": "Alvenis ĉe via destino, sur la dekstra flanko", - "name": "Alvenu ĉe {way_name}, sur la dekstra flanko" + "turn_maneuvers": { + "left": "maldekstre", + "right": "dekstre", + "sharp_left": "akra maldekstre", + "sharp_right": "akra dekstre", + "slight_left": "iomete maldekstre", + "slight_right": "iomete dekstre", + "straight": "rekte", + "uturn": "U-turno" }, - "straight": { - "default": "Alvenis ĉe via destino, rekte antaŭ", - "name": "Alvenu ĉe {way_name} , rekte antaŭ" + "actions": { + "arrive": { + "default": { + "default": "Alvenis ĉe via destino", + "name": "Alvenu ĉe {way_name}" + }, + "left": { + "default": "Alvenis ĉe via destino, maldekstre", + "name": "Alvenu ĉe {way_name}, maldekstre" + }, + "right": { + "default": "Alvenis ĉe via destino, sur la dekstra flanko", + "name": "Alvenu ĉe {way_name}, sur la dekstra flanko" + }, + "straight": { + "default": "Alvenis ĉe via destino, rekte antaŭ", + "name": "Alvenu ĉe {way_name} , rekte antaŭ" + } + }, + "depart": { + "default": { + "default": "Iru {direction}", + "name": "Iru {direction} sur {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Enigu la trafikcirklon kaj prenu la {exit_number} elirejo", + "name": "Enigu la trafikcirklon kaj prenu la {exit_number} elirejo sur {way_name}" + }, + "default": { + "default": "Enigu la trafikcirklon", + "name": "Enigu la trafikcirklon kaj eliru sur {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Turnu {turn_maneuver}n", + "name": "Turnu {turn_maneuver}n sur {way_name}" + } + }, + "continue": { + "default": { + "default": "Daŭrigu {turn_maneuver}", + "name": "Daŭrigu {turn_maneuver} sur {way_name}" + }, + "uturn": { + "default": "Faru U-turnon", + "name": "Faru U-turnon sur {way_name}" + } + }, + "keep": { + "default": { + "default": "Tenu {turn_maneuver}", + "name": "Tenu {turn_maneuver} sur {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Iru {direction}", - "name": "Iru {direction} sur {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Enigu la trafikcirklon kaj prenu la {exit_number} elirejo", - "name": "Enigu la trafikcirklon kaj prenu la {exit_number} elirejo sur {way_name}" - }, - "default": { - "default": "Enigu la trafikcirklon", - "name": "Enigu la trafikcirklon kaj eliru sur {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Turnu {turn_maneuver}n", - "name": "Turnu {turn_maneuver}n sur {way_name}" - } - }, - "continue": { - "default": { - "default": "Daŭrigu {turn_maneuver}", - "name": "Daŭrigu {turn_maneuver} sur {way_name}" - }, - "uturn": { - "default": "Faru U-turnon", - "name": "Faru U-turnon sur {way_name}" - } - }, - "keep": { - "default": { - "default": "Tenu {turn_maneuver}", - "name": "Tenu {turn_maneuver} sur {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_es-ES.resources b/ors-engine/src/main/resources/resources/locales/ors_es-ES.resources index 4ee8888ca8..3e5576db85 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_es-ES.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_es-ES.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1a", - "2": "2a", - "3": "3a", - "4": "4a", - "5": "5a", - "6": "6a", - "7": "7a", - "8": "8a", - "9": "9a", - "10": "10a" - }, - "directions": { - "north": "norte", - "northeast": "nordeste", - "east": "este", - "southeast": "sudeste", - "south": "sur", - "southwest": "suroeste", - "west": "oeste", - "northwest": "noroeste" - }, - "turn_maneuvers": { - "left": "a la izquierda", - "right": "a la derecha", - "sharp_left": "bastante a la izquierda", - "sharp_right": "bastante a la derecha", - "slight_left": "ligeramente a la izquierda", - "slight_right": "ligeramente a la derecha", - "straight": "todo recto", - "uturn": "atrás" - }, - "actions": { - "arrive": { - "default": { - "default": "Llegar a su destino", - "name": "Llegar a {way_name}" + "instructions": { + "numerals": { + "1": "1a", + "2": "2a", + "3": "3a", + "4": "4a", + "5": "5a", + "6": "6a", + "7": "7a", + "8": "8a", + "9": "9a", + "10": "10a" }, - "left": { - "default": "Llegar a su destino, a la izquierda", - "name": "Llegar a {way_name}, a la izquierda" + "directions": { + "north": "norte", + "northeast": "nordeste", + "east": "este", + "southeast": "sudeste", + "south": "sur", + "southwest": "suroeste", + "west": "oeste", + "northwest": "noroeste" }, - "right": { - "default": "Llegar a su destino, a la derecha", - "name": "Llegar a {way_name}, a la derecha" + "turn_maneuvers": { + "left": "a la izquierda", + "right": "a la derecha", + "sharp_left": "bastante a la izquierda", + "sharp_right": "bastante a la derecha", + "slight_left": "ligeramente a la izquierda", + "slight_right": "ligeramente a la derecha", + "straight": "todo recto", + "uturn": "atrás" }, - "straight": { - "default": "Llegar a su destino, es recto", - "name": "Llegar a {way_name}, es recto" + "actions": { + "arrive": { + "default": { + "default": "Llegar a su destino", + "name": "Llegar a {way_name}" + }, + "left": { + "default": "Llegar a su destino, a la izquierda", + "name": "Llegar a {way_name}, a la izquierda" + }, + "right": { + "default": "Llegar a su destino, a la derecha", + "name": "Llegar a {way_name}, a la derecha" + }, + "straight": { + "default": "Llegar a su destino, es recto", + "name": "Llegar a {way_name}, es recto" + } + }, + "depart": { + "default": { + "default": "Camina hacia el {direction}", + "name": "Camina hacia el {direction} en {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Entre en la rotonda y tome la {exit_number} salida", + "name": "Entre en la rotonda y tome la {exit_number} salida a {way_name}" + }, + "default": { + "default": "Entrar en la rotonda", + "name": "Entre en la rotonda y salga a {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Gire {turn_maneuver}", + "name": "Gire {turn_maneuver} a {way_name}" + } + }, + "continue": { + "default": { + "default": "Siga {turn_maneuver}", + "name": "Siga {turn_maneuver} a {way_name}" + }, + "uturn": { + "default": "Haga una vuelta en U", + "name": "Haga una vuelta en U a {way_name}" + } + }, + "keep": { + "default": { + "default": "Gire {turn_maneuver}", + "name": "Gire {turn_maneuver} a {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Camina hacia el {direction}", - "name": "Camina hacia el {direction} en {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Entre en la rotonda y tome la {exit_number} salida", - "name": "Entre en la rotonda y tome la {exit_number} salida a {way_name}" - }, - "default": { - "default": "Entrar en la rotonda", - "name": "Entre en la rotonda y salga a {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Gire {turn_maneuver}", - "name": "Gire {turn_maneuver} a {way_name}" - } - }, - "continue": { - "default": { - "default": "Siga {turn_maneuver}", - "name": "Siga {turn_maneuver} a {way_name}" - }, - "uturn": { - "default": "Haga una vuelta en U", - "name": "Haga una vuelta en U a {way_name}" - } - }, - "keep": { - "default": { - "default": "Gire {turn_maneuver}", - "name": "Gire {turn_maneuver} a {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_fr-FR.resources b/ors-engine/src/main/resources/resources/locales/ors_fr-FR.resources index 72f02b27db..3cb4d43fca 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_fr-FR.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_fr-FR.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1ère", - "2": "2ème", - "3": "3ème", - "4": "4ème", - "5": "5ème", - "6": "6ème", - "7": "7ème", - "8": "8ème", - "9": "9ème", - "10": "10ème" - }, - "directions": { - "north": "du Nord", - "northeast": "du Nord-Est", - "east": "de l’Est", - "southeast": "du Sud-Est", - "south": "du Sud", - "southwest": "du Sud-Ouest", - "west": "de l’Ouest", - "northwest": "du Nord-Ouest" - }, - "turn_maneuvers": { - "left": "à gauche", - "right": "à droite", - "sharp_left": "franchement à gauche", - "sharp_right": "franchement à droite", - "slight_left": "légerement à gauche", - "slight_right": "légèrement à droite", - "straight": "tout droit", - "uturn": "demi-tour" - }, - "actions": { - "arrive": { - "default": { - "default": "Arrivez à votre destination", - "name": "Arrivez à {way_name}" + "instructions": { + "numerals": { + "1": "1ère", + "2": "2ème", + "3": "3ème", + "4": "4ème", + "5": "5ème", + "6": "6ème", + "7": "7ème", + "8": "8ème", + "9": "9ème", + "10": "10ème" }, - "left": { - "default": "Arrivé à votre destination, sur la gauche", - "name": "Arrivé à {way_name}, destination sur la gauche" + "directions": { + "north": "du Nord", + "northeast": "du Nord-Est", + "east": "de l’Est", + "southeast": "du Sud-Est", + "south": "du Sud", + "southwest": "du Sud-Ouest", + "west": "de l’Ouest", + "northwest": "du Nord-Ouest" }, - "right": { - "default": "Arrivé à votre destination, sur la droite", - "name": "Arrivé à {way_name}, destination sur la droite" + "turn_maneuvers": { + "left": "à gauche", + "right": "à droite", + "sharp_left": "franchement à gauche", + "sharp_right": "franchement à droite", + "slight_left": "légerement à gauche", + "slight_right": "légèrement à droite", + "straight": "tout droit", + "uturn": "demi-tour" }, - "straight": { - "default": "Arrivé à votre destination, droit devant", - "name": "Arrivé à {way_name}, destination droit devant" + "actions": { + "arrive": { + "default": { + "default": "Arrivez à votre destination", + "name": "Arrivez à {way_name}" + }, + "left": { + "default": "Arrivé à votre destination, sur la gauche", + "name": "Arrivé à {way_name}, destination sur la gauche" + }, + "right": { + "default": "Arrivé à votre destination, sur la droite", + "name": "Arrivé à {way_name}, destination sur la droite" + }, + "straight": { + "default": "Arrivé à votre destination, droit devant", + "name": "Arrivé à {way_name}, destination droit devant" + } + }, + "depart": { + "default": { + "default": "Démarrez en direction {direction}", + "name": "Démarrez en direction {direction} sur {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Entrez sur le rond-point et prenez la {exit_number} sortie", + "name": "Entrez sur le rond-point et prenez la {exit_number} sortie sur {way_name}" + }, + "default": { + "default": "Entrez sur le rond-point", + "name": "Entrez sur le rond-point et sortie sur {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Tournez {turn_maneuver}", + "name": "Tournez {turn_maneuver} sur {way_name}" + } + }, + "continue": { + "default": { + "default": "Continuez {turn_maneuver}", + "name": "Continuez {turn_maneuver} sur {way_name}" + }, + "uturn": { + "default": "Faites un demi-tour", + "name": "Faites un demi-tour sur {way_name}" + } + }, + "keep": { + "default": { + "default": "Tournez {turn_maneuver}", + "name": "Tournez {turn_maneuver} sur {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Démarrez en direction {direction}", - "name": "Démarrez en direction {direction} sur {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Entrez sur le rond-point et prenez la {exit_number} sortie", - "name": "Entrez sur le rond-point et prenez la {exit_number} sortie sur {way_name}" - }, - "default": { - "default": "Entrez sur le rond-point", - "name": "Entrez sur le rond-point et sortie sur {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Tournez {turn_maneuver}", - "name": "Tournez {turn_maneuver} sur {way_name}" - } - }, - "continue": { - "default": { - "default": "Continuez {turn_maneuver}", - "name": "Continuez {turn_maneuver} sur {way_name}" - }, - "uturn": { - "default": "Faites un demi-tour", - "name": "Faites un demi-tour sur {way_name}" - } - }, - "keep": { - "default": { - "default": "Tournez {turn_maneuver}", - "name": "Tournez {turn_maneuver} sur {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_gr-GR.resources b/ors-engine/src/main/resources/resources/locales/ors_gr-GR.resources index d097c4b76c..73f34a21b4 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_gr-GR.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_gr-GR.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1ος", - "2": "2ος", - "3": "3ος", - "4": "4ος", - "5": "5ος", - "6": "6ος", - "7": "7ος", - "8": "8ος", - "9": "9ος", - "10": "10ος" - }, - "directions": { - "north": "βόρεια", - "northeast": "βορειοανατολικά", - "east": "ανατολικά", - "southeast": "νοτιοανατολικά", - "south": "νότια", - "southwest": "νοτιοδυτικά", - "west": "δυτικά", - "northwest": "βορειοδυτικά" - }, - "turn_maneuvers": { - "left": "αριστερά", - "right": "δεξιά", - "sharp_left": "απότομα αριστερά", - "sharp_right": "απότομα δεξιά", - "slight_left": "ελαφρά αριστερά", - "slight_right": "ελαφρά δεξιά", - "straight": "ευθεία", - "uturn": "αναστροφή" - }, - "actions": { - "arrive": { - "default": { - "default": "Φτάσετε στον προορισμό σας", - "name": "Άφιξη στο {way_name}" + "instructions": { + "numerals": { + "1": "1ος", + "2": "2ος", + "3": "3ος", + "4": "4ος", + "5": "5ος", + "6": "6ος", + "7": "7ος", + "8": "8ος", + "9": "9ος", + "10": "10ος" }, - "left": { - "default": "Άφιξη στον προορισμό σας, στα αριστερά", - "name": "Άφιξη στο {way_name}, στα αριστερά" + "directions": { + "north": "βόρεια", + "northeast": "βορειοανατολικά", + "east": "ανατολικά", + "southeast": "νοτιοανατολικά", + "south": "νότια", + "southwest": "νοτιοδυτικά", + "west": "δυτικά", + "northwest": "βορειοδυτικά" }, - "right": { - "default": "Φτάσετε στον προορισμό σας, στα δεξιά", - "name": "Άφιξη στο {way_name}, στα δεξιά" + "turn_maneuvers": { + "left": "αριστερά", + "right": "δεξιά", + "sharp_left": "απότομα αριστερά", + "sharp_right": "απότομα δεξιά", + "slight_left": "ελαφρά αριστερά", + "slight_right": "ελαφρά δεξιά", + "straight": "ευθεία", + "uturn": "αναστροφή" }, - "straight": { - "default": "Φτάσετε στον προορισμό σας, ευθεία μπροστά", - "name": "Άφιξη στο {way_name}, ευθεία μπροστά" + "actions": { + "arrive": { + "default": { + "default": "Φτάσετε στον προορισμό σας", + "name": "Άφιξη στο {way_name}" + }, + "left": { + "default": "Άφιξη στον προορισμό σας, στα αριστερά", + "name": "Άφιξη στο {way_name}, στα αριστερά" + }, + "right": { + "default": "Φτάσετε στον προορισμό σας, στα δεξιά", + "name": "Άφιξη στο {way_name}, στα δεξιά" + }, + "straight": { + "default": "Φτάσετε στον προορισμό σας, ευθεία μπροστά", + "name": "Άφιξη στο {way_name}, ευθεία μπροστά" + } + }, + "depart": { + "default": { + "default": "Συνεχίστε ευθεία {direction}", + "name": "Συνεχίστε ευθεία {direction} στην οδό {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Μπείτε στον κυκλικό κόμβο και στη συνέχεια ακολουθείστε την έξοδο {exit_number} και", + "name": "Μπείτε στον κυκλικό κόμβο και στη συνέχεια ακολουθείστε την έξοδο {exit_number} και συνεχίστε στην οδό {way_name}" + }, + "default": { + "default": "Εισάγετε τον κυκλικό κόμβο", + "name": "Μπείτε στον κυκλικό κόμβο και συνεχίστε στην οδό {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Στρίψτε {turn_maneuver}", + "name": "Στρίψτε {turn_maneuver} στην οδό {way_name}" + } + }, + "continue": { + "default": { + "default": "Συνεχίστε {turn_maneuver}", + "name": "Συνεχίστε {turn_maneuver} στην οδό {way_name}" + }, + "uturn": { + "default": "Κάντε αναστροφή", + "name": "Κάντε αναστροφή στην οδό {way_name}" + } + }, + "keep": { + "default": { + "default": "Στρίψτε {turn_maneuver}", + "name": "Στρίψτε {turn_maneuver} στην οδό {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Συνεχίστε ευθεία {direction}", - "name": "Συνεχίστε ευθεία {direction} στην οδό {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Μπείτε στον κυκλικό κόμβο και στη συνέχεια ακολουθείστε την έξοδο {exit_number} και", - "name": "Μπείτε στον κυκλικό κόμβο και στη συνέχεια ακολουθείστε την έξοδο {exit_number} και συνεχίστε στην οδό {way_name}" - }, - "default": { - "default": "Εισάγετε τον κυκλικό κόμβο", - "name": "Μπείτε στον κυκλικό κόμβο και συνεχίστε στην οδό {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Στρίψτε {turn_maneuver}", - "name": "Στρίψτε {turn_maneuver} στην οδό {way_name}" - } - }, - "continue": { - "default": { - "default": "Συνεχίστε {turn_maneuver}", - "name": "Συνεχίστε {turn_maneuver} στην οδό {way_name}" - }, - "uturn": { - "default": "Κάντε αναστροφή", - "name": "Κάντε αναστροφή στην οδό {way_name}" - } - }, - "keep": { - "default": { - "default": "Στρίψτε {turn_maneuver}", - "name": "Στρίψτε {turn_maneuver} στην οδό {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_he-IL.resources b/ors-engine/src/main/resources/resources/locales/ors_he-IL.resources index b07cc7ac5a..c2bfca9ca4 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_he-IL.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_he-IL.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "ראשון", - "2": "שני", - "3": "שלישי", - "4": "רביעי", - "5": "חמישי", - "6": "שישי", - "7": "שביעי", - "8": "שמיני", - "9": "תשיעי", - "10": "עשירי" - }, - "directions": { - "north": "צפון", - "northeast": "צפון-מזרח", - "east": "מזרח", - "southeast": "דרום-מזרח", - "south": "דרום", - "southwest": "דרום-מערב", - "west": "מערב", - "northwest": "צפון-מערב" - }, - "turn_maneuvers": { - "left": "שמאלה", - "right": "ימינה", - "sharp_left": "פניה חדה שמאלה", - "sharp_right": "פניה חדה ימינה", - "slight_left": "מעט שמאלה", - "slight_right": "מעט ימינה", - "straight": "ישר", - "uturn": "פניית פרסה" - }, - "actions": { - "arrive": { - "default": { - "default": "הגעת ליעד", - "name": "הגעת אל {way_name}" + "instructions": { + "numerals": { + "1": "ראשון", + "2": "שני", + "3": "שלישי", + "4": "רביעי", + "5": "חמישי", + "6": "שישי", + "7": "שביעי", + "8": "שמיני", + "9": "תשיעי", + "10": "עשירי" }, - "left": { - "default": "הגעת ליעד, משמאלך", - "name": "הגעת אל {way_name}, משמאלך" + "directions": { + "north": "צפון", + "northeast": "צפון-מזרח", + "east": "מזרח", + "southeast": "דרום-מזרח", + "south": "דרום", + "southwest": "דרום-מערב", + "west": "מערב", + "northwest": "צפון-מערב" }, - "right": { - "default": "הגעת ליעד, מימנך", - "name": "הגעת אל {way_name}, מימנך" + "turn_maneuvers": { + "left": "שמאלה", + "right": "ימינה", + "sharp_left": "פניה חדה שמאלה", + "sharp_right": "פניה חדה ימינה", + "slight_left": "מעט שמאלה", + "slight_right": "מעט ימינה", + "straight": "ישר", + "uturn": "פניית פרסה" }, - "straight": { - "default": "הגעת ליעד, ישר מולך", - "name": "הגעת אל {way_name}, ישר מולך" + "actions": { + "arrive": { + "default": { + "default": "הגעת ליעד", + "name": "הגעת אל {way_name}" + }, + "left": { + "default": "הגעת ליעד, משמאלך", + "name": "הגעת אל {way_name}, משמאלך" + }, + "right": { + "default": "הגעת ליעד, מימנך", + "name": "הגעת אל {way_name}, מימנך" + }, + "straight": { + "default": "הגעת ליעד, ישר מולך", + "name": "הגעת אל {way_name}, ישר מולך" + } + }, + "depart": { + "default": { + "default": "סע {direction}", + "name": "סע {direction} ב {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "כנס למעגל התנועה וצא ביציאה מספר {exit_number}", + "name": "כנס למעגל התנועה וצא ביציאה מספר {exit_number} אל {way_name}" + }, + "default": { + "default": "כנס למעגל התנועה", + "name": "כנס למעגל התנועה וצא אל {way_name}" + } + } + }, + "turn": { + "default": { + "default": "פנה {turn_maneuver}", + "name": "פנה {turn_maneuver} אל {way_name}" + } + }, + "continue": { + "default": { + "default": "המשך {turn_maneuver}", + "name": "המשך {turn_maneuver} אל {way_name}" + }, + "uturn": { + "default": "בצע פניית פרסה", + "name": "בצע פניית פרסה אל {way_name}" + } + }, + "keep": { + "default": { + "default": "המשך {turn_maneuver}", + "name": "המשך {turn_maneuver} אל {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "סע {direction}", - "name": "סע {direction} ב {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "כנס למעגל התנועה וצא ביציאה מספר {exit_number}", - "name": "כנס למעגל התנועה וצא ביציאה מספר {exit_number} אל {way_name}" - }, - "default": { - "default": "כנס למעגל התנועה", - "name": "כנס למעגל התנועה וצא אל {way_name}" - } - } - }, - "turn": { - "default": { - "default": "פנה {turn_maneuver}", - "name": "פנה {turn_maneuver} אל {way_name}" - } - }, - "continue": { - "default": { - "default": "המשך {turn_maneuver}", - "name": "המשך {turn_maneuver} אל {way_name}" - }, - "uturn": { - "default": "בצע פניית פרסה", - "name": "בצע פניית פרסה אל {way_name}" - } - }, - "keep": { - "default": { - "default": "המשך {turn_maneuver}", - "name": "המשך {turn_maneuver} אל {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_hu-HU.resources b/ors-engine/src/main/resources/resources/locales/ors_hu-HU.resources index fe8bd33324..4824b07b26 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_hu-HU.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_hu-HU.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "első", - "2": "második", - "3": "harmadik", - "4": "negyedik", - "5": "ötödik", - "6": "hatodik", - "7": "hetedik", - "8": "nyolcadik", - "9": "kilencedik", - "10": "tizedik" - }, - "directions": { - "north": "észak", - "northeast": "északkelet", - "east": "kelet", - "southeast": "délkelet", - "south": "dél", - "southwest": "délnyugat", - "west": "nyugat", - "northwest": "északnyugat" - }, - "turn_maneuvers": { - "left": "balra", - "right": "jobbra", - "sharp_left": "élesen balra", - "sharp_right": "élesen jobbra", - "slight_left": "enyhén balra", - "slight_right": "enyhén jobbra", - "straight": "egyenesen", - "uturn": "vissza" - }, - "actions": { - "arrive": { - "default": { - "default": "Megérkezett az úticéljához", - "name": "Megérkezett: {way_name}" + "instructions": { + "numerals": { + "1": "első", + "2": "második", + "3": "harmadik", + "4": "negyedik", + "5": "ötödik", + "6": "hatodik", + "7": "hetedik", + "8": "nyolcadik", + "9": "kilencedik", + "10": "tizedik" }, - "left": { - "default": "Megérkezett, úticélja a bal oldalon található", - "name": "Megérkezett: {way_name} (a bal oldalon)" + "directions": { + "north": "észak", + "northeast": "északkelet", + "east": "kelet", + "southeast": "délkelet", + "south": "dél", + "southwest": "délnyugat", + "west": "nyugat", + "northwest": "északnyugat" }, - "right": { - "default": "Megérkezett, úticélja a jobb oldalon található", - "name": "Megérkezett: {way_name} (a jobb oldalon)" + "turn_maneuvers": { + "left": "balra", + "right": "jobbra", + "sharp_left": "élesen balra", + "sharp_right": "élesen jobbra", + "slight_left": "enyhén balra", + "slight_right": "enyhén jobbra", + "straight": "egyenesen", + "uturn": "vissza" }, - "straight": { - "default": "Megérkezett, úticélja szemben található", - "name": "Megérkezett: {way_name} (szemben)" + "actions": { + "arrive": { + "default": { + "default": "Megérkezett az úticéljához", + "name": "Megérkezett: {way_name}" + }, + "left": { + "default": "Megérkezett, úticélja a bal oldalon található", + "name": "Megérkezett: {way_name} (a bal oldalon)" + }, + "right": { + "default": "Megérkezett, úticélja a jobb oldalon található", + "name": "Megérkezett: {way_name} (a jobb oldalon)" + }, + "straight": { + "default": "Megérkezett, úticélja szemben található", + "name": "Megérkezett: {way_name} (szemben)" + } + }, + "depart": { + "default": { + "default": "Induljon {direction} felé", + "name": "Induljon {direction} felé ezen: {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Hajtson be a köforgalomba, majd hajtson ki a(z) {exit_number} kijáraton", + "name": "Hajtson be a köforgalomba, majd hajtson ki a(z) {exit_number} kijáraton, ezen: {way_name}" + }, + "default": { + "default": "Hajtson be a köforgalomba", + "name": "Hajtson be a köforgalomba, majd hajtson ki ezen: {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Forduljon be {turn_maneuver}", + "name": "Forduljon be {turn_maneuver} erre: {way_name}" + } + }, + "continue": { + "default": { + "default": "Menjen tovább {turn_maneuver}", + "name": "Menjen tovább {turn_maneuver} ezen: {way_name}" + }, + "uturn": { + "default": "Forduljon meg", + "name": "Forduljon meg, és menjen tovább ezen: {way_name}" + } + }, + "keep": { + "default": { + "default": "Tartson {turn_maneuver}", + "name": "Tartson {turn_maneuver} ezen: {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Induljon {direction} felé", - "name": "Induljon {direction} felé ezen: {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Hajtson be a köforgalomba, majd hajtson ki a(z) {exit_number} kijáraton", - "name": "Hajtson be a köforgalomba, majd hajtson ki a(z) {exit_number} kijáraton, ezen: {way_name}" - }, - "default": { - "default": "Hajtson be a köforgalomba", - "name": "Hajtson be a köforgalomba, majd hajtson ki ezen: {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Forduljon be {turn_maneuver}", - "name": "Forduljon be {turn_maneuver} erre: {way_name}" - } - }, - "continue": { - "default": { - "default": "Menjen tovább {turn_maneuver}", - "name": "Menjen tovább {turn_maneuver} ezen: {way_name}" - }, - "uturn": { - "default": "Forduljon meg", - "name": "Forduljon meg, és menjen tovább ezen: {way_name}" - } - }, - "keep": { - "default": { - "default": "Tartson {turn_maneuver}", - "name": "Tartson {turn_maneuver} ezen: {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_id-ID.resources b/ors-engine/src/main/resources/resources/locales/ors_id-ID.resources index 1b7b561a5a..613e5d283a 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_id-ID.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_id-ID.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "pertama", - "2": "kedua", - "3": "ketiga", - "4": "keempat", - "5": "kelima", - "6": "keenam", - "7": "ketujuh", - "8": "kedelapan", - "9": "kesembilan", - "10": "kesepuluh" - }, - "directions": { - "north": "utara", - "northeast": "timur laut", - "east": "timur", - "southeast": "tenggara", - "south": "selatan", - "southwest": "barat daya", - "west": "barat", - "northwest": "barat laut" - }, - "turn_maneuvers": { - "left": "kiri", - "right": "kanan", - "sharp_left": "kiri tajam", - "sharp_right": "kanan tajam", - "slight_left": "kiri sedikit", - "slight_right": "kanan sedikit", - "straight": "lurus", - "uturn": "putar balik" - }, - "actions": { - "arrive": { - "default": { - "default": "Sampai pada titik tujuan", - "name": "Sampai di {way_name}" + "instructions": { + "numerals": { + "1": "pertama", + "2": "kedua", + "3": "ketiga", + "4": "keempat", + "5": "kelima", + "6": "keenam", + "7": "ketujuh", + "8": "kedelapan", + "9": "kesembilan", + "10": "kesepuluh" }, - "left": { - "default": "Sampai pada titik tujuan, tetap berada di jalur kiri", - "name": "Sampai di {way_name}, tetap berada pada jalur kiri" + "directions": { + "north": "utara", + "northeast": "timur laut", + "east": "timur", + "southeast": "tenggara", + "south": "selatan", + "southwest": "barat daya", + "west": "barat", + "northwest": "barat laut" }, - "right": { - "default": "Sampai pada titik tujuan, tetap berada di jalur kanan", - "name": "Sampai di {way_name}, tetap berada pada jalur kanan" + "turn_maneuvers": { + "left": "kiri", + "right": "kanan", + "sharp_left": "kiri tajam", + "sharp_right": "kanan tajam", + "slight_left": "kiri sedikit", + "slight_right": "kanan sedikit", + "straight": "lurus", + "uturn": "putar balik" }, - "straight": { - "default": "Sampai pada titik tujuan, lurus terus", - "name": "Sampai di {way_name}, lurus terus" + "actions": { + "arrive": { + "default": { + "default": "Sampai pada titik tujuan", + "name": "Sampai di {way_name}" + }, + "left": { + "default": "Sampai pada titik tujuan, tetap berada di jalur kiri", + "name": "Sampai di {way_name}, tetap berada pada jalur kiri" + }, + "right": { + "default": "Sampai pada titik tujuan, tetap berada di jalur kanan", + "name": "Sampai di {way_name}, tetap berada pada jalur kanan" + }, + "straight": { + "default": "Sampai pada titik tujuan, lurus terus", + "name": "Sampai di {way_name}, lurus terus" + } + }, + "depart": { + "default": { + "default": "Ke arah {direction}", + "name": "Menuju ke arah {direction} di {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Masuk pada bundarn dan mengambil jalur {exit_number} untuk keluar", + "name": "Masuk dalam bundaran dan keluar melalui {exit_number} keluar di {way_name}" + }, + "default": { + "default": "Masuk ke bundaran", + "name": "Masuk dalam bundaran {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Belok {turn_maneuver}", + "name": "Belok {turn_maneuver} ke {way_name}" + } + }, + "continue": { + "default": { + "default": "Dilanjutkan {turn_maneuver}", + "name": "Dilanjutkan {turn_maneuver} pada {way_name}" + }, + "uturn": { + "default": "Putar Balik", + "name": "Putar balik pada {way_name}" + } + }, + "keep": { + "default": { + "default": "Tetap berada pada {turn_maneuver}", + "name": "Tetap berada pada {turn_maneuver} di {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Ke arah {direction}", - "name": "Menuju ke arah {direction} di {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Masuk pada bundarn dan mengambil jalur {exit_number} untuk keluar", - "name": "Masuk dalam bundaran dan keluar melalui {exit_number} keluar di {way_name}" - }, - "default": { - "default": "Masuk ke bundaran", - "name": "Masuk dalam bundaran {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Belok {turn_maneuver}", - "name": "Belok {turn_maneuver} ke {way_name}" - } - }, - "continue": { - "default": { - "default": "Dilanjutkan {turn_maneuver}", - "name": "Dilanjutkan {turn_maneuver} pada {way_name}" - }, - "uturn": { - "default": "Putar Balik", - "name": "Putar balik pada {way_name}" - } - }, - "keep": { - "default": { - "default": "Tetap berada pada {turn_maneuver}", - "name": "Tetap berada pada {turn_maneuver} di {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_it-IT.resources b/ors-engine/src/main/resources/resources/locales/ors_it-IT.resources index 17c3a7658c..5e971bddc6 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_it-IT.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_it-IT.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "prima", - "2": "seconda", - "3": "terza", - "4": "quarta", - "5": "quinta", - "6": "sesta", - "7": "settima", - "8": "ottava", - "9": "nona", - "10": "decima" - }, - "directions": { - "north": "Nord", - "northeast": "Nord-Est", - "east": "Est", - "southeast": "Sud-Est", - "south": "Sud", - "southwest": "Sud-Ovest", - "west": "Ovest", - "northwest": "Nord-Ovest" - }, - "turn_maneuvers": { - "left": "a sinistra", - "right": "a destra", - "sharp_left": "svolta sinistra", - "sharp_right": "svolta destra", - "slight_left": "sulla sinistra", - "slight_right": "sulla destra", - "straight": "dritto", - "uturn": "inversione di marcia" - }, - "actions": { - "arrive": { - "default": { - "default": "Arrivo a destinazione", - "name": "Arrivo a {way_name}" + "instructions": { + "numerals": { + "1": "prima", + "2": "seconda", + "3": "terza", + "4": "quarta", + "5": "quinta", + "6": "sesta", + "7": "settima", + "8": "ottava", + "9": "nona", + "10": "decima" }, - "left": { - "default": "Arrivo a destinazione, a sinistra", - "name": "Arrivo a {way_name}, a sinistra" + "directions": { + "north": "Nord", + "northeast": "Nord-Est", + "east": "Est", + "southeast": "Sud-Est", + "south": "Sud", + "southwest": "Sud-Ovest", + "west": "Ovest", + "northwest": "Nord-Ovest" }, - "right": { - "default": "Arrivo a destinazione, sulla destra", - "name": "Arrivo a {way_name}, sulla destra" + "turn_maneuvers": { + "left": "a sinistra", + "right": "a destra", + "sharp_left": "svolta sinistra", + "sharp_right": "svolta destra", + "slight_left": "sulla sinistra", + "slight_right": "sulla destra", + "straight": "dritto", + "uturn": "inversione di marcia" }, - "straight": { - "default": "Arrivo a destinazione, dritto", - "name": "Arrivo a {way_name}, dritto" + "actions": { + "arrive": { + "default": { + "default": "Arrivo a destinazione", + "name": "Arrivo a {way_name}" + }, + "left": { + "default": "Arrivo a destinazione, a sinistra", + "name": "Arrivo a {way_name}, a sinistra" + }, + "right": { + "default": "Arrivo a destinazione, sulla destra", + "name": "Arrivo a {way_name}, sulla destra" + }, + "straight": { + "default": "Arrivo a destinazione, dritto", + "name": "Arrivo a {way_name}, dritto" + } + }, + "depart": { + "default": { + "default": "Avanti {direction}", + "name": "Avanti {direction} su {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Entra nella rotatoria e prendi la {exit_number} uscita", + "name": "Entra nella rotatoria e prendi la {exit_number} uscita su {way_name}" + }, + "default": { + "default": "Entra nella rotatoria", + "name": "Enra nella rotatoria ed esci su {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Gira {turn_maneuver}", + "name": "Gira {turn_maneuver} su {way_name}" + } + }, + "continue": { + "default": { + "default": "Continua {turn_maneuver}", + "name": "Continua {turn_maneuver} su {way_name}" + }, + "uturn": { + "default": "Fai un'inversione a U", + "name": "Fai un'inversione a U su {way_name}" + } + }, + "keep": { + "default": { + "default": "Gira {turn_maneuver}", + "name": "Gira {turn_maneuver} su {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Avanti {direction}", - "name": "Avanti {direction} su {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Entra nella rotatoria e prendi la {exit_number} uscita", - "name": "Entra nella rotatoria e prendi la {exit_number} uscita su {way_name}" - }, - "default": { - "default": "Entra nella rotatoria", - "name": "Enra nella rotatoria ed esci su {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Gira {turn_maneuver}", - "name": "Gira {turn_maneuver} su {way_name}" - } - }, - "continue": { - "default": { - "default": "Continua {turn_maneuver}", - "name": "Continua {turn_maneuver} su {way_name}" - }, - "uturn": { - "default": "Fai un'inversione a U", - "name": "Fai un'inversione a U su {way_name}" - } - }, - "keep": { - "default": { - "default": "Gira {turn_maneuver}", - "name": "Gira {turn_maneuver} su {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_ja-JP.resources b/ors-engine/src/main/resources/resources/locales/ors_ja-JP.resources index 9915ba1d13..cc6c14fcd3 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_ja-JP.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_ja-JP.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1番目", - "2": "2番目", - "3": "3番目", - "4": "4番目", - "5": "5番目", - "6": "6番目", - "7": "7番目", - "8": "8番目", - "9": "9番目", - "10": "10番目" - }, - "directions": { - "north": "北", - "northeast": "北東", - "east": "東", - "southeast": "南東", - "south": "南", - "southwest": "南西", - "west": "西", - "northwest": "北西" - }, - "turn_maneuvers": { - "left": "左", - "right": "右", - "sharp_left": "左急角度", - "sharp_right": "右急角度", - "slight_left": "左方向", - "slight_right": "右方向", - "straight": "直進", - "uturn": "Uターン" - }, - "actions": { - "arrive": { - "default": { - "default": "目的地に到着します", - "name": "{way_name}に到着します" + "instructions": { + "numerals": { + "1": "1番目", + "2": "2番目", + "3": "3番目", + "4": "4番目", + "5": "5番目", + "6": "6番目", + "7": "7番目", + "8": "8番目", + "9": "9番目", + "10": "10番目" }, - "left": { - "default": "左側にある目的地に到着します", - "name": "左側にある{way_name}に到着します" + "directions": { + "north": "北", + "northeast": "北東", + "east": "東", + "southeast": "南東", + "south": "南", + "southwest": "南西", + "west": "西", + "northwest": "北西" }, - "right": { - "default": "右側にある目的地に到着します", - "name": "右側にある{way_name}に到着します" + "turn_maneuvers": { + "left": "左", + "right": "右", + "sharp_left": "左急角度", + "sharp_right": "右急角度", + "slight_left": "左方向", + "slight_right": "右方向", + "straight": "直進", + "uturn": "Uターン" }, - "straight": { - "default": "前方にある目的地に到着します", - "name": "前方にある{way_name}に到着します" + "actions": { + "arrive": { + "default": { + "default": "目的地に到着します", + "name": "{way_name}に到着します" + }, + "left": { + "default": "左側にある目的地に到着します", + "name": "左側にある{way_name}に到着します" + }, + "right": { + "default": "右側にある目的地に到着します", + "name": "右側にある{way_name}に到着します" + }, + "straight": { + "default": "前方にある目的地に到着します", + "name": "前方にある{way_name}に到着します" + } + }, + "depart": { + "default": { + "default": "{direction}に向かいます", + "name": "{way_name}を通って{direction}に向かいます" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "ロータリーに入って{exit_number}番出口を選びます", + "name": "ロータリーに入って{way_name}上の{exit_number}番出口を選びます" + }, + "default": { + "default": "ロータリーに入ります", + "name": "ロータリーに入って{way_name}上へ抜けます" + } + } + }, + "turn": { + "default": { + "default": "{turn_maneuver}へ曲がります", + "name": "{way_name}に向けて{turn_maneuver}へ曲がります" + } + }, + "continue": { + "default": { + "default": "続けて{turn_maneuver}に進みます", + "name": "続けて{way_name}上を{turn_maneuver}に進みます" + }, + "uturn": { + "default": "Uターンします", + "name": "{way_name}に向けてUターンします" + } + }, + "keep": { + "default": { + "default": "そのまま{turn_maneuver}に進みます", + "name": "そのまま{way_name}上を{turn_maneuver}に進みます" + } + }, + "pt": { + "start": { + "default": "{name}に乗車します", + "headsign": "{headsign}行の{name}に乗車します" + }, + "transfer": { + "default": "{name}へ乗り換えます", + "headsign": "{headsign}行の{name}へ乗り換えます" + }, + "end": "{name}で下車します" + } } - }, - "depart": { - "default": { - "default": "{direction}に向かいます", - "name": "{way_name}を通って{direction}に向かいます" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "ロータリーに入って{exit_number}番出口を選びます", - "name": "ロータリーに入って{way_name}上の{exit_number}番出口を選びます" - }, - "default": { - "default": "ロータリーに入ります", - "name": "ロータリーに入って{way_name}上へ抜けます" - } - } - }, - "turn": { - "default": { - "default": "{turn_maneuver}へ曲がります", - "name": "{way_name}に向けて{turn_maneuver}へ曲がります" - } - }, - "continue": { - "default": { - "default": "続けて{turn_maneuver}に進みます", - "name": "続けて{way_name}上を{turn_maneuver}に進みます" - }, - "uturn": { - "default": "Uターンします", - "name": "{way_name}に向けてUターンします" - } - }, - "keep": { - "default": { - "default": "そのまま{turn_maneuver}に進みます", - "name": "そのまま{way_name}上を{turn_maneuver}に進みます" - } - }, - "pt": { - "start": { - "default": "{name}に乗車します", - "headsign": "{headsign}行の{name}に乗車します" - }, - "transfer": { - "default": "{name}へ乗り換えます", - "headsign": "{headsign}行の{name}へ乗り換えます" - }, - "end": "{name}で下車します" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_ne-NP.resources b/ors-engine/src/main/resources/resources/locales/ors_ne-NP.resources index d97374915f..3220fa935e 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_ne-NP.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_ne-NP.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "१", - "2": "२", - "3": "३", - "4": "४", - "5": "५", - "6": "६", - "7": "७", - "8": "८", - "9": "९", - "10": "१०" - }, - "directions": { - "north": "उत्तर", - "northeast": "उत्तर-पूर्व", - "east": "पूर्व", - "southeast": "दक्षिण-पूर्व", - "south": "दक्षिण", - "southwest": "दक्षिण-पश्चिम", - "west": "पश्चिम", - "northwest": "उत्तर-पश्चिम" - }, - "turn_maneuvers": { - "left": "बाँया", - "right": "दाहिने", - "sharp_left": "तिखो बाँया", - "sharp_right": "तिखो दाहिने", - "slight_left": "हल्का बाँया", - "slight_right": "हल्का दाहिने", - "straight": "सिधा", - "uturn": "घुम्ती" - }, - "actions": { - "arrive": { - "default": { - "default": "तपाईंको गन्तव्यमा पुग्नुहोस्", - "name": "{Way_name} मा आइपुग्नुहोस्" + "instructions": { + "numerals": { + "1": "१", + "2": "२", + "3": "३", + "4": "४", + "5": "५", + "6": "६", + "7": "७", + "8": "८", + "9": "९", + "10": "१०" }, - "left": { - "default": "तपाईंको गन्तव्यमा पुग्नुहोस्, बाँयामा", - "name": "{Way_name} मा बायाँ तिर" + "directions": { + "north": "उत्तर", + "northeast": "उत्तर-पूर्व", + "east": "पूर्व", + "southeast": "दक्षिण-पूर्व", + "south": "दक्षिण", + "southwest": "दक्षिण-पश्चिम", + "west": "पश्चिम", + "northwest": "उत्तर-पश्चिम" }, - "right": { - "default": "तपाईंको गन्तव्यमा पुग्नुहोस् दाँयामा", - "name": "दायाँतिर {way_name} मा आइपुग्नुहोस्" + "turn_maneuvers": { + "left": "बाँया", + "right": "दाहिने", + "sharp_left": "तिखो बाँया", + "sharp_right": "तिखो दाहिने", + "slight_left": "हल्का बाँया", + "slight_right": "हल्का दाहिने", + "straight": "सिधा", + "uturn": "घुम्ती" }, - "straight": { - "default": "तपाईंको गन्तव्यमा पुग्नुहोस्, सीधा अगाडी", - "name": "{Way_name} मा जानुहोस्, सीधा अगाडी" + "actions": { + "arrive": { + "default": { + "default": "तपाईंको गन्तव्यमा पुग्नुहोस्", + "name": "{Way_name} मा आइपुग्नुहोस्" + }, + "left": { + "default": "तपाईंको गन्तव्यमा पुग्नुहोस्, बाँयामा", + "name": "{Way_name} मा बायाँ तिर" + }, + "right": { + "default": "तपाईंको गन्तव्यमा पुग्नुहोस् दाँयामा", + "name": "दायाँतिर {way_name} मा आइपुग्नुहोस्" + }, + "straight": { + "default": "तपाईंको गन्तव्यमा पुग्नुहोस्, सीधा अगाडी", + "name": "{Way_name} मा जानुहोस्, सीधा अगाडी" + } + }, + "depart": { + "default": { + "default": "अगाडी {direction}", + "name": "अगाडी {direction} {way_name} मा" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "गोलघुम्ती छिर्नुहोस्, {exit_number} लिनुहोस् र बाहिर निस्कनुहोस्", + "name": "गोलघुम्ती छिर्नुहोस् र {exit_number} लिनुहोस् र {way_name} तिर बाहिर निस्कनुहोस्" + }, + "default": { + "default": "गोलघुम्ती छिर्नुहोस्", + "name": "गोलघुम्ती छिर्नुहोस् र {way_name} तिर बाहिर निस्कनुहोस्" + } + } + }, + "turn": { + "default": { + "default": "घुम्नुहोस् {turn_maneuver}", + "name": "घुम्नुहोस् {turn_maneuver} {way_name} तिर" + } + }, + "continue": { + "default": { + "default": "निरन्तरता दिनु {turn_maneuver}", + "name": "निरन्तरता दिनु {turn_maneuver} {way_name} तिर" + }, + "uturn": { + "default": "U मोड लिनुहोस्", + "name": "{way_name} तिर U मोड लिनुहोस्" + } + }, + "keep": { + "default": { + "default": "घुम्नुहोस् {turn_maneuver}", + "name": "घुम्नुहोस् {turn_maneuver} {way_name} तिर" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "अगाडी {direction}", - "name": "अगाडी {direction} {way_name} मा" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "गोलघुम्ती छिर्नुहोस्, {exit_number} लिनुहोस् र बाहिर निस्कनुहोस्", - "name": "गोलघुम्ती छिर्नुहोस् र {exit_number} लिनुहोस् र {way_name} तिर बाहिर निस्कनुहोस्" - }, - "default": { - "default": "गोलघुम्ती छिर्नुहोस्", - "name": "गोलघुम्ती छिर्नुहोस् र {way_name} तिर बाहिर निस्कनुहोस्" - } - } - }, - "turn": { - "default": { - "default": "घुम्नुहोस् {turn_maneuver}", - "name": "घुम्नुहोस् {turn_maneuver} {way_name} तिर" - } - }, - "continue": { - "default": { - "default": "निरन्तरता दिनु {turn_maneuver}", - "name": "निरन्तरता दिनु {turn_maneuver} {way_name} तिर" - }, - "uturn": { - "default": "U मोड लिनुहोस्", - "name": "{way_name} तिर U मोड लिनुहोस्" - } - }, - "keep": { - "default": { - "default": "घुम्नुहोस् {turn_maneuver}", - "name": "घुम्नुहोस् {turn_maneuver} {way_name} तिर" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_nl-NL.resources b/ors-engine/src/main/resources/resources/locales/ors_nl-NL.resources index e031efd73e..cfc0c3c7d2 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_nl-NL.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_nl-NL.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1e", - "2": "2e", - "3": "3e", - "4": "4e", - "5": "5e", - "6": "6e", - "7": "7e", - "8": "8e", - "9": "9e", - "10": "10e" - }, - "directions": { - "north": "noord", - "northeast": "noordoost", - "east": "oost", - "southeast": "zuidoost", - "south": "zuid", - "southwest": "zuidwest", - "west": "west", - "northwest": "noordwest" - }, - "turn_maneuvers": { - "left": "links", - "right": "rechts", - "sharp_left": "scherp links", - "sharp_right": "scherp rechts", - "slight_left": "flauw links", - "slight_right": "flauw rechts", - "straight": "rechtdoor", - "uturn": "U-bocht" - }, - "actions": { - "arrive": { - "default": { - "default": "Aankomst op uw bestemming", - "name": "Aankomen op {way_name}" + "instructions": { + "numerals": { + "1": "1e", + "2": "2e", + "3": "3e", + "4": "4e", + "5": "5e", + "6": "6e", + "7": "7e", + "8": "8e", + "9": "9e", + "10": "10e" }, - "left": { - "default": "Aankomst op uw bestemming, links", - "name": "Aankomen op {way_name}, links" + "directions": { + "north": "noord", + "northeast": "noordoost", + "east": "oost", + "southeast": "zuidoost", + "south": "zuid", + "southwest": "zuidwest", + "west": "west", + "northwest": "noordwest" }, - "right": { - "default": "Aankomst op uw bestemming, aan de rechterkant", - "name": "Aankomen op {way_name}, rechts" + "turn_maneuvers": { + "left": "links", + "right": "rechts", + "sharp_left": "scherp links", + "sharp_right": "scherp rechts", + "slight_left": "flauw links", + "slight_right": "flauw rechts", + "straight": "rechtdoor", + "uturn": "U-bocht" }, - "straight": { - "default": "Aankomst op uw bestemming, rechtdoor", - "name": "Aankomen op {way_name}, rechtdoor" + "actions": { + "arrive": { + "default": { + "default": "Aankomst op uw bestemming", + "name": "Aankomen op {way_name}" + }, + "left": { + "default": "Aankomst op uw bestemming, links", + "name": "Aankomen op {way_name}, links" + }, + "right": { + "default": "Aankomst op uw bestemming, aan de rechterkant", + "name": "Aankomen op {way_name}, rechts" + }, + "straight": { + "default": "Aankomst op uw bestemming, rechtdoor", + "name": "Aankomen op {way_name}, rechtdoor" + } + }, + "depart": { + "default": { + "default": "Richting {direction}", + "name": "Richting {direction} op {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Ga de rotonde op en neem de {exit_number} afslag", + "name": "Ga de rotonde op en neem de {exit_number} afslag richting {way_name}" + }, + "default": { + "default": "Ga de rotonde op", + "name": "Ga de rotonde op en neem de afslag richting {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Keer om {turn_maneuver}", + "name": "Keer om {turn_maneuver} richting {way_name}" + } + }, + "continue": { + "default": { + "default": "Doorgaan {turn_maneuver}", + "name": "Doorgaan {turn_maneuver} richting {way_name}" + }, + "uturn": { + "default": "Rechtsomkeerd", + "name": "Rechtsomkeerd richting {way_name}" + } + }, + "keep": { + "default": { + "default": "Keer om {turn_maneuver}", + "name": "Keer om {turn_maneuver} richting {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Richting {direction}", - "name": "Richting {direction} op {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Ga de rotonde op en neem de {exit_number} afslag", - "name": "Ga de rotonde op en neem de {exit_number} afslag richting {way_name}" - }, - "default": { - "default": "Ga de rotonde op", - "name": "Ga de rotonde op en neem de afslag richting {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Keer om {turn_maneuver}", - "name": "Keer om {turn_maneuver} richting {way_name}" - } - }, - "continue": { - "default": { - "default": "Doorgaan {turn_maneuver}", - "name": "Doorgaan {turn_maneuver} richting {way_name}" - }, - "uturn": { - "default": "Rechtsomkeerd", - "name": "Rechtsomkeerd richting {way_name}" - } - }, - "keep": { - "default": { - "default": "Keer om {turn_maneuver}", - "name": "Keer om {turn_maneuver} richting {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_pl-PL.resources b/ors-engine/src/main/resources/resources/locales/ors_pl-PL.resources index a5d6616d30..d17a8357fd 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_pl-PL.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_pl-PL.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1.", - "2": "2.", - "3": "3.", - "4": "4.", - "5": "5.", - "6": "6.", - "7": "7.", - "8": "8.", - "9": "9.", - "10": "10." - }, - "directions": { - "north": "północ", - "northeast": "północny wschód", - "east": "wschód", - "southeast": "południowy wschód", - "south": "południe", - "southwest": "południowy zachód", - "west": "zachód", - "northwest": "północny zachód" - }, - "turn_maneuvers": { - "left": "w lewo", - "right": "w prawo", - "sharp_left": "ostro w lewo", - "sharp_right": "ostro w prawo", - "slight_left": "łagodnie w lewo", - "slight_right": "łagodnie w prawo", - "straight": "prosto", - "uturn": "zawróć" - }, - "actions": { - "arrive": { - "default": { - "default": "Dojeżdżasz do celu", - "name": "Dojeżdżasz do {way_name}" + "instructions": { + "numerals": { + "1": "1.", + "2": "2.", + "3": "3.", + "4": "4.", + "5": "5.", + "6": "6.", + "7": "7.", + "8": "8.", + "9": "9.", + "10": "10." }, - "left": { - "default": "Dotrzesz do celu po lewej stronie", - "name": "Dojeżdżasz do {way_name} po lewej stronie" + "directions": { + "north": "północ", + "northeast": "północny wschód", + "east": "wschód", + "southeast": "południowy wschód", + "south": "południe", + "southwest": "południowy zachód", + "west": "zachód", + "northwest": "północny zachód" }, - "right": { - "default": "Dotrzesz do celu po prawej stronie", - "name": "Dojeżdżasz do {way_name} po prawej stronie" + "turn_maneuvers": { + "left": "w lewo", + "right": "w prawo", + "sharp_left": "ostro w lewo", + "sharp_right": "ostro w prawo", + "slight_left": "łagodnie w lewo", + "slight_right": "łagodnie w prawo", + "straight": "prosto", + "uturn": "zawróć" }, - "straight": { - "default": "Dojeżdżasz do celu prosto przed siebie", - "name": "Dojeżdżasz do {way_name} na wprost" + "actions": { + "arrive": { + "default": { + "default": "Dojeżdżasz do celu", + "name": "Dojeżdżasz do {way_name}" + }, + "left": { + "default": "Dotrzesz do celu po lewej stronie", + "name": "Dojeżdżasz do {way_name} po lewej stronie" + }, + "right": { + "default": "Dotrzesz do celu po prawej stronie", + "name": "Dojeżdżasz do {way_name} po prawej stronie" + }, + "straight": { + "default": "Dojeżdżasz do celu prosto przed siebie", + "name": "Dojeżdżasz do {way_name} na wprost" + } + }, + "depart": { + "default": { + "default": "Kieruj się na {direction}", + "name": "Kieruj się na {direction} na {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Na rondzie zjedź {exit_number} zjazdem", + "name": "Na rondzie zjedź {exit_number} zjazdem na {way_name}" + }, + "default": { + "default": "Wjedź na rondo", + "name": "Na rondzie zjedź na {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Skręć {turn_maneuver}", + "name": "Skręć {turn_maneuver} na {way_name}" + } + }, + "continue": { + "default": { + "default": "Kontynuuj {turn_maneuver}", + "name": "Kontynuuj {turn_maneuver} na {way_name}" + }, + "uturn": { + "default": "Zawróć", + "name": "Zawróć na {way_name}" + } + }, + "keep": { + "default": { + "default": "Kieruj się {turn_maneuver}", + "name": "Kieruj się {turn_maneuver} na {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Kieruj się na {direction}", - "name": "Kieruj się na {direction} na {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Na rondzie zjedź {exit_number} zjazdem", - "name": "Na rondzie zjedź {exit_number} zjazdem na {way_name}" - }, - "default": { - "default": "Wjedź na rondo", - "name": "Na rondzie zjedź na {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Skręć {turn_maneuver}", - "name": "Skręć {turn_maneuver} na {way_name}" - } - }, - "continue": { - "default": { - "default": "Kontynuuj {turn_maneuver}", - "name": "Kontynuuj {turn_maneuver} na {way_name}" - }, - "uturn": { - "default": "Zawróć", - "name": "Zawróć na {way_name}" - } - }, - "keep": { - "default": { - "default": "Kieruj się {turn_maneuver}", - "name": "Kieruj się {turn_maneuver} na {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_pt-PT.resources b/ors-engine/src/main/resources/resources/locales/ors_pt-PT.resources index cddc0bae86..da4f5d89f5 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_pt-PT.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_pt-PT.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1ª", - "2": "2ª", - "3": "3ª", - "4": "4ª", - "5": "5ª", - "6": "6ª", - "7": "7ª", - "8": "8ª", - "9": "9ª", - "10": "10ª" - }, - "directions": { - "north": "norte", - "northeast": "nordeste", - "east": "este", - "southeast": "sudeste", - "south": "sul", - "southwest": "sudoeste", - "west": "oeste", - "northwest": "nordoeste" - }, - "turn_maneuvers": { - "left": "à esquerda", - "right": "à direita", - "sharp_left": "bastante à esquerda", - "sharp_right": "bastante à direita", - "slight_left": "ligeiramente à esquerda", - "slight_right": "ligeiramente à direita", - "straight": "em frente", - "uturn": "no sentido inverso" - }, - "actions": { - "arrive": { - "default": { - "default": "Chegar ao seu destino", - "name": "Chegar a {way_name}" + "instructions": { + "numerals": { + "1": "1ª", + "2": "2ª", + "3": "3ª", + "4": "4ª", + "5": "5ª", + "6": "6ª", + "7": "7ª", + "8": "8ª", + "9": "9ª", + "10": "10ª" }, - "left": { - "default": "Chegar ao seu destino, à esquerda", - "name": "Chegar a {way_name}, à esquerda" + "directions": { + "north": "norte", + "northeast": "nordeste", + "east": "este", + "southeast": "sudeste", + "south": "sul", + "southwest": "sudoeste", + "west": "oeste", + "northwest": "nordoeste" }, - "right": { - "default": "Chegar ao seu destino, à direita", - "name": "Chegar a {way_name}, à direita" + "turn_maneuvers": { + "left": "à esquerda", + "right": "à direita", + "sharp_left": "bastante à esquerda", + "sharp_right": "bastante à direita", + "slight_left": "ligeiramente à esquerda", + "slight_right": "ligeiramente à direita", + "straight": "em frente", + "uturn": "no sentido inverso" }, - "straight": { - "default": "Chegar ao seu destino, em frente", - "name": "Chegar a {way_name}, em frente" + "actions": { + "arrive": { + "default": { + "default": "Chegar ao seu destino", + "name": "Chegar a {way_name}" + }, + "left": { + "default": "Chegar ao seu destino, à esquerda", + "name": "Chegar a {way_name}, à esquerda" + }, + "right": { + "default": "Chegar ao seu destino, à direita", + "name": "Chegar a {way_name}, à direita" + }, + "straight": { + "default": "Chegar ao seu destino, em frente", + "name": "Chegar a {way_name}, em frente" + } + }, + "depart": { + "default": { + "default": "Siga para {direction}", + "name": "Siga para {direction} em direção a {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Entre na rotunda e saia na {exit_number} saída", + "name": "Entre na rotunda e saia na {exit_number} saída em direção a {way_name}" + }, + "default": { + "default": "Entre na rotunda", + "name": "Entre na rotunda e saia em direção a {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Vire {turn_maneuver}", + "name": "Vire {turn_maneuver} em direção a {way_name}" + } + }, + "continue": { + "default": { + "default": "Continuar {turn_maneuver}", + "name": "Continue {turn_maneuver} em direção a {way_name}" + }, + "uturn": { + "default": "Faça inversão de marcha", + "name": "Faça inversão de marcha em direção a {way_name}" + } + }, + "keep": { + "default": { + "default": "Vire {turn_maneuver}", + "name": "Vire {turn_maneuver} em direção a {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Siga para {direction}", - "name": "Siga para {direction} em direção a {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Entre na rotunda e saia na {exit_number} saída", - "name": "Entre na rotunda e saia na {exit_number} saída em direção a {way_name}" - }, - "default": { - "default": "Entre na rotunda", - "name": "Entre na rotunda e saia em direção a {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Vire {turn_maneuver}", - "name": "Vire {turn_maneuver} em direção a {way_name}" - } - }, - "continue": { - "default": { - "default": "Continuar {turn_maneuver}", - "name": "Continue {turn_maneuver} em direção a {way_name}" - }, - "uturn": { - "default": "Faça inversão de marcha", - "name": "Faça inversão de marcha em direção a {way_name}" - } - }, - "keep": { - "default": { - "default": "Vire {turn_maneuver}", - "name": "Vire {turn_maneuver} em direção a {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_ro-RO.resources b/ors-engine/src/main/resources/resources/locales/ors_ro-RO.resources index 2f6ea003be..abdcc77dd5 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_ro-RO.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_ro-RO.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "primul", - "2": "al doilea", - "3": "al treilea", - "4": "al patrulea", - "5": "al cincilea", - "6": "al șaselea", - "7": "al șaptelea", - "8": "al optulea", - "9": "al nouălea", - "10": "al zecelea" - }, - "directions": { - "north": "nord", - "northeast": "nord-est", - "east": "est", - "southeast": "sud-est", - "south": "sud", - "southwest": "sud-vest", - "west": "vest", - "northwest": "nord-vest" - }, - "turn_maneuvers": { - "left": "stânga", - "right": "dreapta", - "sharp_left": "stânga brusc", - "sharp_right": "dreapta brusc", - "slight_left": "ușor stânga", - "slight_right": "ușor dreapta", - "straight": "drept înainte", - "uturn": "Întoarcerea în U" - }, - "actions": { - "arrive": { - "default": { - "default": "Ajungeți la destinație", - "name": "Ajungeți la {way_name}" + "instructions": { + "numerals": { + "1": "primul", + "2": "al doilea", + "3": "al treilea", + "4": "al patrulea", + "5": "al cincilea", + "6": "al șaselea", + "7": "al șaptelea", + "8": "al optulea", + "9": "al nouălea", + "10": "al zecelea" }, - "left": { - "default": "Ajungeți la destinație, pe stânga", - "name": "Ajungeți la {way_name}, pe stânga" + "directions": { + "north": "nord", + "northeast": "nord-est", + "east": "est", + "southeast": "sud-est", + "south": "sud", + "southwest": "sud-vest", + "west": "vest", + "northwest": "nord-vest" }, - "right": { - "default": "Ajungeți la destinație, pe dreapta", - "name": "Ajungeți la {way_name}, pe dreapta" + "turn_maneuvers": { + "left": "stânga", + "right": "dreapta", + "sharp_left": "stânga brusc", + "sharp_right": "dreapta brusc", + "slight_left": "ușor stânga", + "slight_right": "ușor dreapta", + "straight": "drept înainte", + "uturn": "Întoarcerea în U" }, - "straight": { - "default": "Ajungeți la destinație, drept înainte", - "name": "Ajungeți la {way_name}, drept înainte" + "actions": { + "arrive": { + "default": { + "default": "Ajungeți la destinație", + "name": "Ajungeți la {way_name}" + }, + "left": { + "default": "Ajungeți la destinație, pe stânga", + "name": "Ajungeți la {way_name}, pe stânga" + }, + "right": { + "default": "Ajungeți la destinație, pe dreapta", + "name": "Ajungeți la {way_name}, pe dreapta" + }, + "straight": { + "default": "Ajungeți la destinație, drept înainte", + "name": "Ajungeți la {way_name}, drept înainte" + } + }, + "depart": { + "default": { + "default": "Direcția {direcția}", + "name": "Continuați în {direction} pe {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Intrați în sensul giratoriu și luați ieșirea {exit_number}", + "name": "Intrați în sensul giratoriu și luați ieșirea {exit_number} pe {way_name}" + }, + "default": { + "default": "Intrați în sensul giratoriu", + "name": "Intrați în sensul giratoriu și ieșiți pe {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Întoarceți {turn_maneuver}", + "name": "Întoarceți {turn_maneuver} pe {way_name}" + } + }, + "continue": { + "default": { + "default": "Continuați {turn_maneuver}", + "name": "Continuați {turn_maneuver} pe {way_name}" + }, + "uturn": { + "default": "Efectuați o întoarcere în U", + "name": "Întoarceți în U pe {way_name}" + } + }, + "keep": { + "default": { + "default": "Țineți {turn_maneuver}", + "name": "Țineți {turn_maneuver} pe {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Direcția {direcția}", - "name": "Continuați în {direction} pe {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Intrați în sensul giratoriu și luați ieșirea {exit_number}", - "name": "Intrați în sensul giratoriu și luați ieșirea {exit_number} pe {way_name}" - }, - "default": { - "default": "Intrați în sensul giratoriu", - "name": "Intrați în sensul giratoriu și ieșiți pe {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Întoarceți {turn_maneuver}", - "name": "Întoarceți {turn_maneuver} pe {way_name}" - } - }, - "continue": { - "default": { - "default": "Continuați {turn_maneuver}", - "name": "Continuați {turn_maneuver} pe {way_name}" - }, - "uturn": { - "default": "Efectuați o întoarcere în U", - "name": "Întoarceți în U pe {way_name}" - } - }, - "keep": { - "default": { - "default": "Țineți {turn_maneuver}", - "name": "Țineți {turn_maneuver} pe {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_ru-RU.resources b/ors-engine/src/main/resources/resources/locales/ors_ru-RU.resources index 106dbed65c..ac3b4575ca 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_ru-RU.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_ru-RU.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1-й", - "2": "2-й", - "3": "3-й", - "4": "4-й", - "5": "5-й", - "6": "6-й", - "7": "7-й", - "8": "8-й", - "9": "9-й", - "10": "10-й" - }, - "directions": { - "north": "север", - "northeast": "северо-восток", - "east": "восток", - "southeast": "юго-восток", - "south": "юг", - "southwest": "юго-запад", - "west": "запад", - "northwest": "северо-запад" - }, - "turn_maneuvers": { - "left": "налево", - "right": "направо", - "sharp_left": "резко налево", - "sharp_right": "резко направо", - "slight_left": "плавно налево", - "slight_right": "плавно направо", - "straight": "прямо", - "uturn": "разворот" - }, - "actions": { - "arrive": { - "default": { - "default": "Прибытие в пункт назначения", - "name": "Прибываете на {way_name}" + "instructions": { + "numerals": { + "1": "1-й", + "2": "2-й", + "3": "3-й", + "4": "4-й", + "5": "5-й", + "6": "6-й", + "7": "7-й", + "8": "8-й", + "9": "9-й", + "10": "10-й" }, - "left": { - "default": "Прибытие в пункт назначения (слева)", - "name": "Прибываете на {way_name} (слева)" + "directions": { + "north": "север", + "northeast": "северо-восток", + "east": "восток", + "southeast": "юго-восток", + "south": "юг", + "southwest": "юго-запад", + "west": "запад", + "northwest": "северо-запад" }, - "right": { - "default": "Прибытие в пункт назначения (справа)", - "name": "Прибываете на {way_name} (справа)" + "turn_maneuvers": { + "left": "налево", + "right": "направо", + "sharp_left": "резко налево", + "sharp_right": "резко направо", + "slight_left": "плавно налево", + "slight_right": "плавно направо", + "straight": "прямо", + "uturn": "разворот" }, - "straight": { - "default": "Прибытие в пункт назначения (прямо)", - "name": "Прибываете на {way_name} (прямо)" + "actions": { + "arrive": { + "default": { + "default": "Прибытие в пункт назначения", + "name": "Прибываете на {way_name}" + }, + "left": { + "default": "Прибытие в пункт назначения (слева)", + "name": "Прибываете на {way_name} (слева)" + }, + "right": { + "default": "Прибытие в пункт назначения (справа)", + "name": "Прибываете на {way_name} (справа)" + }, + "straight": { + "default": "Прибытие в пункт назначения (прямо)", + "name": "Прибываете на {way_name} (прямо)" + } + }, + "depart": { + "default": { + "default": "Направляйтесь на {direction}", + "name": "Направляйтесь на {direction} по {way_name}" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Въезжайте на кольцо, затем выбирете {exit_number} съезд", + "name": "Въезжайте на кольцо, затем выбирете {exit_number} съезд на {way_name}" + }, + "default": { + "default": "Въезжайте на кольцо", + "name": "Въезжайте на кольцо на {way_name}" + } + } + }, + "turn": { + "default": { + "default": "Поверните {turn_maneuver}", + "name": "Поверните {turn_maneuver} на {way_name}" + } + }, + "continue": { + "default": { + "default": "Следуйте {turn_maneuver}", + "name": "Следуйте {turn_maneuver} по {way_name}" + }, + "uturn": { + "default": "Произведите разворот", + "name": "Произведите разворот на {way_name}" + } + }, + "keep": { + "default": { + "default": "Поверните {turn_maneuver}", + "name": "Поверните {turn_maneuver} на {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "Направляйтесь на {direction}", - "name": "Направляйтесь на {direction} по {way_name}" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Въезжайте на кольцо, затем выбирете {exit_number} съезд", - "name": "Въезжайте на кольцо, затем выбирете {exit_number} съезд на {way_name}" - }, - "default": { - "default": "Въезжайте на кольцо", - "name": "Въезжайте на кольцо на {way_name}" - } - } - }, - "turn": { - "default": { - "default": "Поверните {turn_maneuver}", - "name": "Поверните {turn_maneuver} на {way_name}" - } - }, - "continue": { - "default": { - "default": "Следуйте {turn_maneuver}", - "name": "Следуйте {turn_maneuver} по {way_name}" - }, - "uturn": { - "default": "Произведите разворот", - "name": "Произведите разворот на {way_name}" - } - }, - "keep": { - "default": { - "default": "Поверните {turn_maneuver}", - "name": "Поверните {turn_maneuver} на {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_tr-TR.resources b/ors-engine/src/main/resources/resources/locales/ors_tr-TR.resources index 31e8741d11..0d58204154 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_tr-TR.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_tr-TR.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "1.", - "2": "2.", - "3": "3.", - "4": "4.", - "5": "5.", - "6": "6.", - "7": "7.", - "8": "8.", - "9": "9.", - "10": "10." - }, - "directions": { - "north": "kuzey", - "northeast": "kuzeydoğu", - "east": "doğu", - "southeast": "güneydoğu", - "south": "güney", - "southwest": "güneydoğu", - "west": "batı", - "northwest": "kuzeydoğu" - }, - "turn_maneuvers": { - "left": "sol", - "right": "sağ", - "sharp_left": "tam sol", - "sharp_right": "tam sağ", - "slight_left": "hafifçe sol", - "slight_right": "hafifçe sağ", - "straight": "düz şekilde", - "uturn": "U dönüşü" - }, - "actions": { - "arrive": { - "default": { - "default": "Varış noktanıza ulaştınız", - "name": "{way_name} noktasına ulaştınız" + "instructions": { + "numerals": { + "1": "1.", + "2": "2.", + "3": "3.", + "4": "4.", + "5": "5.", + "6": "6.", + "7": "7.", + "8": "8.", + "9": "9.", + "10": "10." }, - "left": { - "default": "Varış noktanıza ulaştınız, sol tarafınızda", - "name": "{way_name} noktasına ulaştınız, sol tarafınızda" + "directions": { + "north": "kuzey", + "northeast": "kuzeydoğu", + "east": "doğu", + "southeast": "güneydoğu", + "south": "güney", + "southwest": "güneydoğu", + "west": "batı", + "northwest": "kuzeydoğu" }, - "right": { - "default": "Varış noktanıza ulaştınız, sağ tarafınızd", - "name": "{way_name} noktasına ulaştınız, sağ tarafınızda" + "turn_maneuvers": { + "left": "sol", + "right": "sağ", + "sharp_left": "tam sol", + "sharp_right": "tam sağ", + "slight_left": "hafifçe sol", + "slight_right": "hafifçe sağ", + "straight": "düz şekilde", + "uturn": "U dönüşü" }, - "straight": { - "default": "Varış noktanıza ulaştınız, tam karşınızda", - "name": "{way_name} noktasına ulaştınız, tam karşınızda" + "actions": { + "arrive": { + "default": { + "default": "Varış noktanıza ulaştınız", + "name": "{way_name} noktasına ulaştınız" + }, + "left": { + "default": "Varış noktanıza ulaştınız, sol tarafınızda", + "name": "{way_name} noktasına ulaştınız, sol tarafınızda" + }, + "right": { + "default": "Varış noktanıza ulaştınız, sağ tarafınızd", + "name": "{way_name} noktasına ulaştınız, sağ tarafınızda" + }, + "straight": { + "default": "Varış noktanıza ulaştınız, tam karşınızda", + "name": "{way_name} noktasına ulaştınız, tam karşınızda" + } + }, + "depart": { + "default": { + "default": "{direction} yönüne ilrleyin", + "name": "{way_name} üzerinde {direction} tarafına ilerleyin" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "Döner kavşağa girin ve {exit_number} çıkışından ilerleyin", + "name": "Döner kavşağa girin ve {way_name} tarafına doğru {exit_number} çıkışından ilerleyin" + }, + "default": { + "default": "Döner kavşağa girin", + "name": "Döner kavşağa girin {way_name} tarafına doğru çıkın" + } + } + }, + "turn": { + "default": { + "default": "{turn_maneuver}a dönün", + "name": "{way_name} tarafına doğru {turn_maneuver}a dönün" + } + }, + "continue": { + "default": { + "default": "{turn_maneuver} tarafta kalın", + "name": "{way_name} konumuna doğru {turn_maneuver}da kalın" + }, + "uturn": { + "default": "U Dönüşü yapın", + "name": "{way_name} tarafına doğru U Dönüşü yapın" + } + }, + "keep": { + "default": { + "default": "{turn_maneuver}da kalın", + "name": "{way_name} tarafına doğru {turn_maneuver}da kalın" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "{direction} yönüne ilrleyin", - "name": "{way_name} üzerinde {direction} tarafına ilerleyin" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "Döner kavşağa girin ve {exit_number} çıkışından ilerleyin", - "name": "Döner kavşağa girin ve {way_name} tarafına doğru {exit_number} çıkışından ilerleyin" - }, - "default": { - "default": "Döner kavşağa girin", - "name": "Döner kavşağa girin {way_name} tarafına doğru çıkın" - } - } - }, - "turn": { - "default": { - "default": "{turn_maneuver}a dönün", - "name": "{way_name} tarafına doğru {turn_maneuver}a dönün" - } - }, - "continue": { - "default": { - "default": "{turn_maneuver} tarafta kalın", - "name": "{way_name} konumuna doğru {turn_maneuver}da kalın" - }, - "uturn": { - "default": "U Dönüşü yapın", - "name": "{way_name} tarafına doğru U Dönüşü yapın" - } - }, - "keep": { - "default": { - "default": "{turn_maneuver}da kalın", - "name": "{way_name} tarafına doğru {turn_maneuver}da kalın" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/locales/ors_zh-CN.resources b/ors-engine/src/main/resources/resources/locales/ors_zh-CN.resources index 781360e46b..c08c56b62b 100644 --- a/ors-engine/src/main/resources/resources/locales/ors_zh-CN.resources +++ b/ors-engine/src/main/resources/resources/locales/ors_zh-CN.resources @@ -1,107 +1,107 @@ { - "instructions": { - "numerals": { - "1": "第1", - "2": "第2", - "3": "第3", - "4": "第4", - "5": "第5", - "6": "第6", - "7": "第7", - "8": "第8", - "9": "第9", - "10": "第10" - }, - "directions": { - "north": "北", - "northeast": "东北", - "east": "东", - "southeast": "东南", - "south": "南", - "southwest": "西南", - "west": "西", - "northwest": "西北" - }, - "turn_maneuvers": { - "left": "向左转", - "right": "向右转", - "sharp_left": "向左急转", - "sharp_right": "向右急转", - "slight_left": "稍向左转", - "slight_right": "稍向右转", - "straight": "直行", - "uturn": "掉头" - }, - "actions": { - "arrive": { - "default": { - "default": "到达目的地", - "name": "到达 {way_name}" + "instructions": { + "numerals": { + "1": "第1", + "2": "第2", + "3": "第3", + "4": "第4", + "5": "第5", + "6": "第6", + "7": "第7", + "8": "第8", + "9": "第9", + "10": "第10" }, - "left": { - "default": "到达你的目的地, 在左边", - "name": "到达 {way_name}, 在左侧" + "directions": { + "north": "北", + "northeast": "东北", + "east": "东", + "southeast": "东南", + "south": "南", + "southwest": "西南", + "west": "西", + "northwest": "西北" }, - "right": { - "default": "到达你的目的地, 在右边", - "name": "到达 {way_name}, 在右侧" + "turn_maneuvers": { + "left": "向左转", + "right": "向右转", + "sharp_left": "向左急转", + "sharp_right": "向右急转", + "slight_left": "稍向左转", + "slight_right": "稍向右转", + "straight": "直行", + "uturn": "掉头" }, - "straight": { - "default": "到达目的地, 笔直向前", - "name": "到达 {way_name}, 直接向前" + "actions": { + "arrive": { + "default": { + "default": "到达目的地", + "name": "到达 {way_name}" + }, + "left": { + "default": "到达你的目的地, 在左边", + "name": "到达 {way_name}, 在左侧" + }, + "right": { + "default": "到达你的目的地, 在右边", + "name": "到达 {way_name}, 在右侧" + }, + "straight": { + "default": "到达目的地, 笔直向前", + "name": "到达 {way_name}, 直接向前" + } + }, + "depart": { + "default": { + "default": "向 {direction} 前进", + "name": "沿 {way_name} 向 {direction} 前进" + } + }, + "roundabout": { + "default": { + "exit": { + "default": "进入环岛后在 {exit_number} 出口离开环岛", + "name": "进入环岛后在 {exit_number} 出口离开后进入 {way_name}" + }, + "default": { + "default": "进入环岛", + "name": "进入并通过环岛后进入 {way_name}" + } + } + }, + "turn": { + "default": { + "default": "{turn_maneuver}", + "name": "{turn_maneuver} 进入 {way_name}" + } + }, + "continue": { + "default": { + "default": "继续 {turn_maneuver}", + "name": "继续 {turn_maneuver} 进入 {way_name}" + }, + "uturn": { + "default": "前方掉头", + "name": "前方掉头后进入 {way_name}" + } + }, + "keep": { + "default": { + "default": "{turn_maneuver}", + "name": "{turn_maneuver} 进入 {way_name}" + } + }, + "pt": { + "start": { + "default": "Enter {name}", + "headsign": "Enter {name} headed for {headsign}" + }, + "transfer": { + "default": "Change to {name}", + "headsign": "Change to {name} headed for {headsign}" + }, + "end": "Exit to {name}" + } } - }, - "depart": { - "default": { - "default": "向 {direction} 前进", - "name": "沿 {way_name} 向 {direction} 前进" - } - }, - "roundabout": { - "default": { - "exit": { - "default": "进入环岛后在 {exit_number} 出口离开环岛", - "name": "进入环岛后在 {exit_number} 出口离开后进入 {way_name}" - }, - "default": { - "default": "进入环岛", - "name": "进入并通过环岛后进入 {way_name}" - } - } - }, - "turn": { - "default": { - "default": "{turn_maneuver}", - "name": "{turn_maneuver} 进入 {way_name}" - } - }, - "continue": { - "default": { - "default": "继续 {turn_maneuver}", - "name": "继续 {turn_maneuver} 进入 {way_name}" - }, - "uturn": { - "default": "前方掉头", - "name": "前方掉头后进入 {way_name}" - } - }, - "keep": { - "default": { - "default": "{turn_maneuver}", - "name": "{turn_maneuver} 进入 {way_name}" - } - }, - "pt": { - "start": { - "default": "Enter {name}", - "headsign": "Enter {name} headed for {headsign}" - }, - "transfer": { - "default": "Change to {name}", - "headsign": "Change to {name} headed for {headsign}" - }, - "end": "Exit to {name}" - } } - } } diff --git a/ors-engine/src/main/resources/resources/services/isochrones/eurostat/example_query.sql b/ors-engine/src/main/resources/resources/services/isochrones/eurostat/example_query.sql index bb6bd1eac1..8432a035b3 100644 --- a/ors-engine/src/main/resources/resources/services/isochrones/eurostat/example_query.sql +++ b/ors-engine/src/main/resources/resources/services/isochrones/eurostat/example_query.sql @@ -1,12 +1,11 @@ -SELECT Round(SUM(c.ratio * c.%%column_name%%)) -FROM ( - SELECT St_area(St_intersection(a.geog,poly)) / St_area(a.geog) ratio, - a.* - FROM geostat_grd_2016_ageclasses_nuts a, - %%wkb_geom%% - WHERE a.gid IN - ( - SELECT a.gid - FROM geostat_grd_2016_ageclasses_nuts a, - %%wkb_geom%% - WHERE st_intersects (a.geog, poly))) AS c; +SELECT Round(SUM(c.ratio * c.%%column_name%%)) +FROM (SELECT St_area(St_intersection(a.geog, poly)) / St_area(a.geog) ratio, + a.* + FROM geostat_grd_2016_ageclasses_nuts a, %%wkb_geom%% + WHERE a.gid IN + ( + SELECT a.gid + FROM geostat_grd_2016_ageclasses_nuts a + , %%wkb_geom%% + WHERE st_intersects (a.geog + , poly))) AS c; diff --git a/ors-engine/src/main/resources/resources/services/routing/speed_limits/bike.json b/ors-engine/src/main/resources/resources/services/routing/speed_limits/bike.json index 42493c14a8..af152a46fa 100644 --- a/ors-engine/src/main/resources/resources/services/routing/speed_limits/bike.json +++ b/ors-engine/src/main/resources/resources/services/routing/speed_limits/bike.json @@ -1,66 +1,63 @@ { - "default": - { - "motorway": 18, - "motorway_link": 18, - "trunk": 18, - "trunk_link": 18, - "primary": 18, - "primary_link": 18, - "secondary": 18, - "secondary_link": 18, - "tertiary": 18, - "tertiary_link": 18, - "unclassified": 16, - "residential": 18, - "living_street": 12, - "cycleway": 18, - "path": 10, - "service": 14, - "road": 12, - "track": 12, - "footway": 6, - "pedestrian": 6, - "steps": 2 - }, - "surface": - { - "asphalt": 18, - "cobblestone": 8, - "cobblestone:flattened": 10, - "concrete": 18, - "concrete:plates": 16, - "concrete:lanes": 16, - "cement": 6, - "clay": 6, - "compacted": 16, - "dirt": 10, - "earth": 12, - "fine_gravel": 18, - "grass": 8, - "grass_paver": 8, - "gravel": 12, - "ground": 12, - "ice": 2, - "metal": 10, - "mud": 10, - "paved": 18, - "paving_stones": 12, - "paving_stones:30": 12, - "pebblestone": 16, - "sand": 6, - "salt": 6, - "sett": 10, - "unpaved": 14, - "unknown" : 6, - "wood": 6 - }, - "tracktype": - { - "grade1": 18, - "grade2": 12, - "grade3": 8, - "grade4": 6, - "grade5": 4 - } + "default": { + "motorway": 18, + "motorway_link": 18, + "trunk": 18, + "trunk_link": 18, + "primary": 18, + "primary_link": 18, + "secondary": 18, + "secondary_link": 18, + "tertiary": 18, + "tertiary_link": 18, + "unclassified": 16, + "residential": 18, + "living_street": 12, + "cycleway": 18, + "path": 10, + "service": 14, + "road": 12, + "track": 12, + "footway": 6, + "pedestrian": 6, + "steps": 2 + }, + "surface": { + "asphalt": 18, + "cobblestone": 8, + "cobblestone:flattened": 10, + "concrete": 18, + "concrete:plates": 16, + "concrete:lanes": 16, + "cement": 6, + "clay": 6, + "compacted": 16, + "dirt": 10, + "earth": 12, + "fine_gravel": 18, + "grass": 8, + "grass_paver": 8, + "gravel": 12, + "ground": 12, + "ice": 2, + "metal": 10, + "mud": 10, + "paved": 18, + "paving_stones": 12, + "paving_stones:30": 12, + "pebblestone": 16, + "sand": 6, + "salt": 6, + "sett": 10, + "unpaved": 14, + "unknown": 6, + "wood": 6 + }, + "tracktype": { + "grade1": 18, + "grade2": 12, + "grade3": 8, + "grade4": 6, + "grade5": 4 + } } diff --git a/ors-engine/src/main/resources/resources/services/routing/speed_limits/car.json b/ors-engine/src/main/resources/resources/services/routing/speed_limits/car.json index d3c32c7115..15aa66aef7 100644 --- a/ors-engine/src/main/resources/resources/services/routing/speed_limits/car.json +++ b/ors-engine/src/main/resources/resources/services/routing/speed_limits/car.json @@ -1,144 +1,141 @@ { - "default": - { - "motorway": 100, - "motorway_link": 60, - "motorroad": 90, - "trunk": 85, - "trunk_link": 60, - "primary": 65, - "primary_link": 50, - "secondary": 60, - "secondary_link": 50, - "tertiary": 50, - "tertiary_link": 40, - "unclassified": 30, - "residential": 30, - "living_street": 10, - "service": 20, - "road": 20, - "track": 15 - }, - "surface": - { - "asphalt": -1, - "concrete": -1, - "concrete:plates": -1, - "concrete:lanes": -1, - "paved": -1, - "cement": 80, - "compacted": 80, - "fine_gravel": 60, - "paving_stones":40, - "metal": 40, - "bricks": 40, - "grass": 30, - "wood": 30, - "sett": 30, - "grass_paver": 30, - "gravel": 30, - "unpaved": 30, - "ground": 30, - "dirt": 30, - "pebblestone": 30, - "tartan": 30, - "cobblestone": 20, - "clay": 20, - "earth": 15, - "stone": 15, - "rocky": 15, - "sand": 15, - "mud": 10, - "unknown" : 30 - }, - "tracktype": - { - "grade1": 40, - "grade2": 30, - "grade3": 20, - "grade4": 15, - "grade5": 10 - }, - "max_speeds": { - "AT:urban": 50, - "AT:rural": 100, - "AT:trunk": 100, - "AT:motorway": 130, - "CH:urban": 50, - "CH:rural": 80, - "CH:trunk": 100, - "CH:motorway": 120, - "CZ:urban": 50, - "CZ:rural": 90, - "CZ:trunk": 80, - "CZ:motorway": 80, - "DK:urban": 50, - "DK:rural": 80, - "DK:motorway": 130, - "DE:living_street": 7, - "DE:urban": 50, - "DE:rural": 100, - "DE:motorway": 130, - "FI:urban": 50, - "FI:rural": 80, - "FI:trunk": 100, - "FI:motorway": 120, - "FR:urban": 50, - "FR:rural": 80, - "FR:trunk": 110, - "FR:motorway": 130, - "GR:urban": 50, - "GR:rural": 90, - "GR:trunk": 110, - "GR:motorway": 130, - "HU:urban": 50, - "HU:rural": 90, - "HU:trunk": 110, - "HU:motorway": 130, - "IT:urban": 50, - "IT:rural": 90, - "IT:trunk": 110, - "IT:motorway": 130, - "JP:national": 60, - "JP:motorway": 100, - "PL:living_street": 20, - "PL:urban": 50, - "PL:rural": 90, - "PL:motorway": 140, - "RO:urban": 50, - "RO:rural": 90, - "RO:trunk": 100, - "RO:motorway": 130, - "RU:living_street": 20, - "RU:rural": 90, - "RU:urban": 60, - "RU:motorway": 110, - "SK:urban": 50, - "SK:rural": 90, - "SK:trunk": 90, - "SK:motorway": 90, - "SI:urban": 50, - "SI:rural": 90, - "SI:trunk": 110, - "SI:motorway": 130, - "ES:urban": 50, - "ES:rural": 90, - "ES:trunk": 100, - "ES:motorway": 120, - "SE:urban": 50, - "SE:rural": 70, - "SE:trunk": 90, - "SE:motorway": 110, - "GB:nsl_single": 95, - "GB:nsl_dual": 112, - "GB:motorway": 112, - "UA:urban": 60, - "UA:rural": 90, - "UA:trunk": 110, - "UA:motorway": 130, - "UZ:living_street": 30, - "UZ:urban": 70, - "UZ:rural": 100, - "UZ:motorway": 110 - } + "default": { + "motorway": 100, + "motorway_link": 60, + "motorroad": 90, + "trunk": 85, + "trunk_link": 60, + "primary": 65, + "primary_link": 50, + "secondary": 60, + "secondary_link": 50, + "tertiary": 50, + "tertiary_link": 40, + "unclassified": 30, + "residential": 30, + "living_street": 10, + "service": 20, + "road": 20, + "track": 15 + }, + "surface": { + "asphalt": -1, + "concrete": -1, + "concrete:plates": -1, + "concrete:lanes": -1, + "paved": -1, + "cement": 80, + "compacted": 80, + "fine_gravel": 60, + "paving_stones": 40, + "metal": 40, + "bricks": 40, + "grass": 30, + "wood": 30, + "sett": 30, + "grass_paver": 30, + "gravel": 30, + "unpaved": 30, + "ground": 30, + "dirt": 30, + "pebblestone": 30, + "tartan": 30, + "cobblestone": 20, + "clay": 20, + "earth": 15, + "stone": 15, + "rocky": 15, + "sand": 15, + "mud": 10, + "unknown": 30 + }, + "tracktype": { + "grade1": 40, + "grade2": 30, + "grade3": 20, + "grade4": 15, + "grade5": 10 + }, + "max_speeds": { + "AT:urban": 50, + "AT:rural": 100, + "AT:trunk": 100, + "AT:motorway": 130, + "CH:urban": 50, + "CH:rural": 80, + "CH:trunk": 100, + "CH:motorway": 120, + "CZ:urban": 50, + "CZ:rural": 90, + "CZ:trunk": 80, + "CZ:motorway": 80, + "DK:urban": 50, + "DK:rural": 80, + "DK:motorway": 130, + "DE:living_street": 7, + "DE:urban": 50, + "DE:rural": 100, + "DE:motorway": 130, + "FI:urban": 50, + "FI:rural": 80, + "FI:trunk": 100, + "FI:motorway": 120, + "FR:urban": 50, + "FR:rural": 80, + "FR:trunk": 110, + "FR:motorway": 130, + "GR:urban": 50, + "GR:rural": 90, + "GR:trunk": 110, + "GR:motorway": 130, + "HU:urban": 50, + "HU:rural": 90, + "HU:trunk": 110, + "HU:motorway": 130, + "IT:urban": 50, + "IT:rural": 90, + "IT:trunk": 110, + "IT:motorway": 130, + "JP:national": 60, + "JP:motorway": 100, + "PL:living_street": 20, + "PL:urban": 50, + "PL:rural": 90, + "PL:motorway": 140, + "RO:urban": 50, + "RO:rural": 90, + "RO:trunk": 100, + "RO:motorway": 130, + "RU:living_street": 20, + "RU:rural": 90, + "RU:urban": 60, + "RU:motorway": 110, + "SK:urban": 50, + "SK:rural": 90, + "SK:trunk": 90, + "SK:motorway": 90, + "SI:urban": 50, + "SI:rural": 90, + "SI:trunk": 110, + "SI:motorway": 130, + "ES:urban": 50, + "ES:rural": 90, + "ES:trunk": 100, + "ES:motorway": 120, + "SE:urban": 50, + "SE:rural": 70, + "SE:trunk": 90, + "SE:motorway": 110, + "GB:nsl_single": 95, + "GB:nsl_dual": 112, + "GB:motorway": 112, + "UA:urban": 60, + "UA:rural": 90, + "UA:trunk": 110, + "UA:motorway": 130, + "UZ:living_street": 30, + "UZ:urban": 70, + "UZ:rural": 100, + "UZ:motorway": 110 + } } diff --git a/ors-engine/src/main/resources/resources/services/routing/speed_limits/electrobike.json b/ors-engine/src/main/resources/resources/services/routing/speed_limits/electrobike.json index f51066b344..a3b483a7cd 100644 --- a/ors-engine/src/main/resources/resources/services/routing/speed_limits/electrobike.json +++ b/ors-engine/src/main/resources/resources/services/routing/speed_limits/electrobike.json @@ -1,66 +1,63 @@ { - "default": - { - "motorway": 21, - "motorway_link": 21, - "trunk": 21, - "trunk_link": 21, - "primary": 21, - "primary_link": 21, - "secondary": 21, - "secondary_link": 21, - "tertiary": 21, - "tertiary_link": 21, - "unclassified": 18, - "residential": 21, - "living_street": 12, - "cycleway": 21, - "path": 13, - "service": 15, - "road": 14, - "track": 13, - "footway": 6, - "pedestrian": 6, - "steps": 2 - }, - "surface": - { - "asphalt": 21, - "cobblestone": 9, - "cobblestone:flattened": 11, - "concrete": 21, - "concrete:plates": 18, - "concrete:lanes": 18, - "cement": 6, - "clay": 6, - "compacted": 17, - "dirt": 11, - "earth": 13, - "fine_gravel": 19, - "grass": 9, - "grass_paver": 9, - "gravel": 13, - "ground": 13, - "ice": 2, - "metal": 11, - "mud": 11, - "paved": 21, - "paving_stones": 13, - "paving_stones:30": 13, - "pebblestone": 18, - "sand": 7, - "salt": 7, - "sett": 11, - "unpaved": 15, - "unknown" : 6, - "wood": 7 - }, - "tracktype": - { - "grade1": 21, - "grade2": 15, - "grade3": 9, - "grade4": 7, - "grade5": 4 - } + "default": { + "motorway": 21, + "motorway_link": 21, + "trunk": 21, + "trunk_link": 21, + "primary": 21, + "primary_link": 21, + "secondary": 21, + "secondary_link": 21, + "tertiary": 21, + "tertiary_link": 21, + "unclassified": 18, + "residential": 21, + "living_street": 12, + "cycleway": 21, + "path": 13, + "service": 15, + "road": 14, + "track": 13, + "footway": 6, + "pedestrian": 6, + "steps": 2 + }, + "surface": { + "asphalt": 21, + "cobblestone": 9, + "cobblestone:flattened": 11, + "concrete": 21, + "concrete:plates": 18, + "concrete:lanes": 18, + "cement": 6, + "clay": 6, + "compacted": 17, + "dirt": 11, + "earth": 13, + "fine_gravel": 19, + "grass": 9, + "grass_paver": 9, + "gravel": 13, + "ground": 13, + "ice": 2, + "metal": 11, + "mud": 11, + "paved": 21, + "paving_stones": 13, + "paving_stones:30": 13, + "pebblestone": 18, + "sand": 7, + "salt": 7, + "sett": 11, + "unpaved": 15, + "unknown": 6, + "wood": 7 + }, + "tracktype": { + "grade1": 21, + "grade2": 15, + "grade3": 9, + "grade4": 7, + "grade5": 4 + } } diff --git a/ors-engine/src/main/resources/resources/services/routing/speed_limits/emergency.json b/ors-engine/src/main/resources/resources/services/routing/speed_limits/emergency.json index a17509041d..1f567292f0 100644 --- a/ors-engine/src/main/resources/resources/services/routing/speed_limits/emergency.json +++ b/ors-engine/src/main/resources/resources/services/routing/speed_limits/emergency.json @@ -1,146 +1,143 @@ { - "default": - { - "motorway": 130, - "motorway_link": 50, - "motorroad": 130, - "trunk": 120, - "trunk_link": 50, - "primary": 120, - "primary_link": 50, - "secondary": 120, - "secondary_link": 50, - "tertiary": 110, - "tertiary_link": 40, - "unclassified": 60, - "residential": 50, - "living_street": 20, - "service": 20, - "road": 20, - "track": 15, - "raceway": 100, - "cycleway": 10 - }, - "surface": - { - "asphalt": -1, - "concrete": -1, - "concrete:plates": -1, - "concrete:lanes": -1, - "paved": -1, - "cement": 60, - "compacted": 60, - "fine_gravel": 50, - "paving_stones":40, - "metal": 40, - "bricks": 40, - "grass": 30, - "wood": 30, - "sett": 30, - "grass_paver": 30, - "gravel": 30, - "unpaved": 30, - "ground": 30, - "dirt": 30, - "pebblestone": 30, - "tartan": 30, - "cobblestone": 20, - "clay": 20, - "earth": 15, - "stone": 15, - "rocky": 15, - "sand": 15, - "mud": 10, - "unknown" : 30 - }, - "tracktype": - { - "grade1": 25, - "grade2": 15, - "grade3": 15, - "grade4": 10, - "grade5": 5 - }, - "max_speeds": { - "AT:urban": 50, - "AT:rural": 80, - "AT:trunk": 80, - "AT:motorway": 80, - "CH:urban": 50, - "CH:rural": 80, - "CH:trunk": 80, - "CH:motorway": 80, - "CZ:urban": 50, - "CZ:rural": 90, - "CZ:trunk": 80, - "CZ:motorway": 80, - "DK:urban": 50, - "DK:rural": 80, - "DK:motorway": 80, - "DE:living_street": 7, - "DE:urban": 50, - "DE:rural": 80, - "DE:motorway": 80, - "FI:urban": 50, - "FI:rural": 80, - "FI:trunk": 80, - "FI:motorway": 80, - "FR:urban": 50, - "FR:rural": 80, - "FR:trunk": 80, - "FR:motorway": 80, - "GR:urban": 50, - "GR:rural": 80, - "GR:trunk": 80, - "GR:motorway": 80, - "HU:urban": 50, - "HU:rural": 80, - "HU:trunk": 80, - "HU:motorway": 80, - "IT:urban": 50, - "IT:rural": 80, - "IT:trunk": 80, - "IT:motorway": 80, - "JP:national": 60, - "JP:motorway": 80, - "PL:living_street": 20, - "PL:urban": 50, - "PL:rural": 80, - "PL:motorway": 80, - "RO:urban": 50, - "RO:rural": 80, - "RO:trunk": 80, - "RO:motorway": 80, - "RU:living_street": 20, - "RU:rural": 80, - "RU:urban": 60, - "RU:motorway": 80, - "SK:urban": 50, - "SK:rural": 80, - "SK:trunk": 80, - "SK:motorway": 80, - "SI:urban": 50, - "SI:rural": 80, - "SI:trunk": 80, - "SI:motorway": 80, - "ES:urban": 50, - "ES:rural": 80, - "ES:trunk": 80, - "ES:motorway": 80, - "SE:urban": 50, - "SE:rural": 70, - "SE:trunk": 80, - "SE:motorway": 80, - "GB:nsl_single": 90, - "GB:nsl_dual": 90, - "GB:motorway": 90, - "UA:urban": 60, - "UA:rural": 80, - "UA:trunk": 80, - "UA:motorway": 80, - "UZ:living_street": 30, - "UZ:urban": 70, - "UZ:rural": 90, - "UZ:motorway": 90 - } + "default": { + "motorway": 130, + "motorway_link": 50, + "motorroad": 130, + "trunk": 120, + "trunk_link": 50, + "primary": 120, + "primary_link": 50, + "secondary": 120, + "secondary_link": 50, + "tertiary": 110, + "tertiary_link": 40, + "unclassified": 60, + "residential": 50, + "living_street": 20, + "service": 20, + "road": 20, + "track": 15, + "raceway": 100, + "cycleway": 10 + }, + "surface": { + "asphalt": -1, + "concrete": -1, + "concrete:plates": -1, + "concrete:lanes": -1, + "paved": -1, + "cement": 60, + "compacted": 60, + "fine_gravel": 50, + "paving_stones": 40, + "metal": 40, + "bricks": 40, + "grass": 30, + "wood": 30, + "sett": 30, + "grass_paver": 30, + "gravel": 30, + "unpaved": 30, + "ground": 30, + "dirt": 30, + "pebblestone": 30, + "tartan": 30, + "cobblestone": 20, + "clay": 20, + "earth": 15, + "stone": 15, + "rocky": 15, + "sand": 15, + "mud": 10, + "unknown": 30 + }, + "tracktype": { + "grade1": 25, + "grade2": 15, + "grade3": 15, + "grade4": 10, + "grade5": 5 + }, + "max_speeds": { + "AT:urban": 50, + "AT:rural": 80, + "AT:trunk": 80, + "AT:motorway": 80, + "CH:urban": 50, + "CH:rural": 80, + "CH:trunk": 80, + "CH:motorway": 80, + "CZ:urban": 50, + "CZ:rural": 90, + "CZ:trunk": 80, + "CZ:motorway": 80, + "DK:urban": 50, + "DK:rural": 80, + "DK:motorway": 80, + "DE:living_street": 7, + "DE:urban": 50, + "DE:rural": 80, + "DE:motorway": 80, + "FI:urban": 50, + "FI:rural": 80, + "FI:trunk": 80, + "FI:motorway": 80, + "FR:urban": 50, + "FR:rural": 80, + "FR:trunk": 80, + "FR:motorway": 80, + "GR:urban": 50, + "GR:rural": 80, + "GR:trunk": 80, + "GR:motorway": 80, + "HU:urban": 50, + "HU:rural": 80, + "HU:trunk": 80, + "HU:motorway": 80, + "IT:urban": 50, + "IT:rural": 80, + "IT:trunk": 80, + "IT:motorway": 80, + "JP:national": 60, + "JP:motorway": 80, + "PL:living_street": 20, + "PL:urban": 50, + "PL:rural": 80, + "PL:motorway": 80, + "RO:urban": 50, + "RO:rural": 80, + "RO:trunk": 80, + "RO:motorway": 80, + "RU:living_street": 20, + "RU:rural": 80, + "RU:urban": 60, + "RU:motorway": 80, + "SK:urban": 50, + "SK:rural": 80, + "SK:trunk": 80, + "SK:motorway": 80, + "SI:urban": 50, + "SI:rural": 80, + "SI:trunk": 80, + "SI:motorway": 80, + "ES:urban": 50, + "ES:rural": 80, + "ES:trunk": 80, + "ES:motorway": 80, + "SE:urban": 50, + "SE:rural": 70, + "SE:trunk": 80, + "SE:motorway": 80, + "GB:nsl_single": 90, + "GB:nsl_dual": 90, + "GB:motorway": 90, + "UA:urban": 60, + "UA:rural": 80, + "UA:trunk": 80, + "UA:motorway": 80, + "UZ:living_street": 30, + "UZ:urban": 70, + "UZ:rural": 90, + "UZ:motorway": 90 + } } diff --git a/ors-engine/src/main/resources/resources/services/routing/speed_limits/heavyvehicle.json b/ors-engine/src/main/resources/resources/services/routing/speed_limits/heavyvehicle.json index ce92316a1e..e767b6d28f 100644 --- a/ors-engine/src/main/resources/resources/services/routing/speed_limits/heavyvehicle.json +++ b/ors-engine/src/main/resources/resources/services/routing/speed_limits/heavyvehicle.json @@ -1,144 +1,141 @@ { - "default": - { - "motorway": 85, - "motorway_link": 50, - "motorroad": 80, - "trunk": 80, - "trunk_link": 50, - "primary": 60, - "primary_link": 50, - "secondary": 60, - "secondary_link": 50, - "tertiary": 50, - "tertiary_link": 40, - "unclassified": 30, - "residential": 30, - "living_street": 10, - "service": 20, - "road": 20, - "track": 15 - }, - "surface": - { - "asphalt": -1, - "concrete": -1, - "concrete:plates": -1, - "concrete:lanes": -1, - "paved": -1, - "cement": 60, - "compacted": 60, - "fine_gravel": 50, - "paving_stones":40, - "metal": 40, - "bricks": 40, - "grass": 30, - "wood": 30, - "sett": 30, - "grass_paver": 30, - "gravel": 30, - "unpaved": 30, - "ground": 30, - "dirt": 30, - "pebblestone": 30, - "tartan": 30, - "cobblestone": 20, - "clay": 20, - "earth": 15, - "stone": 15, - "rocky": 15, - "sand": 15, - "mud": 10, - "unknown" : 30 - }, - "tracktype": - { - "grade1": 40, - "grade2": 30, - "grade3": 20, - "grade4": 15, - "grade5": 10 - }, - "max_speeds": { - "AT:urban": 50, - "AT:rural": 80, - "AT:trunk": 80, - "AT:motorway": 80, - "CH:urban": 50, - "CH:rural": 80, - "CH:trunk": 80, - "CH:motorway": 80, - "CZ:urban": 50, - "CZ:rural": 90, - "CZ:trunk": 80, - "CZ:motorway": 80, - "DK:urban": 50, - "DK:rural": 80, - "DK:motorway": 80, - "DE:living_street": 7, - "DE:urban": 50, - "DE:rural": 80, - "DE:motorway": 80, - "FI:urban": 50, - "FI:rural": 80, - "FI:trunk": 80, - "FI:motorway": 80, - "FR:urban": 50, - "FR:rural": 80, - "FR:trunk": 80, - "FR:motorway": 80, - "GR:urban": 50, - "GR:rural": 80, - "GR:trunk": 80, - "GR:motorway": 80, - "HU:urban": 50, - "HU:rural": 80, - "HU:trunk": 80, - "HU:motorway": 80, - "IT:urban": 50, - "IT:rural": 80, - "IT:trunk": 80, - "IT:motorway": 80, - "JP:national": 60, - "JP:motorway": 80, - "PL:living_street": 20, - "PL:urban": 50, - "PL:rural": 80, - "PL:motorway": 80, - "RO:urban": 50, - "RO:rural": 80, - "RO:trunk": 80, - "RO:motorway": 80, - "RU:living_street": 20, - "RU:rural": 80, - "RU:urban": 60, - "RU:motorway": 80, - "SK:urban": 50, - "SK:rural": 80, - "SK:trunk": 80, - "SK:motorway": 80, - "SI:urban": 50, - "SI:rural": 80, - "SI:trunk": 80, - "SI:motorway": 80, - "ES:urban": 50, - "ES:rural": 80, - "ES:trunk": 80, - "ES:motorway": 80, - "SE:urban": 50, - "SE:rural": 70, - "SE:trunk": 80, - "SE:motorway": 80, - "GB:nsl_single": 90, - "GB:nsl_dual": 90, - "GB:motorway": 90, - "UA:urban": 60, - "UA:rural": 80, - "UA:trunk": 80, - "UA:motorway": 80, - "UZ:living_street": 30, - "UZ:urban": 70, - "UZ:rural": 90, - "UZ:motorway": 90 - } + "default": { + "motorway": 85, + "motorway_link": 50, + "motorroad": 80, + "trunk": 80, + "trunk_link": 50, + "primary": 60, + "primary_link": 50, + "secondary": 60, + "secondary_link": 50, + "tertiary": 50, + "tertiary_link": 40, + "unclassified": 30, + "residential": 30, + "living_street": 10, + "service": 20, + "road": 20, + "track": 15 + }, + "surface": { + "asphalt": -1, + "concrete": -1, + "concrete:plates": -1, + "concrete:lanes": -1, + "paved": -1, + "cement": 60, + "compacted": 60, + "fine_gravel": 50, + "paving_stones": 40, + "metal": 40, + "bricks": 40, + "grass": 30, + "wood": 30, + "sett": 30, + "grass_paver": 30, + "gravel": 30, + "unpaved": 30, + "ground": 30, + "dirt": 30, + "pebblestone": 30, + "tartan": 30, + "cobblestone": 20, + "clay": 20, + "earth": 15, + "stone": 15, + "rocky": 15, + "sand": 15, + "mud": 10, + "unknown": 30 + }, + "tracktype": { + "grade1": 40, + "grade2": 30, + "grade3": 20, + "grade4": 15, + "grade5": 10 + }, + "max_speeds": { + "AT:urban": 50, + "AT:rural": 80, + "AT:trunk": 80, + "AT:motorway": 80, + "CH:urban": 50, + "CH:rural": 80, + "CH:trunk": 80, + "CH:motorway": 80, + "CZ:urban": 50, + "CZ:rural": 90, + "CZ:trunk": 80, + "CZ:motorway": 80, + "DK:urban": 50, + "DK:rural": 80, + "DK:motorway": 80, + "DE:living_street": 7, + "DE:urban": 50, + "DE:rural": 80, + "DE:motorway": 80, + "FI:urban": 50, + "FI:rural": 80, + "FI:trunk": 80, + "FI:motorway": 80, + "FR:urban": 50, + "FR:rural": 80, + "FR:trunk": 80, + "FR:motorway": 80, + "GR:urban": 50, + "GR:rural": 80, + "GR:trunk": 80, + "GR:motorway": 80, + "HU:urban": 50, + "HU:rural": 80, + "HU:trunk": 80, + "HU:motorway": 80, + "IT:urban": 50, + "IT:rural": 80, + "IT:trunk": 80, + "IT:motorway": 80, + "JP:national": 60, + "JP:motorway": 80, + "PL:living_street": 20, + "PL:urban": 50, + "PL:rural": 80, + "PL:motorway": 80, + "RO:urban": 50, + "RO:rural": 80, + "RO:trunk": 80, + "RO:motorway": 80, + "RU:living_street": 20, + "RU:rural": 80, + "RU:urban": 60, + "RU:motorway": 80, + "SK:urban": 50, + "SK:rural": 80, + "SK:trunk": 80, + "SK:motorway": 80, + "SI:urban": 50, + "SI:rural": 80, + "SI:trunk": 80, + "SI:motorway": 80, + "ES:urban": 50, + "ES:rural": 80, + "ES:trunk": 80, + "ES:motorway": 80, + "SE:urban": 50, + "SE:rural": 70, + "SE:trunk": 80, + "SE:motorway": 80, + "GB:nsl_single": 90, + "GB:nsl_dual": 90, + "GB:motorway": 90, + "UA:urban": 60, + "UA:rural": 80, + "UA:trunk": 80, + "UA:motorway": 80, + "UZ:living_street": 30, + "UZ:urban": 70, + "UZ:rural": 90, + "UZ:motorway": 90 + } } diff --git a/ors-engine/src/main/resources/resources/services/routing/speed_limits/mtb.json b/ors-engine/src/main/resources/resources/services/routing/speed_limits/mtb.json index 069395808d..dae0eb11fb 100644 --- a/ors-engine/src/main/resources/resources/services/routing/speed_limits/mtb.json +++ b/ors-engine/src/main/resources/resources/services/routing/speed_limits/mtb.json @@ -1,66 +1,63 @@ { - "default": - { - "motorway": 18, - "motorway_link": 18, - "trunk": 18, - "trunk_link": 18, - "primary": 18, - "primary_link": 18, - "secondary": 18, - "secondary_link": 18, - "tertiary": 18, - "tertiary_link": 18, - "unclassified": 16, - "residential": 16, - "living_street": 12, - "cycleway": 18, - "path": 10, - "service": 14, - "road": 12, - "track": 18, - "footway": 6, - "pedestrian": 6, - "steps": 2 - }, - "surface": - { - "asphalt": 18, - "cobblestone": 10, - "cobblestone:flattened": 10, - "concrete": 14, - "concrete:plates": 16, - "concrete:lanes": 16, - "cement": 10, - "clay": 10, - "compacted": 14, - "dirt": 14, - "earth": 14, - "fine_gravel": 18, - "grass": 14, - "grass_paver": 14, - "gravel": 16, - "ground": 16, - "ice": 2, - "metal": 10, - "mud": 12, - "paved": 18, - "paving_stones": 12, - "paving_stones:30": 12, - "pebblestone": 12, - "sand": 10, - "salt": 12, - "sett": 10, - "unpaved": 16, - "unknown" : 6, - "wood": 10 - }, - "tracktype": - { - "grade1": 18, - "grade2": 12, - "grade3": 8, - "grade4": 6, - "grade5": 4 - } + "default": { + "motorway": 18, + "motorway_link": 18, + "trunk": 18, + "trunk_link": 18, + "primary": 18, + "primary_link": 18, + "secondary": 18, + "secondary_link": 18, + "tertiary": 18, + "tertiary_link": 18, + "unclassified": 16, + "residential": 16, + "living_street": 12, + "cycleway": 18, + "path": 10, + "service": 14, + "road": 12, + "track": 18, + "footway": 6, + "pedestrian": 6, + "steps": 2 + }, + "surface": { + "asphalt": 18, + "cobblestone": 10, + "cobblestone:flattened": 10, + "concrete": 14, + "concrete:plates": 16, + "concrete:lanes": 16, + "cement": 10, + "clay": 10, + "compacted": 14, + "dirt": 14, + "earth": 14, + "fine_gravel": 18, + "grass": 14, + "grass_paver": 14, + "gravel": 16, + "ground": 16, + "ice": 2, + "metal": 10, + "mud": 12, + "paved": 18, + "paving_stones": 12, + "paving_stones:30": 12, + "pebblestone": 12, + "sand": 10, + "salt": 12, + "sett": 10, + "unpaved": 16, + "unknown": 6, + "wood": 10 + }, + "tracktype": { + "grade1": 18, + "grade2": 12, + "grade3": 8, + "grade4": 6, + "grade5": 4 + } } diff --git a/ors-engine/src/main/resources/resources/services/routing/speed_limits/racingbike.json b/ors-engine/src/main/resources/resources/services/routing/speed_limits/racingbike.json index 3d956167e7..be70d15a9b 100644 --- a/ors-engine/src/main/resources/resources/services/routing/speed_limits/racingbike.json +++ b/ors-engine/src/main/resources/resources/services/routing/speed_limits/racingbike.json @@ -1,66 +1,63 @@ { - "default": - { - "motorway": 20, - "motorway_link": 20, - "trunk": 20, - "trunk_link": 20, - "primary": 20, - "primary_link": 20, - "secondary": 20, - "secondary_link": 20, - "tertiary": 20, - "tertiary_link": 20, - "unclassified": 16, - "residential": 16, - "living_street": 12, - "cycleway": 18, - "path": 8, - "service": 12, - "road": 12, - "track": 2, - "footway": 6, - "pedestrian": 6, - "steps": 2 - }, - "surface": - { - "asphalt": 20, - "cobblestone": 10, - "cobblestone:flattened": 10, - "concrete": 20, - "concrete:plates": 16, - "concrete:lanes": 16, - "cement": 6, - "clay": 6, - "compacted": 2, - "dirt": 2, - "earth": 2, - "fine_gravel": 4, - "grass": 2, - "grass_paver": 2, - "gravel": 2, - "ground": 2, - "ice": 2, - "metal": 2, - "mud": 2, - "paved": 20, - "paving_stones": 10, - "paving_stones:30": 10, - "pebblestone": 2, - "sand": 2, - "salt": 2, - "sett": 10, - "unpaved": 2, - "unknown" : 2, - "wood": 2 - }, - "tracktype": - { - "grade1": 20, - "grade2": 10, - "grade3": 2, - "grade4": 2, - "grade5": 2 - } + "default": { + "motorway": 20, + "motorway_link": 20, + "trunk": 20, + "trunk_link": 20, + "primary": 20, + "primary_link": 20, + "secondary": 20, + "secondary_link": 20, + "tertiary": 20, + "tertiary_link": 20, + "unclassified": 16, + "residential": 16, + "living_street": 12, + "cycleway": 18, + "path": 8, + "service": 12, + "road": 12, + "track": 2, + "footway": 6, + "pedestrian": 6, + "steps": 2 + }, + "surface": { + "asphalt": 20, + "cobblestone": 10, + "cobblestone:flattened": 10, + "concrete": 20, + "concrete:plates": 16, + "concrete:lanes": 16, + "cement": 6, + "clay": 6, + "compacted": 2, + "dirt": 2, + "earth": 2, + "fine_gravel": 4, + "grass": 2, + "grass_paver": 2, + "gravel": 2, + "ground": 2, + "ice": 2, + "metal": 2, + "mud": 2, + "paved": 20, + "paving_stones": 10, + "paving_stones:30": 10, + "pebblestone": 2, + "sand": 2, + "salt": 2, + "sett": 10, + "unpaved": 2, + "unknown": 2, + "wood": 2 + }, + "tracktype": { + "grade1": 20, + "grade2": 10, + "grade3": 2, + "grade4": 2, + "grade5": 2 + } } diff --git a/ors-engine/src/test/java/org/heigit/ors/pbt/AlgorithmComparisonTest.java b/ors-engine/src/test/java/org/heigit/ors/pbt/AlgorithmComparisonTest.java index ad7a4f9d07..aaafe5c306 100644 --- a/ors-engine/src/test/java/org/heigit/ors/pbt/AlgorithmComparisonTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/pbt/AlgorithmComparisonTest.java @@ -28,8 +28,8 @@ @Domain(GraphHopperDomain.class) class AlgorithmComparisonTest { private static Directory dir; - private Weighting weighting = new ShortestWeighting(carEncoder); - private CHConfig chConfig = new CHConfig("c", weighting, false, CHConfig.TYPE_CORE); + private final Weighting weighting = new ShortestWeighting(carEncoder); + private final CHConfig chConfig = new CHConfig("c", weighting, false, CHConfig.TYPE_CORE); private RoutingCHGraph routingCHGraph; @BeforeProperty @@ -54,7 +54,7 @@ public void cleanUp() { } // TODO Future improvement : Uncomment this and resolve differences to enable this test - + // @Property(tries = 2000)// , seed="-2270368960184993644") // reproduces a failure // // @Report(Reporting.GENERATED) // void compare_distance_computation_between_CoreMatrix_and_CoreALT( @@ -136,7 +136,7 @@ private float[] computeDistancesFromRPHAST(GraphHopperStorage sampleGraph, Matri return extractValues(sampleGraph, sources, destinations, destTrees); } - private float[] extractValues(GraphHopperStorage sampleGraph, MatrixLocations sources, MatrixLocations destinations, MultiTreeSPEntry[] destTrees) throws Exception { + private float[] extractValues(GraphHopperStorage sampleGraph, MatrixLocations sources, MatrixLocations destinations, MultiTreeSPEntry[] destTrees) throws Exception { MultiTreeMetricsExtractor pathMetricsExtractor = new MultiTreeMetricsExtractor(MatrixMetricsType.DISTANCE, sampleGraph.getRoutingCHGraph(), carEncoder, weighting, DistanceUnit.METERS); int tableSize = sources.size() * destinations.size(); diff --git a/ors-engine/src/test/java/org/heigit/ors/pbt/GraphGenerator.java b/ors-engine/src/test/java/org/heigit/ors/pbt/GraphGenerator.java index 6da02d3b3c..7e45f26d18 100644 --- a/ors-engine/src/test/java/org/heigit/ors/pbt/GraphGenerator.java +++ b/ors-engine/src/test/java/org/heigit/ors/pbt/GraphGenerator.java @@ -41,7 +41,7 @@ GraphHopperStorage createGHStorage() { return new GraphBuilder(encodingManager).setCHConfigs(chConfig).create(); } - private static Map randomSeeds = new HashMap<>(); + private static final Map randomSeeds = new HashMap<>(); private static void rememberSeed(GraphHopperStorage storage, long randomSeed) { randomSeeds.put(storage, randomSeed); diff --git a/ors-engine/src/test/java/org/heigit/ors/pbt/GraphHopperDomain.java b/ors-engine/src/test/java/org/heigit/ors/pbt/GraphHopperDomain.java index 984296dcd5..7eba07cef6 100644 --- a/ors-engine/src/test/java/org/heigit/ors/pbt/GraphHopperDomain.java +++ b/ors-engine/src/test/java/org/heigit/ors/pbt/GraphHopperDomain.java @@ -120,12 +120,12 @@ public Object report(Object o) { Map edges = new HashMap<>(); AllEdgesIterator edgesIterator = graph.getAllEdges(); while (edgesIterator.next()) { - String edgeString = - "%s->%s: %s".formatted( - edgesIterator.getBaseNode(), - edgesIterator.getAdjNode(), - edgesIterator.getDistance() - ); + String edgeString = + "%s->%s: %s".formatted( + edgesIterator.getBaseNode(), + edgesIterator.getAdjNode(), + edgesIterator.getDistance() + ); edges.put(edgesIterator.getEdge(), edgeString); } attributes.put("edges", edges); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/RouteResultBuilderTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/RouteResultBuilderTest.java index 5020df196d..369b03147d 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/RouteResultBuilderTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/RouteResultBuilderTest.java @@ -28,12 +28,12 @@ public RouteResultBuilderTest() throws Exception { @BeforeEach void init() throws Exception { - Coordinate [] coordinates = new Coordinate[2]; + Coordinate[] coordinates = new Coordinate[2]; coordinates[0] = new Coordinate(12.3, 45.6); coordinates[1] = new Coordinate(23.4, 56.7); request1 = new RoutingRequest(); request1.setCoordinates(coordinates); - request1.setAttributes(new String[] {"detourfactor"}); + request1.setAttributes(new String[]{"detourfactor"}); request1.setExtraInfo(RouteExtraInfoFlag.getFromString("osmid")); request1.setIncludeManeuvers(true); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/RouteSearchParametersTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/RouteSearchParametersTest.java index 48f1feca24..44f0608e8a 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/RouteSearchParametersTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/RouteSearchParametersTest.java @@ -1,6 +1,5 @@ package org.heigit.ors.routing; -import org.heigit.ors.exceptions.ParameterValueException; import org.heigit.ors.routing.graphhopper.extensions.HeavyVehicleAttributes; import org.heigit.ors.routing.parameters.VehicleParameters; import org.heigit.ors.routing.pathprocessors.BordersExtractor; diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstraTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstraTest.java index 9ed82f53fe..2ac1b3b603 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstraTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreDijkstraTest.java @@ -300,7 +300,7 @@ void testTwoProfiles() { //car prepareCore(g, carConfig, new CoreTestEdgeFilter()); RoutingCHGraph chGraph = g.getCoreGraph(carConfig.getName()); - RoutingAlgorithm algo = new CoreRoutingAlgorithmFactory(chGraph).createAlgo(g, carWeighting, new AlgorithmOptions()); + RoutingAlgorithm algo = new CoreRoutingAlgorithmFactory(chGraph).createAlgo(g, carWeighting, new AlgorithmOptions()); Path p1 = algo.calcPath(0, 7); assertEquals(IntArrayList.from(0, 4, 6, 7), p1.calcNodes()); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreTestEdgeFilter.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreTestEdgeFilter.java index ce7c5c8bd0..5012bdacf4 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreTestEdgeFilter.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/core/CoreTestEdgeFilter.java @@ -13,32 +13,33 @@ */ package org.heigit.ors.routing.graphhopper.extensions.core; -import java.util.HashSet; - import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.GHUtility; +import java.util.HashSet; + public class CoreTestEdgeFilter extends HashSet implements EdgeFilter { - /** - *Determine whether or not an edge is to be filtered - * @param iter iterator pointing to a given edge - * @return true iff the edge pointed to by the iterator is not to be filtered - */ - @Override - public final boolean accept(EdgeIteratorState iter) { - return !contains(iter.getEdgeKey()); - } - - public void add(int edge) { - add(edge, false); - add(edge, true); - } - - public void add(int edge, boolean reverse) { - int edgeKey = GHUtility.createEdgeKey(edge, reverse); - super.add(edgeKey); - } + /** + * Determine whether or not an edge is to be filtered + * + * @param iter iterator pointing to a given edge + * @return true iff the edge pointed to by the iterator is not to be filtered + */ + @Override + public final boolean accept(EdgeIteratorState iter) { + return !contains(iter.getEdgeKey()); + } + + public void add(int edge) { + add(edge, false); + add(edge, true); + } + + public void add(int edge, boolean reverse) { + int edgeKey = GHUtility.createEdgeKey(edge, reverse); + super.add(edgeKey); + } } diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLMPreparationHandlerTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLMPreparationHandlerTest.java index 7c73293c94..d2b3803495 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLMPreparationHandlerTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLMPreparationHandlerTest.java @@ -76,7 +76,7 @@ void testPrepareWeightingNo() { assertTrue(handler.isEnabled()); // See #1076 - ghConfig.setLMProfiles(Collections.emptyList()); + ghConfig.setLMProfiles(Collections.emptyList()); handler = new CoreLMPreparationHandler(); handler.init(ghConfig); assertFalse(handler.isEnabled()); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLandmarkStorageTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLandmarkStorageTest.java index 79bf40fb5b..c983f4efac 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLandmarkStorageTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/CoreLandmarkStorageTest.java @@ -50,7 +50,7 @@ class CoreLandmarkStorageTest { private BooleanEncodedValue subnetworkEnc; private Weighting weighting; - private Directory dir = new GHDirectory("", DAType.RAM_INT); + private final Directory dir = new GHDirectory("", DAType.RAM_INT); private RoutingCHGraph routingCHGraph; private CHConfig chConfig; @@ -63,7 +63,7 @@ void setUp() { weighting = new ShortestWeighting(encoder); chConfig = new CHConfig(encoder.toString(), weighting, false, CHConfig.TYPE_CORE); - graph = new ORSGraphHopperStorage(new RAMDirectory(), encodingManager, false, false, -1); + graph = new ORSGraphHopperStorage(new RAMDirectory(), encodingManager, false, false, -1); graph.addCoreGraph(chConfig); graph.create(1000); routingCHGraph = graph.getCoreGraph(chConfig.getName()); @@ -110,7 +110,7 @@ private void contractGraph(CoreTestEdgeFilter restrictedEdges, int[] nodeOrderin PrepareCore prepare = new PrepareCore(graph, chConfig, restrictedEdges); - if (nodeOrdering!=null) + if (nodeOrdering != null) prepare.useFixedNodeOrdering(NodeOrderingProvider.fromArray(nodeOrdering)); // set contraction parameters to prevent test results from changing when algorithm parameters are tweaked diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/PrepareCoreLandmarksTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/PrepareCoreLandmarksTest.java index 4cc5d922fe..387277599d 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/PrepareCoreLandmarksTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/corelm/PrepareCoreLandmarksTest.java @@ -60,10 +60,10 @@ */ class PrepareCoreLandmarksTest -/* extends AbstractRoutingAlgorithmTester */ { + /* extends AbstractRoutingAlgorithmTester */ { private ORSGraphHopperStorage graph; private FlagEncoder encoder; - private TraversalMode tm = TraversalMode.NODE_BASED; + private final TraversalMode tm = TraversalMode.NODE_BASED; private EncodingManager encodingManager; private Weighting weighting; private CHConfig chConfig; diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilterTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilterTest.java index a181b34bba..d660b3ade8 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilterTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidAreasEdgeFilterTest.java @@ -36,12 +36,12 @@ void TestAvoidPolygons() { GeometryFactory gf = new GeometryFactory(); - Polygon poly = gf.createPolygon(new Coordinate[]{ new Coordinate(-1,5), - new Coordinate(1,5), - new Coordinate(1,6), - new Coordinate(-1,5)}); + Polygon poly = gf.createPolygon(new Coordinate[]{new Coordinate(-1, 5), + new Coordinate(1, 5), + new Coordinate(1, 6), + new Coordinate(-1, 5)}); - AvoidAreasEdgeFilter filter = new AvoidAreasEdgeFilter(new Polygon[] {poly}); + AvoidAreasEdgeFilter filter = new AvoidAreasEdgeFilter(new Polygon[]{poly}); assertFalse(filter.accept(iter1)); assertTrue(filter.accept(iter2)); } diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilterTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilterTest.java index 233bc925ad..3c248805ef 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilterTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/edgefilters/AvoidBordersEdgeFilterTest.java @@ -33,8 +33,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class AvoidBordersEdgeFilterTest { - private PMap properties = new PMap(); - private final EncodingManager encodingManager = EncodingManager.create(new ORSDefaultFlagEncoderFactory().createFlagEncoder(FlagEncoderNames.CAR_ORS,properties)); + private final PMap properties = new PMap(); + private final EncodingManager encodingManager = EncodingManager.create(new ORSDefaultFlagEncoderFactory().createFlagEncoder(FlagEncoderNames.CAR_ORS, properties)); private final FlagEncoder encoder = encodingManager.getEncoder(FlagEncoderNames.CAR_ORS); private final BordersGraphStorage _graphStorage; @@ -60,13 +60,13 @@ private VirtualEdgeIteratorState generateEdge(int id) { IntsRef intsRef = encodingManager.createEdgeFlags(); int edgeKey = GHUtility.createEdgeKey(id, false); return new VirtualEdgeIteratorState(0, edgeKey, 1, 2, 10, - intsRef, "test", Helper.createPointList(51,0,51,1),false); + intsRef, "test", Helper.createPointList(51, 0, 51, 1), false); } @Test void TestAvoidAllBorders() { _searchParams.setAvoidBorders(BordersExtractor.Avoid.ALL); - _searchParams.setAvoidCountries(new int[] {}); + _searchParams.setAvoidCountries(new int[]{}); AvoidBordersEdgeFilter filter = new AvoidBordersEdgeFilter(_searchParams, _graphStorage); @@ -83,7 +83,7 @@ void TestAvoidAllBorders() { @Test void TestAvoidControlledBorders() { _searchParams.setAvoidBorders(BordersExtractor.Avoid.CONTROLLED); - _searchParams.setAvoidCountries(new int[] {}); + _searchParams.setAvoidCountries(new int[]{}); AvoidBordersEdgeFilter filter = new AvoidBordersEdgeFilter(_searchParams, _graphStorage); @@ -99,7 +99,7 @@ void TestAvoidControlledBorders() { @Test void TestAvoidNoBorders() { _searchParams.setAvoidBorders(BordersExtractor.Avoid.NONE); - _searchParams.setAvoidCountries(new int[] {}); + _searchParams.setAvoidCountries(new int[]{}); AvoidBordersEdgeFilter filter = new AvoidBordersEdgeFilter(_searchParams, _graphStorage); @@ -115,7 +115,7 @@ void TestAvoidNoBorders() { @Test void TestAvoidSpecificBorders() { _searchParams.setAvoidBorders(BordersExtractor.Avoid.NONE); - _searchParams.setAvoidCountries(new int[] {1, 5}); + _searchParams.setAvoidCountries(new int[]{1, 5}); AvoidBordersEdgeFilter filter = new AvoidBordersEdgeFilter(_searchParams, _graphStorage); @@ -131,7 +131,7 @@ void TestAvoidSpecificBorders() { @Test void TestAvoidSpecificAndControlledBorders() { _searchParams.setAvoidBorders(BordersExtractor.Avoid.CONTROLLED); - _searchParams.setAvoidCountries(new int[] {3}); + _searchParams.setAvoidCountries(new int[]{3}); AvoidBordersEdgeFilter filter = new AvoidBordersEdgeFilter(_searchParams, _graphStorage); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HikingFlagEncoderTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HikingFlagEncoderTest.java index dfc7d182aa..0588206b93 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HikingFlagEncoderTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/flagencoders/HikingFlagEncoderTest.java @@ -35,7 +35,7 @@ class HikingFlagEncoderTest { public HikingFlagEncoderTest() { encodingManager = EncodingManager.create(new ORSDefaultFlagEncoderFactory(), FlagEncoderNames.HIKING_ORS); - flagEncoder = (HikingFlagEncoder)encodingManager.getEncoder(FlagEncoderNames.HIKING_ORS); + flagEncoder = (HikingFlagEncoder) encodingManager.getEncoder(FlagEncoderNames.HIKING_ORS); } @BeforeEach @@ -111,20 +111,20 @@ void testSafeHighwayPriorities() { TreeMap priorityMap = new TreeMap<>(); way.setTag("highway", "track"); flagEncoder.assignSafeHighwayPriority(way, priorityMap); - assertEquals((Integer)PriorityCode.VERY_NICE.getValue(), priorityMap.lastEntry().getValue()); + assertEquals((Integer) PriorityCode.VERY_NICE.getValue(), priorityMap.lastEntry().getValue()); priorityMap.clear(); way.setTag("highway", "path"); flagEncoder.assignSafeHighwayPriority(way, priorityMap); - assertEquals((Integer)PriorityCode.VERY_NICE.getValue(), priorityMap.lastEntry().getValue()); + assertEquals((Integer) PriorityCode.VERY_NICE.getValue(), priorityMap.lastEntry().getValue()); priorityMap.clear(); way.setTag("highway", "footway"); flagEncoder.assignSafeHighwayPriority(way, priorityMap); - assertEquals((Integer)PriorityCode.VERY_NICE.getValue(), priorityMap.lastEntry().getValue()); + assertEquals((Integer) PriorityCode.VERY_NICE.getValue(), priorityMap.lastEntry().getValue()); priorityMap.clear(); way.setTag("highway", "living_street"); flagEncoder.assignSafeHighwayPriority(way, priorityMap); - assertEquals((Integer)PriorityCode.PREFER.getValue(), priorityMap.lastEntry().getValue()); + assertEquals((Integer) PriorityCode.PREFER.getValue(), priorityMap.lastEntry().getValue()); priorityMap.clear(); } diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchyTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchyTest.java index ba88389d2e..6d13abf532 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchyTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersHierarchyTest.java @@ -28,26 +28,26 @@ class CountryBordersHierarchyTest { CountryBordersPolygon cbp1, cbp2, cbp3; CountryBordersHierarchy cbh1, cbh2; - Coordinate[] country1Geom = new Coordinate[] { - new Coordinate(0,0), - new Coordinate(0,1), - new Coordinate(1,1), - new Coordinate(1,0), - new Coordinate(0,0) + Coordinate[] country1Geom = new Coordinate[]{ + new Coordinate(0, 0), + new Coordinate(0, 1), + new Coordinate(1, 1), + new Coordinate(1, 0), + new Coordinate(0, 0) }; - Coordinate[] country2Geom = new Coordinate[] { - new Coordinate(0.1,0.1), - new Coordinate(-1,0.1), - new Coordinate(-1,-1), - new Coordinate(0.1,-1), - new Coordinate(0.1,0.1) + Coordinate[] country2Geom = new Coordinate[]{ + new Coordinate(0.1, 0.1), + new Coordinate(-1, 0.1), + new Coordinate(-1, -1), + new Coordinate(0.1, -1), + new Coordinate(0.1, 0.1) }; - Coordinate[] country3Geom = new Coordinate[] { - new Coordinate(5,5), - new Coordinate(10,5), - new Coordinate(10,10), - new Coordinate(5,10), - new Coordinate(5,5) + Coordinate[] country3Geom = new Coordinate[]{ + new Coordinate(5, 5), + new Coordinate(10, 5), + new Coordinate(10, 10), + new Coordinate(5, 10), + new Coordinate(5, 5) }; public CountryBordersHierarchyTest() { diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygonTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygonTest.java index 1022d88882..18d8d26802 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygonTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersPolygonTest.java @@ -25,12 +25,12 @@ class CountryBordersPolygonTest { GeometryFactory gf = new GeometryFactory(); CountryBordersPolygon cbp; - Coordinate[] country1Geom = new Coordinate[] { - new Coordinate(0,0), - new Coordinate(-1,1), - new Coordinate(1,2), - new Coordinate(1,-1), - new Coordinate(0,0) + Coordinate[] country1Geom = new Coordinate[]{ + new Coordinate(0, 0), + new Coordinate(-1, 1), + new Coordinate(1, 2), + new Coordinate(1, -1), + new Coordinate(0, 0) }; public CountryBordersPolygonTest() { @@ -58,7 +58,7 @@ void TestBoundaryGeometry() { Coordinate[] cbpCoords = boundary.getCoordinates(); assertEquals(country1Geom.length, cbpCoords.length); assertEquals(country1Geom[0].x, cbpCoords[0].x, 0.0); - assertEquals(country1Geom[3].y, cbpCoords[3].y,0.0); + assertEquals(country1Geom[3].y, cbpCoords[3].y, 0.0); } /** @@ -78,14 +78,14 @@ void TestBBox() { */ @Test void TestIntersection() { - LineString ls = gf.createLineString(new Coordinate[] { + LineString ls = gf.createLineString(new Coordinate[]{ new Coordinate(0.5, 0.5), new Coordinate(-10.5, -10.5) }); assertTrue(cbp.crossesBoundary(ls)); - ls = gf.createLineString(new Coordinate[] { + ls = gf.createLineString(new Coordinate[]{ new Coordinate(0.5, 0.5), new Coordinate(0.25, 0.25) }); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReaderTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReaderTest.java index 4d52f659fe..d9d183ce12 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReaderTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/borders/CountryBordersReaderTest.java @@ -13,8 +13,8 @@ */ package org.heigit.ors.routing.graphhopper.extensions.reader.borders; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; @@ -27,32 +27,32 @@ class CountryBordersReaderTest { CountryBordersHierarchy[] hierarchies; - Coordinate[] country1Geom = new Coordinate[] { - new Coordinate(0,1), - new Coordinate(1,1), - new Coordinate(1,0), - new Coordinate(0,0), - new Coordinate(0,1) + Coordinate[] country1Geom = new Coordinate[]{ + new Coordinate(0, 1), + new Coordinate(1, 1), + new Coordinate(1, 0), + new Coordinate(0, 0), + new Coordinate(0, 1) }; - Coordinate[] country2Geom = new Coordinate[] { - new Coordinate(1,2), - new Coordinate(2,2), - new Coordinate(2,1), - new Coordinate(1,1), - new Coordinate(1,2) + Coordinate[] country2Geom = new Coordinate[]{ + new Coordinate(1, 2), + new Coordinate(2, 2), + new Coordinate(2, 1), + new Coordinate(1, 1), + new Coordinate(1, 2) }; - Coordinate[] country3Geom = new Coordinate[] { - new Coordinate(-1,0), - new Coordinate(0,-1), - new Coordinate(-1,-1), - new Coordinate(-1,0) + Coordinate[] country3Geom = new Coordinate[]{ + new Coordinate(-1, 0), + new Coordinate(0, -1), + new Coordinate(-1, -1), + new Coordinate(-1, 0) }; - Coordinate[] country4Geom = new Coordinate[] { - new Coordinate(-2,-1), - new Coordinate(-1,-1), - new Coordinate(-1,-2), - new Coordinate(-2,-2), - new Coordinate(-2,-1) + Coordinate[] country4Geom = new Coordinate[]{ + new Coordinate(-2, -1), + new Coordinate(-1, -1), + new Coordinate(-1, -2), + new Coordinate(-2, -2), + new Coordinate(-2, -1) }; GeometryFactory gf = new GeometryFactory(); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWayTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWayTest.java index d6adb80eed..504ee2b119 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWayTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/reader/osmfeatureprocessors/WheelchairSidewalkWayTest.java @@ -34,7 +34,7 @@ void TestThatBothSidesGetProcessed() { int count = 0; - while(!way.hasWayBeenFullyProcessed()) { + while (!way.hasWayBeenFullyProcessed()) { count++; way.prepare(); } diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorageTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorageTest.java index 12ab5ac002..af5e92fc7d 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorageTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/BordersGraphStorageTest.java @@ -29,7 +29,7 @@ public BordersGraphStorageTest() { @Test void TestItemCreation() { - _storage.setEdgeValue(1, (short)1, (short)2, (short)3); + _storage.setEdgeValue(1, (short) 1, (short) 2, (short) 3); assertEquals(1, _storage.getEdgeValue(1, BordersGraphStorage.Property.TYPE)); assertEquals(2, _storage.getEdgeValue(1, BordersGraphStorage.Property.START)); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilderTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilderTest.java index 0f7de10516..781a8094f5 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilderTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/BordersGraphStorageBuilderTest.java @@ -29,46 +29,46 @@ class BordersGraphStorageBuilderTest { private final CountryBordersReader _cbr; - private final Coordinate[] coords1 = new Coordinate[] { - new Coordinate(0,0), - new Coordinate(1,0), - new Coordinate(1,1), - new Coordinate(0,1), - new Coordinate(0,0) + private final Coordinate[] coords1 = new Coordinate[]{ + new Coordinate(0, 0), + new Coordinate(1, 0), + new Coordinate(1, 1), + new Coordinate(0, 1), + new Coordinate(0, 0) }; - private final Coordinate[] coords2 = new Coordinate[] { - new Coordinate(1,0), - new Coordinate(1,1), - new Coordinate(2,1), - new Coordinate(2,0), - new Coordinate(1,0) + private final Coordinate[] coords2 = new Coordinate[]{ + new Coordinate(1, 0), + new Coordinate(1, 1), + new Coordinate(2, 1), + new Coordinate(2, 0), + new Coordinate(1, 0) }; - private final Coordinate[] coords3 = new Coordinate[] { - new Coordinate(2,0), - new Coordinate(3,0), - new Coordinate(3,1), - new Coordinate(2,1), - new Coordinate(2,0) + private final Coordinate[] coords3 = new Coordinate[]{ + new Coordinate(2, 0), + new Coordinate(3, 0), + new Coordinate(3, 1), + new Coordinate(2, 1), + new Coordinate(2, 0) }; - private final Coordinate[] coordsO1 = new Coordinate[] { - new Coordinate(100,100), - new Coordinate(100,102), - new Coordinate(102,102), - new Coordinate(102,100), - new Coordinate(100,100) + private final Coordinate[] coordsO1 = new Coordinate[]{ + new Coordinate(100, 100), + new Coordinate(100, 102), + new Coordinate(102, 102), + new Coordinate(102, 100), + new Coordinate(100, 100) }; - private final Coordinate[] coordsO2 = new Coordinate[] { - new Coordinate(101,101), - new Coordinate(103,101), - new Coordinate(103,103), - new Coordinate(101,103), - new Coordinate(101,101) + private final Coordinate[] coordsO2 = new Coordinate[]{ + new Coordinate(101, 101), + new Coordinate(103, 101), + new Coordinate(103, 103), + new Coordinate(101, 103), + new Coordinate(101, 101) }; private final GeometryFactory gf = new GeometryFactory(); public BordersGraphStorageBuilderTest() { - _builder= new BordersGraphStorageBuilder(); + _builder = new BordersGraphStorageBuilder(); _cbr = new CountryBordersReader(); CountryBordersHierarchy h = new CountryBordersHierarchy(); @@ -101,9 +101,9 @@ public BordersGraphStorageBuilderTest() { @Test void TestProcessWay() { ReaderWay rw = new ReaderWay(1); - Coordinate[] cs = new Coordinate[] { - new Coordinate(0.5,0.5), - new Coordinate(1.5,0.5) + Coordinate[] cs = new Coordinate[]{ + new Coordinate(0.5, 0.5), + new Coordinate(1.5, 0.5) }; _builder.processWay(rw, cs, null); @@ -112,9 +112,9 @@ void TestProcessWay() { assertEquals("c2", rw.getTag("country2")); ReaderWay rw2 = new ReaderWay(1); - Coordinate[] cs2 = new Coordinate[] { - new Coordinate(0.5,0.5), - new Coordinate(0.75,0.5) + Coordinate[] cs2 = new Coordinate[]{ + new Coordinate(0.5, 0.5), + new Coordinate(0.75, 0.5) }; _builder.processWay(rw2, cs2, null); @@ -128,9 +128,9 @@ void TestProcessWay() { */ @Test void TestFindBorderCrossing() { - String[] names = _builder.findBorderCrossing(new Coordinate[] { - new Coordinate(0.5,0.5), - new Coordinate(1.5,0.5) + String[] names = _builder.findBorderCrossing(new Coordinate[]{ + new Coordinate(0.5, 0.5), + new Coordinate(1.5, 0.5) }); assertEquals(2, names.length); @@ -141,16 +141,16 @@ void TestFindBorderCrossing() { @Test void TestOverlappingRegion() { // Overlapping and crossing border - should return the two countries - String[] names = _builder.findBorderCrossing(new Coordinate[] { - new Coordinate(101.5,101.5), - new Coordinate(102.5,101.5) + String[] names = _builder.findBorderCrossing(new Coordinate[]{ + new Coordinate(101.5, 101.5), + new Coordinate(102.5, 101.5) }); assertEquals(2, names.length); // Overlapping but not crossing - should return only the one country - String[] names2 = _builder.findBorderCrossing(new Coordinate[] { - new Coordinate(101.5,101.5), - new Coordinate(101.75,101.5) + String[] names2 = _builder.findBorderCrossing(new Coordinate[]{ + new Coordinate(101.5, 101.5), + new Coordinate(101.75, 101.5) }); assertEquals(1, names2.length); } diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilderTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilderTest.java index 69e7907047..c2bb981ca2 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilderTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/storages/builders/WheelchairGraphStorageBuilderTest.java @@ -143,7 +143,7 @@ void TestKerbHeightFromNode() { way.setTag("highway", "crossing"); - Map> nodeTags = new HashMap<>(); + Map> nodeTags = new HashMap<>(); Map tags = new HashMap<>(); tags.put("kerb:height", "0.03"); nodeTags.put(1, tags); @@ -161,7 +161,7 @@ void TestAttachKerbHeightToCrossing() { way.setTag("footway", "crossing"); - Map> nodeTags = new HashMap<>(); + Map> nodeTags = new HashMap<>(); Map tags = new HashMap<>(); tags.put("kerb:height", "0.03"); nodeTags.put(1, tags); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtilsTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtilsTest.java index 53fe073827..bd5ea5659d 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtilsTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/graphhopper/extensions/util/EncodeUtilsTest.java @@ -18,19 +18,19 @@ void longToByteArrayTest() { @Test void byteArrayToLongTest() { // 01001001 10010110 00000010 11010010 - byte[] byteArr = {0,0,0,0,73,-106,2,-46}; + byte[] byteArr = {0, 0, 0, 0, 73, -106, 2, -46}; long value = EncodeUtils.byteArrayToLong(byteArr); assertEquals(1234567890, value); // 11101000 01101010 00000100 10011111 - byte[] byteArr2 = {-24,106,4,-97}; + byte[] byteArr2 = {-24, 106, 4, -97}; long value2 = EncodeUtils.byteArrayToLong(byteArr2); assertEquals(3899262111L, value2); // 01111100 00000000 00000000 00001100 11010011 01001100 11111000 10100000 00000001 - byte[] byteArr3 = {124,0,0,12,-45,76,-8,-96,1}; + byte[] byteArr3 = {124, 0, 0, 12, -45, 76, -8, -96, 1}; long value3 = EncodeUtils.byteArrayToLong(byteArr3); assertEquals(14101668995073L, value3); diff --git a/ors-engine/src/test/java/org/heigit/ors/routing/pathprocessors/BordersExtractorTest.java b/ors-engine/src/test/java/org/heigit/ors/routing/pathprocessors/BordersExtractorTest.java index 836ad4fa5b..5fb7e6a231 100644 --- a/ors-engine/src/test/java/org/heigit/ors/routing/pathprocessors/BordersExtractorTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/routing/pathprocessors/BordersExtractorTest.java @@ -28,12 +28,12 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; class BordersExtractorTest { - private PMap properties = new PMap(); - private final EncodingManager encodingManager= EncodingManager.create(new ORSDefaultFlagEncoderFactory().createFlagEncoder(FlagEncoderNames.CAR_ORS, properties)); + private final PMap properties = new PMap(); + private final EncodingManager encodingManager = EncodingManager.create(new ORSDefaultFlagEncoderFactory().createFlagEncoder(FlagEncoderNames.CAR_ORS, properties)); private final BordersGraphStorage _graphstorage; public BordersExtractorTest() { @@ -44,19 +44,19 @@ public BordersExtractorTest() { // (edgeId, borderType, startCountry, endCountry) - _graphstorage.setEdgeValue(1, BordersGraphStorage.CONTROLLED_BORDER, (short)1, (short)2); - _graphstorage.setEdgeValue(2, BordersGraphStorage.OPEN_BORDER, (short)3, (short)4); - _graphstorage.setEdgeValue(3, BordersGraphStorage.NO_BORDER, (short)5, (short)5); - _graphstorage.setEdgeValue(4, BordersGraphStorage.NO_BORDER, (short)5, (short)6); - _graphstorage.setEdgeValue(5, BordersGraphStorage.NO_BORDER, (short)7, (short)7); - _graphstorage.setEdgeValue(6, BordersGraphStorage.NO_BORDER, (short)7, (short)7); + _graphstorage.setEdgeValue(1, BordersGraphStorage.CONTROLLED_BORDER, (short) 1, (short) 2); + _graphstorage.setEdgeValue(2, BordersGraphStorage.OPEN_BORDER, (short) 3, (short) 4); + _graphstorage.setEdgeValue(3, BordersGraphStorage.NO_BORDER, (short) 5, (short) 5); + _graphstorage.setEdgeValue(4, BordersGraphStorage.NO_BORDER, (short) 5, (short) 6); + _graphstorage.setEdgeValue(5, BordersGraphStorage.NO_BORDER, (short) 7, (short) 7); + _graphstorage.setEdgeValue(6, BordersGraphStorage.NO_BORDER, (short) 7, (short) 7); } private VirtualEdgeIteratorState generateEdge(int id) { IntsRef intsRef = encodingManager.createEdgeFlags(); return new VirtualEdgeIteratorState(0, id, 1, 2, 10, - intsRef, "test", Helper.createPointList(51,0,51,1),false); + intsRef, "test", Helper.createPointList(51, 0, 51, 1), false); } @Test @@ -101,7 +101,7 @@ void TestAvoidCountry() { VirtualEdgeIteratorState ve2 = generateEdge(2); VirtualEdgeIteratorState ve3 = generateEdge(3); - BordersExtractor be = new BordersExtractor(_graphstorage, new int[] {2, 4}); + BordersExtractor be = new BordersExtractor(_graphstorage, new int[]{2, 4}); assertTrue(be.restrictedCountry(1)); assertTrue(be.restrictedCountry(2)); assertFalse(be.restrictedCountry(3)); @@ -113,7 +113,7 @@ void TestIsSameCountry() { VirtualEdgeIteratorState ve2 = generateEdge(2); VirtualEdgeIteratorState ve3 = generateEdge(3); - BordersExtractor be = new BordersExtractor(_graphstorage, new int[] {2, 4}); + BordersExtractor be = new BordersExtractor(_graphstorage, new int[]{2, 4}); List countries = new ArrayList<>(); countries.add(1); countries.add(2); diff --git a/ors-engine/src/test/java/org/heigit/ors/util/GeomUtilityTest.java b/ors-engine/src/test/java/org/heigit/ors/util/GeomUtilityTest.java index 96acb148ff..febf640fb4 100644 --- a/ors-engine/src/test/java/org/heigit/ors/util/GeomUtilityTest.java +++ b/ors-engine/src/test/java/org/heigit/ors/util/GeomUtilityTest.java @@ -16,7 +16,7 @@ class GeomUtilityTest { static void setUp() { pointList3D.add(41.310824, -3.164063, 113.0); pointList3D.add(45.089036, 2.900391, 250.0); - pointList3D.add(45.336702, -7.119141,244.55); + pointList3D.add(45.336702, -7.119141, 244.55); pointList3D.add(38.959409, 7.294922, 409.0); pointList3D.add(50.958427, 12.304688, 122.0); pointList3D.add(18.729502, 38.408203, 400.443); @@ -38,22 +38,22 @@ void calculateBoundingBox() { BBox bbox2D = GeomUtility.calculateBoundingBox(pointList2D); BBox bbox_fallback = GeomUtility.calculateBoundingBox(emptyPointList); - assertEquals(-35.507813,bbox3D.minLon, 0.000009); - assertEquals(38.408203,bbox3D.maxLon, 0.0000009); - assertEquals(-12.897489,bbox3D.minLat, 0.000009); - assertEquals(50.958427,bbox3D.maxLat, 0.0000009); - assertEquals(113.0,bbox3D.minEle, 0.09); - assertEquals(409.0,bbox3D.maxEle, 0.09); + assertEquals(-35.507813, bbox3D.minLon, 0.000009); + assertEquals(38.408203, bbox3D.maxLon, 0.0000009); + assertEquals(-12.897489, bbox3D.minLat, 0.000009); + assertEquals(50.958427, bbox3D.maxLat, 0.0000009); + assertEquals(113.0, bbox3D.minEle, 0.09); + assertEquals(409.0, bbox3D.maxEle, 0.09); - assertEquals(-35.507813,bbox2D.minLon, 0.000009); - assertEquals(38.408203,bbox2D.maxLon, 0.000009); - assertEquals(-12.897489,bbox2D.minLat, 0.000009); - assertEquals(50.958427,bbox2D.maxLat, 0.000009); + assertEquals(-35.507813, bbox2D.minLon, 0.000009); + assertEquals(38.408203, bbox2D.maxLon, 0.000009); + assertEquals(-12.897489, bbox2D.minLat, 0.000009); + assertEquals(50.958427, bbox2D.maxLat, 0.000009); - assertEquals(0f,bbox_fallback.minLon, 0.000009); - assertEquals(0f,bbox_fallback.maxLon, 0.000009); - assertEquals(0f,bbox_fallback.minLat, 0.000009); - assertEquals(0f,bbox_fallback.maxLat, 0.000009); + assertEquals(0f, bbox_fallback.minLon, 0.000009); + assertEquals(0f, bbox_fallback.maxLon, 0.000009); + assertEquals(0f, bbox_fallback.minLat, 0.000009); + assertEquals(0f, bbox_fallback.maxLat, 0.000009); } @Test