diff --git a/libjava/lib/src/main/java/com/mapbox/services/Constants.java b/libjava/lib/src/main/java/com/mapbox/services/Constants.java index b7b7264f5..f36518cb2 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/Constants.java +++ b/libjava/lib/src/main/java/com/mapbox/services/Constants.java @@ -4,43 +4,43 @@ public class Constants { - /** - * Package version - */ - public final static String MAPBOX_JAVA_VERSION = "2.0.0-SNAPSHOT"; - - /** - * User agent for HTTP requests - */ - public final static String HEADER_USER_AGENT = - String.format(Locale.US, "MapboxJava/%s", MAPBOX_JAVA_VERSION); - - /** - * Base URL for all API calls, not hardcoded to enable testing - */ - public final static String BASE_API_URL = "https://api.mapbox.com"; - - /** - * Constants for polyline encoding/decoding - */ - public final static int GOOGLE_PRECISION = 5; - public final static int OSRM_PRECISION_V4 = 6; - public final static int OSRM_PRECISION_V5 = 5; - - /** - * Default user for services - */ - public final static String MAPBOX_USER = "mapbox"; - - /** - * Mapbox default styles - * https://www.mapbox.com/developers/api/styles/ - */ - public final static String MAPBOX_STYLE_STREETS = "streets-v9"; - public final static String MAPBOX_STYLE_LIGHT = "light-v9"; - public final static String MAPBOX_STYLE_DARK = "dark-v9"; - public final static String MAPBOX_STYLE_OUTDOORS = "outdoors-v9"; - public final static String MAPBOX_STYLE_SATELLITE = "satellite-v9"; - public final static String MAPBOX_STYLE_SATELLITE_HYBRID = "satellite-streets-v9"; + /** + * Package version + */ + public static final String MAPBOX_JAVA_VERSION = "2.0.0-SNAPSHOT"; + + /** + * User agent for HTTP requests + */ + public static final String HEADER_USER_AGENT = + String.format(Locale.US, "MapboxJava/%s", MAPBOX_JAVA_VERSION); + + /** + * Base URL for all API calls, not hardcoded to enable testing + */ + public static final String BASE_API_URL = "https://api.mapbox.com"; + + /** + * Constants for polyline encoding/decoding + */ + public static final int GOOGLE_PRECISION = 5; + public static final int OSRM_PRECISION_V4 = 6; + public static final int OSRM_PRECISION_V5 = 5; + + /** + * Default user for services + */ + public static final String MAPBOX_USER = "mapbox"; + + /** + * Mapbox default styles + * https://www.mapbox.com/developers/api/styles/ + */ + public static final String MAPBOX_STYLE_STREETS = "streets-v9"; + public static final String MAPBOX_STYLE_LIGHT = "light-v9"; + public static final String MAPBOX_STYLE_DARK = "dark-v9"; + public static final String MAPBOX_STYLE_OUTDOORS = "outdoors-v9"; + public static final String MAPBOX_STYLE_SATELLITE = "satellite-v9"; + public static final String MAPBOX_STYLE_SATELLITE_HYBRID = "satellite-streets-v9"; } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsCriteria.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsCriteria.java index 6898e65c9..8c1efceae 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsCriteria.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsCriteria.java @@ -8,98 +8,98 @@ */ public final class DirectionsCriteria { - /** - * For car and motorcycle routing. This profile shows the fastest routes by preferring - * high-speed roads like highways. - * - * @since 1.0.0 - */ - public static final String PROFILE_DRIVING = "mapbox.driving"; + /** + * For car and motorcycle routing. This profile shows the fastest routes by preferring + * high-speed roads like highways. + * + * @since 1.0.0 + */ + public static final String PROFILE_DRIVING = "mapbox.driving"; - /** - * For pedestrian and hiking routing. This profile shows the shortest path by using sidewalks - * and trails. - * - * @since 1.0.0 - */ - public static final String PROFILE_WALKING = "mapbox.walking"; + /** + * For pedestrian and hiking routing. This profile shows the shortest path by using sidewalks + * and trails. + * + * @since 1.0.0 + */ + public static final String PROFILE_WALKING = "mapbox.walking"; - /** - * For bicycle routing. This profile shows routes that are short and safe for cyclist, avoiding - * highways and preferring streets with bike lanes. - * - * @since 1.0.0 - */ - public static final String PROFILE_CYCLING = "mapbox.cycling"; + /** + * For bicycle routing. This profile shows routes that are short and safe for cyclist, avoiding + * highways and preferring streets with bike lanes. + * + * @since 1.0.0 + */ + public static final String PROFILE_CYCLING = "mapbox.cycling"; - /** - * Format to return route instructions will be text. - * - * @since 1.0.0 - */ - public static final String INSTRUCTIONS_TEXT = "text"; + /** + * Format to return route instructions will be text. + * + * @since 1.0.0 + */ + public static final String INSTRUCTIONS_TEXT = "text"; - /** - * Format to return route instructions will be html. - * - * @since 1.0.0 - */ - public static final String INSTRUCTIONS_HTML = "html"; + /** + * Format to return route instructions will be html. + * + * @since 1.0.0 + */ + public static final String INSTRUCTIONS_HTML = "html"; - /** - * Format to return route geometry will be geojson. - * - * @since 1.0.0 - */ - public static final String GEOMETRY_GEOJSON = "geojson"; + /** + * Format to return route geometry will be geojson. + * + * @since 1.0.0 + */ + public static final String GEOMETRY_GEOJSON = "geojson"; - /** - * Format to return route geometry will be encoded polyline. - * - * @since 1.0.0 - */ - public static final String GEOMETRY_POLYLINE = "polyline"; + /** + * Format to return route geometry will be encoded polyline. + * + * @since 1.0.0 + */ + public static final String GEOMETRY_POLYLINE = "polyline"; - /** - * Use false to omit geometry from response. - * - * @since 1.0.0 - */ - public static final String GEOMETRY_FALSE = "false"; + /** + * Use false to omit geometry from response. + * + * @since 1.0.0 + */ + public static final String GEOMETRY_FALSE = "false"; - /** - * Normal case - * - * @since 1.0.0 - */ - public final static String RESPONSE_OK = "Ok"; + /** + * Normal case + * + * @since 1.0.0 + */ + public static final String RESPONSE_OK = "Ok"; - /** - * The input did not produce any matches. Features will be an empty array. - * - * @since 1.0.0 - */ - public final static String RESPONSE_NO_MATCH = "NoMatch"; + /** + * The input did not produce any matches. Features will be an empty array. + * + * @since 1.0.0 + */ + public static final String RESPONSE_NO_MATCH = "NoMatch"; - /** - * There are more than 100 points in the request. - * - * @since 1.0.0 - */ - public final static String RESPONSE_TOO_MANY_COORDINATES = "TooManyCoordinates"; + /** + * There are more than 100 points in the request. + * + * @since 1.0.0 + */ + public static final String RESPONSE_TOO_MANY_COORDINATES = "TooManyCoordinates"; - /** - * message will hold an explanation of the invalid input. - * - * @since 1.0.0 - */ - public final static String RESPONSE_INVALID_INPUT = "InvalidInput"; + /** + * message will hold an explanation of the invalid input. + * + * @since 1.0.0 + */ + public static final String RESPONSE_INVALID_INPUT = "InvalidInput"; - /** - * Profile should be mapbox.driving, mapbox.walking, or mapbox.cycling. - * - * @since 1.0.0 - */ - public final static String RESPONSE_PROFILE_NOT_FOUND = "ProfileNotFound"; + /** + * Profile should be mapbox.driving, mapbox.walking, or mapbox.cycling. + * + * @since 1.0.0 + */ + public static final String RESPONSE_PROFILE_NOT_FOUND = "ProfileNotFound"; } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsService.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsService.java index b53ac07e6..ddb5a45d6 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsService.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/DirectionsService.java @@ -15,29 +15,29 @@ */ public interface DirectionsService { - /** - * Call-based interface - * - * @param userAgent The user. - * @param profile The profile directions should use. - * @param waypoints The waypoints the route should follow. - * @param accessToken Mapbox access token. - * @param alternatives Define whether you want to recieve more then one route. - * @param instructions Define if you'd like to recieve route instructions. - * @param geometry Route geometry. - * @param steps Define if you'd like the route steps. - * @return A retrofit Call object - * @since 1.0.0 - */ - @GET("v4/directions/{profile}/{waypoints}.json") - Call getCall( - @Header("User-Agent") String userAgent, - @Path("profile") String profile, - @Path("waypoints") String waypoints, - @Query("access_token") String accessToken, - @Query("alternatives") Boolean alternatives, - @Query("instructions") String instructions, - @Query("geometry") String geometry, - @Query("steps") Boolean steps - ); + /** + * Call-based interface + * + * @param userAgent The user. + * @param profile The profile directions should use. + * @param waypoints The waypoints the route should follow. + * @param accessToken Mapbox access token. + * @param alternatives Define whether you want to recieve more then one route. + * @param instructions Define if you'd like to recieve route instructions. + * @param geometry Route geometry. + * @param steps Define if you'd like the route steps. + * @return A retrofit Call object + * @since 1.0.0 + */ + @GET("v4/directions/{profile}/{waypoints}.json") + Call getCall( + @Header("User-Agent") String userAgent, + @Path("profile") String profile, + @Path("waypoints") String waypoints, + @Query("access_token") String accessToken, + @Query("alternatives") Boolean alternatives, + @Query("instructions") String instructions, + @Query("geometry") String geometry, + @Query("steps") Boolean steps + ); } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/MapboxDirections.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/MapboxDirections.java index d7feb2a8c..a9d69b5e5 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/MapboxDirections.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/MapboxDirections.java @@ -27,366 +27,370 @@ */ public class MapboxDirections extends MapboxService { - private Builder builder = null; - private DirectionsService service = null; - private Call call = null; + private Builder builder = null; + private DirectionsService service = null; + private Call call = null; + + // Allows testing + private String baseUrl = Constants.BASE_API_URL; + + /** + * Mapbox builder + * + * @param builder {@link Builder} + * @since 1.0.0 + */ + public MapboxDirections(Builder builder) { + this.builder = builder; + } + + /** + * Used internally. + * + * @param baseUrl {@link String} baseUrl + * @since 1.0.0 + */ + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + /** + * Used internally. + * + * @return DirectionsService + * @since 1.0.0 + */ + public DirectionsService getService() { + // No need to recreate it + if (service != null) { + return service; + } + + Retrofit retrofit = new Retrofit.Builder() + .client(getOkHttpClient()) + .baseUrl(baseUrl) + .addConverterFactory(GsonConverterFactory.create()) + .build(); + service = retrofit.create(DirectionsService.class); + return service; + } + + /** + * Used internally. + * + * @return The directions response call. + * @since 1.0.0 + */ + public Call getCall() { + // No need to recreate it + if (call != null) { + return call; + } - // Allows testing - private String baseUrl = Constants.BASE_API_URL; + call = getService().getCall( + getHeaderUserAgent(), + builder.getProfile(), + builder.getWaypoints(), + builder.getAccessToken(), + builder.isAlternatives(), + builder.getInstructions(), + builder.getGeometry(), + builder.isSteps()); + + return call; + } + + /** + * Execute the call + * + * @return The Directions v4 response + * @throws IOException Signals that an I/O exception of some sort has occurred. + * @since 1.0.0 + */ + @Override + public Response executeCall() throws IOException { + return getCall().execute(); + } + + /** + * Execute the call + * + * @param callback A Retrofit callback. + * @since 1.0.0 + */ + @Override + public void enqueueCall(Callback callback) { + getCall().enqueue(callback); + } + + /** + * Cancel the call + * + * @since 1.0.0 + */ + @Override + public void cancelCall() { + getCall().cancel(); + } + + /** + * clone the call + * + * @return cloned call + * @since 1.0.0 + */ + @Override + public Call cloneCall() { + return getCall().clone(); + } + + /** + * Directions v4 builder + * + * @since 1.0.0 + */ + public static class Builder extends MapboxBuilder { + + private String accessToken; + private String profile; + private List waypoints; + private Waypoint origin; + private Waypoint destination; + private Boolean alternatives; + private String instructions; + private String geometry; + private Boolean steps; /** - * Mapbox builder + * Required to call when building {@link com.mapbox.services.directions.v4.MapboxDirections.Builder}. * - * @param builder {@link Builder} + * @param accessToken Mapbox access token, You must have a Mapbox account inorder to use + * this library. * @since 1.0.0 */ - public MapboxDirections(Builder builder) { - this.builder = builder; + @Override + public Builder setAccessToken(String accessToken) { + this.accessToken = accessToken; + return this; } /** - * Used internally. + * Specify what routing profile you'd like: driving, walking, or cycling. * - * @param baseUrl {@link String} baseUrl + * @param profile {@link DirectionsCriteria#PROFILE_DRIVING}, + * {@link DirectionsCriteria#PROFILE_CYCLING}, or {@link DirectionsCriteria#PROFILE_WALKING} + * @return Builder * @since 1.0.0 */ - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; + public Builder setProfile(String profile) { + this.profile = profile; + return this; } /** - * Used internally. + * If you have more then one destination, call this method passing in a list of all + * waypoints including origin and final destination. * - * @return DirectionsService + * @param waypoints List including all {@link Waypoint} you'd line to include in route. + * @return Builder * @since 1.0.0 */ - public DirectionsService getService() { - // No need to recreate it - if (service != null) return service; - - Retrofit retrofit = new Retrofit.Builder() - .client(getOkHttpClient()) - .baseUrl(baseUrl) - .addConverterFactory(GsonConverterFactory.create()) - .build(); - service = retrofit.create(DirectionsService.class); - return service; + public Builder setWaypoints(List waypoints) { + this.waypoints = waypoints; + return this; } /** - * Used internally. + * Origin of the destination. * - * @return The directions response call. + * @param origin {@link Waypoint} of origin. + * @return Builder * @since 1.0.0 */ - public Call getCall() { - // No need to recreate it - if (call != null) return call; - - call = getService().getCall( - getHeaderUserAgent(), - builder.getProfile(), - builder.getWaypoints(), - builder.getAccessToken(), - builder.isAlternatives(), - builder.getInstructions(), - builder.getGeometry(), - builder.isSteps()); - - return call; + public Builder setOrigin(Waypoint origin) { + this.origin = origin; + return this; } /** - * Execute the call + * Final destination of your route, call this only if you have one destination, otherwise, + * use {@link #setWaypoints(List)} * - * @return The Directions v4 response - * @throws IOException Signals that an I/O exception of some sort has occurred. + * @param destination {@link Waypoint} of destination. + * @return Builder * @since 1.0.0 */ - @Override - public Response executeCall() throws IOException { - return getCall().execute(); + public Builder setDestination(Waypoint destination) { + this.destination = destination; + return this; } /** - * Execute the call + * Optionally, call if you'd like to receive alternative routes besides just one. * - * @param callback A Retrofit callback. + * @param alternatives true if you'd like alternative routes, else false. + * @return Builder * @since 1.0.0 */ - @Override - public void enqueueCall(Callback callback) { - getCall().enqueue(callback); + public Builder setAlternatives(Boolean alternatives) { + this.alternatives = alternatives; + return this; } /** - * Cancel the call + * Optionally, call if you'd like to receive human-readable instructions. * + * @param instructions {@link DirectionsCriteria#INSTRUCTIONS_TEXT} or + * {@link DirectionsCriteria#INSTRUCTIONS_HTML} + * @return Builder * @since 1.0.0 */ - @Override - public void cancelCall() { - getCall().cancel(); + public Builder setInstructions(String instructions) { + this.instructions = instructions; + return this; + } + + /** + * Optionally, call with the format you'd like the route geometry to be in. + * + * @param geometry {@link DirectionsCriteria#GEOMETRY_GEOJSON}, + * {@link DirectionsCriteria#GEOMETRY_POLYLINE}, or {@link DirectionsCriteria#GEOMETRY_FALSE} + * @return Builder + * @since 1.0.0 + */ + public Builder setGeometry(String geometry) { + this.geometry = geometry; + return this; } /** - * clone the call + * Optionally, call if you'd like to include step information within route. * - * @return cloned call + * @param steps true if you'd like step information. + * @return Builder + * @since 1.0.0 + */ + public Builder setSteps(Boolean steps) { + this.steps = steps; + return this; + } + + /** + * @return your Mapbox access token. * @since 1.0.0 */ @Override - public Call cloneCall() { - return getCall().clone(); + public String getAccessToken() { + return accessToken; + } + + /** + * @return {@link DirectionsCriteria#PROFILE_DRIVING}, + * {@link DirectionsCriteria#PROFILE_CYCLING}, or {@link DirectionsCriteria#PROFILE_WALKING} + * @since 1.0.0 + */ + public String getProfile() { + return profile; } /** - * Directions v4 builder + * @return List including all {@link Waypoint} within route. + * @since 1.0.0 + */ + public String getWaypoints() { + String waypointsFormatted = ""; + + // Set origin and destination + if (origin != null && destination != null) { + waypoints = new ArrayList<>(Arrays.asList(origin, destination)); + } + + // Empty list + if (waypoints == null || waypoints.size() == 0) { + return waypointsFormatted; + } + + // Convert to {lon},{lat} coordinate pairs + List pieces = new ArrayList<>(); + for (Waypoint waypoint : waypoints) { + pieces.add(String.format(Locale.US, "%f,%f", + waypoint.getLongitude(), + waypoint.getLatitude())); + } + + // The waypoints parameter should be a semicolon-separated list of locations to visit + waypointsFormatted = TextUtils.join(";", pieces.toArray()); + return waypointsFormatted; + } + + /** + * @return routes origin {@link Waypoint}. + * @since 1.0.0 + */ + public Waypoint getOrigin() { + return origin; + } + + /** + * @return routes final destination {@link Waypoint}. + * @since 1.0.0 + */ + public Waypoint getDestination() { + return destination; + } + + /** + * @return true if you {@link #setAlternatives(Boolean)} to true. + * @since 1.0.0 + */ + public Boolean isAlternatives() { + return alternatives; + } + + /** + * @return {@link DirectionsCriteria#INSTRUCTIONS_TEXT} or + * {@link DirectionsCriteria#INSTRUCTIONS_HTML} + * @since 1.0.0 + */ + public String getInstructions() { + return instructions; + } + + /** + * @return {@link DirectionsCriteria#GEOMETRY_GEOJSON}, + * {@link DirectionsCriteria#GEOMETRY_POLYLINE}, or {@link DirectionsCriteria#GEOMETRY_FALSE} + * @since 1.0.0 + */ + public String getGeometry() { + return geometry; + } + + /** + * @return true if you requested step information in {@link #setSteps(Boolean)}. + * @since 1.0.0 + */ + public Boolean isSteps() { + return steps; + } + + /** + * Build the MapboxDirections * + * @return {@link MapboxDirections} + * @throws ServicesException Generic Exception for all things directions. * @since 1.0.0 */ - public static class Builder extends MapboxBuilder { - - private String accessToken; - private String profile; - private List waypoints; - private Waypoint origin; - private Waypoint destination; - private Boolean alternatives; - private String instructions; - private String geometry; - private Boolean steps; - - /** - * Required to call when building {@link com.mapbox.services.directions.v4.MapboxDirections.Builder}. - * - * @param accessToken Mapbox access token, You must have a Mapbox account inorder to use - * this library. - * @since 1.0.0 - */ - @Override - public Builder setAccessToken(String accessToken) { - this.accessToken = accessToken; - return this; - } - - /** - * Specify what routing profile you'd like: driving, walking, or cycling. - * - * @param profile {@link DirectionsCriteria#PROFILE_DRIVING}, - * {@link DirectionsCriteria#PROFILE_CYCLING}, or {@link DirectionsCriteria#PROFILE_WALKING} - * @return Builder - * @since 1.0.0 - */ - public Builder setProfile(String profile) { - this.profile = profile; - return this; - } - - /** - * If you have more then one destination, call this method passing in a list of all - * waypoints including origin and final destination. - * - * @param waypoints List including all {@link Waypoint} you'd line to include in route. - * @return Builder - * @since 1.0.0 - */ - public Builder setWaypoints(List waypoints) { - this.waypoints = waypoints; - return this; - } - - /** - * Origin of the destination. - * - * @param origin {@link Waypoint} of origin. - * @return Builder - * @since 1.0.0 - */ - public Builder setOrigin(Waypoint origin) { - this.origin = origin; - return this; - } - - /** - * Final destination of your route, call this only if you have one destination, otherwise, - * use {@link #setWaypoints(List)} - * - * @param destination {@link Waypoint} of destination. - * @return Builder - * @since 1.0.0 - */ - public Builder setDestination(Waypoint destination) { - this.destination = destination; - return this; - } - - /** - * Optionally, call if you'd like to receive alternative routes besides just one. - * - * @param alternatives true if you'd like alternative routes, else false. - * @return Builder - * @since 1.0.0 - */ - public Builder setAlternatives(Boolean alternatives) { - this.alternatives = alternatives; - return this; - } - - /** - * Optionally, call if you'd like to receive human-readable instructions. - * - * @param instructions {@link DirectionsCriteria#INSTRUCTIONS_TEXT} or - * {@link DirectionsCriteria#INSTRUCTIONS_HTML} - * @return Builder - * @since 1.0.0 - */ - public Builder setInstructions(String instructions) { - this.instructions = instructions; - return this; - } - - /** - * Optionally, call with the format you'd like the route geometry to be in. - * - * @param geometry {@link DirectionsCriteria#GEOMETRY_GEOJSON}, - * {@link DirectionsCriteria#GEOMETRY_POLYLINE}, or {@link DirectionsCriteria#GEOMETRY_FALSE} - * @return Builder - * @since 1.0.0 - */ - public Builder setGeometry(String geometry) { - this.geometry = geometry; - return this; - } - - /** - * Optionally, call if you'd like to include step information within route. - * - * @param steps true if you'd like step information. - * @return Builder - * @since 1.0.0 - */ - public Builder setSteps(Boolean steps) { - this.steps = steps; - return this; - } - - /** - * @return your Mapbox access token. - * @since 1.0.0 - */ - @Override - public String getAccessToken() { - return accessToken; - } - - /** - * @return {@link DirectionsCriteria#PROFILE_DRIVING}, - * {@link DirectionsCriteria#PROFILE_CYCLING}, or {@link DirectionsCriteria#PROFILE_WALKING} - * @since 1.0.0 - */ - public String getProfile() { - return profile; - } - - /** - * @return List including all {@link Waypoint} within route. - * @since 1.0.0 - */ - public String getWaypoints() { - String waypointsFormatted = ""; - - // Set origin and destination - if (origin != null && destination != null) { - waypoints = new ArrayList<>(Arrays.asList(origin, destination)); - } - - // Empty list - if (waypoints == null || waypoints.size() == 0) { - return waypointsFormatted; - } - - // Convert to {lon},{lat} coordinate pairs - List pieces = new ArrayList<>(); - for (Waypoint waypoint : waypoints) { - pieces.add(String.format(Locale.US, "%f,%f", - waypoint.getLongitude(), - waypoint.getLatitude())); - } - - // The waypoints parameter should be a semicolon-separated list of locations to visit - waypointsFormatted = TextUtils.join(";", pieces.toArray()); - return waypointsFormatted; - } - - /** - * @return routes origin {@link Waypoint}. - * @since 1.0.0 - */ - public Waypoint getOrigin() { - return origin; - } - - /** - * @return routes final destination {@link Waypoint}. - * @since 1.0.0 - */ - public Waypoint getDestination() { - return destination; - } - - /** - * @return true if you {@link #setAlternatives(Boolean)} to true. - * @since 1.0.0 - */ - public Boolean isAlternatives() { - return alternatives; - } - - /** - * @return {@link DirectionsCriteria#INSTRUCTIONS_TEXT} or - * {@link DirectionsCriteria#INSTRUCTIONS_HTML} - * @since 1.0.0 - */ - public String getInstructions() { - return instructions; - } - - /** - * @return {@link DirectionsCriteria#GEOMETRY_GEOJSON}, - * {@link DirectionsCriteria#GEOMETRY_POLYLINE}, or {@link DirectionsCriteria#GEOMETRY_FALSE} - * @since 1.0.0 - */ - public String getGeometry() { - return geometry; - } - - /** - * @return true if you requested step information in {@link #setSteps(Boolean)}. - * @since 1.0.0 - */ - public Boolean isSteps() { - return steps; - } - - /** - * Build the MapboxDirections - * - * @return {@link MapboxDirections} - * @throws ServicesException Generic Exception for all things directions. - * @since 1.0.0 - */ - @Override - public MapboxDirections build() throws ServicesException { - validateAccessToken(accessToken); - - // We force the geometry to be a polyline to make the request more efficient. - // We have utils to transform polylines into a LineString easily. - geometry = DirectionsCriteria.GEOMETRY_POLYLINE; - - return new MapboxDirections(this); - } + @Override + public MapboxDirections build() throws ServicesException { + validateAccessToken(accessToken); + + // We force the geometry to be a polyline to make the request more efficient. + // We have utils to transform polylines into a LineString easily. + geometry = DirectionsCriteria.GEOMETRY_POLYLINE; + return new MapboxDirections(this); } + } + } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsFeature.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsFeature.java index 8d67bf3ab..d70511410 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsFeature.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsFeature.java @@ -8,61 +8,61 @@ */ public class DirectionsFeature { - private String type; - private FeatureGeometry geometry; - private FeatureProperties properties; + private String type; + private FeatureGeometry geometry; + private FeatureProperties properties; - /** - * The type of the GeoJSON object. - * - * @return string type. - * @since 1.0.0 - */ - public String getType() { - return type; - } + /** + * The type of the GeoJSON object. + * + * @return string type. + * @since 1.0.0 + */ + public String getType() { + return type; + } - /** - * @param type The type of the GeoJSON object. - * @since 1.0.0 - */ - public void setType(String type) { - this.type = type; - } + /** + * @param type The type of the GeoJSON object. + * @since 1.0.0 + */ + public void setType(String type) { + this.type = type; + } - /** - * {@link FeatureGeometry} object contains type and the coordinates. - * - * @return {@link FeatureGeometry} object. - * @since 1.0.0 - */ - public FeatureGeometry getGeometry() { - return geometry; - } + /** + * {@link FeatureGeometry} object contains type and the coordinates. + * + * @return {@link FeatureGeometry} object. + * @since 1.0.0 + */ + public FeatureGeometry getGeometry() { + return geometry; + } - /** - * @param geometry {@link FeatureGeometry} object contains type and the coordinates. - * @since 1.0.0 - */ - public void setGeometry(FeatureGeometry geometry) { - this.geometry = geometry; - } + /** + * @param geometry {@link FeatureGeometry} object contains type and the coordinates. + * @since 1.0.0 + */ + public void setGeometry(FeatureGeometry geometry) { + this.geometry = geometry; + } - /** - * Properties describing the point. This includes, at a minimum, a name. - * - * @return {@link FeatureProperties} object. - * @since 1.0.0 - */ - public FeatureProperties getProperties() { - return properties; - } + /** + * Properties describing the point. This includes, at a minimum, a name. + * + * @return {@link FeatureProperties} object. + * @since 1.0.0 + */ + public FeatureProperties getProperties() { + return properties; + } - /** - * @param properties Properties describing the point. This includes, at a minimum, a name. - * @since 1.0.0 - */ - public void setProperties(FeatureProperties properties) { - this.properties = properties; - } + /** + * @param properties Properties describing the point. This includes, at a minimum, a name. + * @since 1.0.0 + */ + public void setProperties(FeatureProperties properties) { + this.properties = properties; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsResponse.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsResponse.java index 3a4989b34..ebfcb123f 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsResponse.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsResponse.java @@ -10,90 +10,90 @@ */ public class DirectionsResponse { - private DirectionsFeature origin; - private DirectionsFeature destination; - private List waypoints; - private List routes; + private DirectionsFeature origin; + private DirectionsFeature destination; + private List waypoints; + private List routes; - public DirectionsResponse() { - waypoints = new ArrayList<>(); - routes = new ArrayList<>(); - } + public DirectionsResponse() { + waypoints = new ArrayList<>(); + routes = new ArrayList<>(); + } - /** - * Gives details about the origin of the route. - * - * @return {@link DirectionsFeature} object. - * @since 1.0.0 - */ - public DirectionsFeature getOrigin() { - return origin; - } + /** + * Gives details about the origin of the route. + * + * @return {@link DirectionsFeature} object. + * @since 1.0.0 + */ + public DirectionsFeature getOrigin() { + return origin; + } - /** - * @param origin Details about the origin of the route. - * @since 1.0.0 - */ - public void setOrigin(DirectionsFeature origin) { - this.origin = origin; - } + /** + * @param origin Details about the origin of the route. + * @since 1.0.0 + */ + public void setOrigin(DirectionsFeature origin) { + this.origin = origin; + } - /** - * Gives details about the destination of the route. - * - * @return {@link DirectionsFeature} object. - * @since 1.0.0 - */ - public DirectionsFeature getDestination() { - return destination; - } + /** + * Gives details about the destination of the route. + * + * @return {@link DirectionsFeature} object. + * @since 1.0.0 + */ + public DirectionsFeature getDestination() { + return destination; + } - /** - * @param destination Details about the destination of the route. - * @since 1.0.0 - */ - public void setDestination(DirectionsFeature destination) { - this.destination = destination; - } + /** + * @param destination Details about the destination of the route. + * @since 1.0.0 + */ + public void setDestination(DirectionsFeature destination) { + this.destination = destination; + } - /** - * A List of {@link DirectionsFeature} objects representing intermediate waypoints along route, - * if any exist. If you request directions with more then two waypoints (origin and destination) - * addition information about those intermediate points will be given here in a List object. - * - * @return List of {@link DirectionsFeature} objects. - * @since 1.0.0 - */ - public List getWaypoints() { - return waypoints; - } + /** + * A List of {@link DirectionsFeature} objects representing intermediate waypoints along route, + * if any exist. If you request directions with more then two waypoints (origin and destination) + * addition information about those intermediate points will be given here in a List object. + * + * @return List of {@link DirectionsFeature} objects. + * @since 1.0.0 + */ + public List getWaypoints() { + return waypoints; + } - /** - * @param waypoints List of {@link DirectionsFeature} objects. - * @since 1.0.0 - */ - public void setWaypoints(List waypoints) { - this.waypoints = waypoints; - } + /** + * @param waypoints List of {@link DirectionsFeature} objects. + * @since 1.0.0 + */ + public void setWaypoints(List waypoints) { + this.waypoints = waypoints; + } - /** - * List containing all the different route options. It's ordered by descending recommendation - * rank. In other words, object 0 in the List is the highest recommended route. if you - * setAlternatives to false (default is true) in your builder this should always be a List of - * size 1. - * - * @return List of {@link DirectionsRoute} objects. - * @since 1.0.0 - */ - public List getRoutes() { - return routes; - } + /** + * List containing all the different route options. It's ordered by descending recommendation + * rank. In other words, object 0 in the List is the highest recommended route. if you + * setAlternatives to false (default is true) in your builder this should always be a List of + * size 1. + * + * @return List of {@link DirectionsRoute} objects. + * @since 1.0.0 + */ + public List getRoutes() { + return routes; + } - /** - * @param routes List of {@link DirectionsRoute} objects. - * @since 1.0.0 - */ - public void setRoutes(List routes) { - this.routes = routes; - } + /** + * @param routes List of {@link DirectionsRoute} objects. + * @since 1.0.0 + */ + public void setRoutes(List routes) { + this.routes = routes; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsRoute.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsRoute.java index 6734adb6b..a6c52d917 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsRoute.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/DirectionsRoute.java @@ -12,115 +12,115 @@ */ public class DirectionsRoute { - private int distance; - private int duration; - private String summary; - private String geometry; - private List steps; - - public DirectionsRoute() { - steps = new ArrayList<>(); - } - - /** - * The distance traveled from origin to destination. - * - * @return An integer number with unit meters. - * @since 1.0.0 - */ - public int getDistance() { - return distance; - } - - /** - * @param distance The distance traveled from origin to destination. - * @since 1.0.0 - */ - public void setDistance(int distance) { - this.distance = distance; - } - - /** - * The estimated travel time from origin to destination. - * - * @return an integer number with unit seconds. - * @since 1.0.0 - */ - public int getDuration() { - return duration; - } - - /** - * @param duration The estimated travel time from origin to destination. - * @since 1.0.0 - */ - public void setDuration(int duration) { - this.duration = duration; - } - - /** - * A short, human-readable summary of the route (e.g., major roads traversed). - * - * @return a string briefly describing route. - * @since 1.0.0 - */ - public String getSummary() { - return summary; - } - - /** - * @param summary A short, human-readable summary of the route (e.g., major roads traversed). - * @since 1.0.0 - */ - public void setSummary(String summary) { - this.summary = summary; - } - - /** - * Gives the geometry of the route. Commonly used to draw the route on the map view. - * - * @return encoded polyline with precision 6. - * @since 1.0.0 - */ - public String getGeometry() { - return geometry; - } - - /** - * @param geometry The geometry of the route. - * @since 1.0.0 - */ - public void setGeometry(String geometry) { - this.geometry = geometry; - } - - /** - * Steps gives you the route instructions. - * - * @return List of {@link RouteStep} objects. - * @since 1.0.0 - */ - public List getSteps() { - return steps; - } - - /** - * @param steps The route instructions. - * @since 1.0.0 - */ - public void setSteps(List steps) { - this.steps = steps; - } - - /** - * Gets a GeoJSON LineString which can be used to get route coordinates useful for - * drawing on a map view. - * - * @param precision of encoded polyline. - * @return GeoJSON LineString. - * @since 1.0.0 - */ - public LineString asLineString(int precision) { - return LineString.fromPolyline(getGeometry(), precision); - } + private int distance; + private int duration; + private String summary; + private String geometry; + private List steps; + + public DirectionsRoute() { + steps = new ArrayList<>(); + } + + /** + * The distance traveled from origin to destination. + * + * @return An integer number with unit meters. + * @since 1.0.0 + */ + public int getDistance() { + return distance; + } + + /** + * @param distance The distance traveled from origin to destination. + * @since 1.0.0 + */ + public void setDistance(int distance) { + this.distance = distance; + } + + /** + * The estimated travel time from origin to destination. + * + * @return an integer number with unit seconds. + * @since 1.0.0 + */ + public int getDuration() { + return duration; + } + + /** + * @param duration The estimated travel time from origin to destination. + * @since 1.0.0 + */ + public void setDuration(int duration) { + this.duration = duration; + } + + /** + * A short, human-readable summary of the route (e.g., major roads traversed). + * + * @return a string briefly describing route. + * @since 1.0.0 + */ + public String getSummary() { + return summary; + } + + /** + * @param summary A short, human-readable summary of the route (e.g., major roads traversed). + * @since 1.0.0 + */ + public void setSummary(String summary) { + this.summary = summary; + } + + /** + * Gives the geometry of the route. Commonly used to draw the route on the map view. + * + * @return encoded polyline with precision 6. + * @since 1.0.0 + */ + public String getGeometry() { + return geometry; + } + + /** + * @param geometry The geometry of the route. + * @since 1.0.0 + */ + public void setGeometry(String geometry) { + this.geometry = geometry; + } + + /** + * Steps gives you the route instructions. + * + * @return List of {@link RouteStep} objects. + * @since 1.0.0 + */ + public List getSteps() { + return steps; + } + + /** + * @param steps The route instructions. + * @since 1.0.0 + */ + public void setSteps(List steps) { + this.steps = steps; + } + + /** + * Gets a GeoJSON LineString which can be used to get route coordinates useful for + * drawing on a map view. + * + * @param precision of encoded polyline. + * @return GeoJSON LineString. + * @since 1.0.0 + */ + public LineString asLineString(int precision) { + return LineString.fromPolyline(getGeometry(), precision); + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureGeometry.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureGeometry.java index 8a06116ba..cf1f510c7 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureGeometry.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureGeometry.java @@ -10,53 +10,53 @@ */ public class FeatureGeometry { - private String type; - private List coordinates; - - /** - * Builder - * - * @since 1.0.0 - */ - public FeatureGeometry() { - coordinates = new ArrayList<>(); - } - - /** - * Gives GeoJSON geometry type. - * - * @return string naming GeoJSON geometry type. - * @since 1.0.0 - */ - public String getType() { - return type; - } - - /** - * @param type The GeoJSON geometry type. - * @since 1.0.0 - */ - public void setType(String type) { - this.type = type; - } - - /** - * Gives the coordinate of the point. Longitude will always be first (index 0) in list and - * latitude will be second (index 1). - * - * @return List of Double objects containing a point with longitude and latitude values. - * @since 1.0.0 - */ - public List getCoordinates() { - return coordinates; - } - - /** - * @param coordinates List of Double objects containing a point with longitude and latitude - * values. - * @since 1.0.0 - */ - public void setCoordinates(List coordinates) { - this.coordinates = coordinates; - } + private String type; + private List coordinates; + + /** + * Builder + * + * @since 1.0.0 + */ + public FeatureGeometry() { + coordinates = new ArrayList<>(); + } + + /** + * Gives GeoJSON geometry type. + * + * @return string naming GeoJSON geometry type. + * @since 1.0.0 + */ + public String getType() { + return type; + } + + /** + * @param type The GeoJSON geometry type. + * @since 1.0.0 + */ + public void setType(String type) { + this.type = type; + } + + /** + * Gives the coordinate of the point. Longitude will always be first (index 0) in list and + * latitude will be second (index 1). + * + * @return List of Double objects containing a point with longitude and latitude values. + * @since 1.0.0 + */ + public List getCoordinates() { + return coordinates; + } + + /** + * @param coordinates List of Double objects containing a point with longitude and latitude + * values. + * @since 1.0.0 + */ + public void setCoordinates(List coordinates) { + this.coordinates = coordinates; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureProperties.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureProperties.java index 7822467b1..9a21f032c 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureProperties.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/FeatureProperties.java @@ -7,23 +7,23 @@ */ public class FeatureProperties { - private String name; + private String name; - /** - * Gives the name of the closest street to the {@link DirectionsFeature} point. - * - * @return String name. - * @since 1.0.0 - */ - public String getName() { - return name; - } + /** + * Gives the name of the closest street to the {@link DirectionsFeature} point. + * + * @return String name. + * @since 1.0.0 + */ + public String getName() { + return name; + } - /** - * @param name String name. - * @since 1.0.0 - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name String name. + * @since 1.0.0 + */ + public void setName(String name) { + this.name = name; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/ManeuverPoint.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/ManeuverPoint.java index c15026600..08eb5ccce 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/ManeuverPoint.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/ManeuverPoint.java @@ -11,53 +11,53 @@ */ public class ManeuverPoint { - private String type; - private List coordinates; - - /** - * Builder - * - * @since 1.0.0 - */ - public ManeuverPoint() { - coordinates = new ArrayList<>(); - } - - /** - * Gives the GeoJSON geometry type. - * - * @return String naming type. - * @since 1.0.0 - */ - public String getType() { - return type; - } - - /** - * @param type String naming type. - * @since 1.0.0 - */ - public void setType(String type) { - this.type = type; - } - - /** - * Gives the coordinate of the Point. Longitude will always be first (index 0) in list and - * latitude will be second (index 1). - * - * @return List of Double objects containing a point with longitude and latitude values. - * @since 1.0.0 - */ - public List getCoordinates() { - return coordinates; - } - - /** - * @param coordinates List of Double objects containing a point with longitude and latitude - * values. - * @since 1.0.0 - */ - public void setCoordinates(List coordinates) { - this.coordinates = coordinates; - } + private String type; + private List coordinates; + + /** + * Builder + * + * @since 1.0.0 + */ + public ManeuverPoint() { + coordinates = new ArrayList<>(); + } + + /** + * Gives the GeoJSON geometry type. + * + * @return String naming type. + * @since 1.0.0 + */ + public String getType() { + return type; + } + + /** + * @param type String naming type. + * @since 1.0.0 + */ + public void setType(String type) { + this.type = type; + } + + /** + * Gives the coordinate of the Point. Longitude will always be first (index 0) in list and + * latitude will be second (index 1). + * + * @return List of Double objects containing a point with longitude and latitude values. + * @since 1.0.0 + */ + public List getCoordinates() { + return coordinates; + } + + /** + * @param coordinates List of Double objects containing a point with longitude and latitude + * values. + * @since 1.0.0 + */ + public void setCoordinates(List coordinates) { + this.coordinates = coordinates; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/RouteStep.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/RouteStep.java index b10aa9c17..b71470e25 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/RouteStep.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/RouteStep.java @@ -10,120 +10,120 @@ */ public class RouteStep { - private int distance; - private int duration; - @SerializedName("wayName") - private String wayName; - private String direction; - private double heading; - private StepManeuver maneuver; + private int distance; + private int duration; + @SerializedName("wayName") + private String wayName; + private String direction; + private double heading; + private StepManeuver maneuver; - /** - * The distance of travel from the maneuver to the subsequent step. - * - * @return integer distance given in meters. - * @since 1.0.0 - */ - public int getDistance() { - return distance; - } + /** + * The distance of travel from the maneuver to the subsequent step. + * + * @return integer distance given in meters. + * @since 1.0.0 + */ + public int getDistance() { + return distance; + } - /** - * @param distance integer distance given in meters. - * @since 1.0.0 - */ - public void setDistance(int distance) { - this.distance = distance; - } + /** + * @param distance integer distance given in meters. + * @since 1.0.0 + */ + public void setDistance(int distance) { + this.distance = distance; + } - /** - * The estimated travel time from the maneuver to the subsequent step. - * - * @return integer number given in seconds. - * @since 1.0.0 - */ - public int getDuration() { - return duration; - } + /** + * The estimated travel time from the maneuver to the subsequent step. + * + * @return integer number given in seconds. + * @since 1.0.0 + */ + public int getDuration() { + return duration; + } - /** - * @param duration integer number given in seconds. - * @since 1.0.0 - */ - public void setDuration(int duration) { - this.duration = duration; - } + /** + * @param duration integer number given in seconds. + * @since 1.0.0 + */ + public void setDuration(int duration) { + this.duration = duration; + } - /** - * The name of the way along which travel proceeds. - * - * @return string containing a name. - * @since 1.0.0 - */ - public String getWayName() { - return wayName; - } + /** + * The name of the way along which travel proceeds. + * + * @return string containing a name. + * @since 1.0.0 + */ + public String getWayName() { + return wayName; + } - /** - * @param wayName string containing a name. - * @since 1.0.0 - */ - public void setWayName(String wayName) { - this.wayName = wayName; - } + /** + * @param wayName string containing a name. + * @since 1.0.0 + */ + public void setWayName(String wayName) { + this.wayName = wayName; + } - /** - * The approximate cardinal direction of travel following the maneuver. Typically one of the - * following: 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. - * - * @return string containing abbreviated cardinal direction. - * @since 1.0.0 - */ - public String getDirection() { - return direction; - } + /** + * The approximate cardinal direction of travel following the maneuver. Typically one of the + * following: 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. + * + * @return string containing abbreviated cardinal direction. + * @since 1.0.0 + */ + public String getDirection() { + return direction; + } - /** - * @param direction string containing abbreviated cardinal direction. - * @since 1.0.0 - */ - public void setDirection(String direction) { - this.direction = direction; - } + /** + * @param direction string containing abbreviated cardinal direction. + * @since 1.0.0 + */ + public void setDirection(String direction) { + this.direction = direction; + } - /** - * The clockwise angle from true north to the direction of travel immediately following the maneuver. - * - * @return double value ranging from 0 to 359. - * @since 1.0.0 - */ - public double getHeading() { - return heading; - } + /** + * The clockwise angle from true north to the direction of travel immediately following the maneuver. + * + * @return double value ranging from 0 to 359. + * @since 1.0.0 + */ + public double getHeading() { + return heading; + } - /** - * @param heading Double value ranging from 0 to 359. - * @since 1.0.0 - */ - public void setHeading(double heading) { - this.heading = heading; - } + /** + * @param heading Double value ranging from 0 to 359. + * @since 1.0.0 + */ + public void setHeading(double heading) { + this.heading = heading; + } - /** - * A {@link StepManeuver} object representing the step maneuver. - * - * @return a {@link StepManeuver} object. - * @since 1.0.0 - */ - public StepManeuver getManeuver() { - return maneuver; - } + /** + * A {@link StepManeuver} object representing the step maneuver. + * + * @return a {@link StepManeuver} object. + * @since 1.0.0 + */ + public StepManeuver getManeuver() { + return maneuver; + } - /** - * @param maneuver A {@link StepManeuver} object. - * @since 1.0.0 - */ - public void setManeuver(StepManeuver maneuver) { - this.maneuver = maneuver; - } + /** + * @param maneuver A {@link StepManeuver} object. + * @since 1.0.0 + */ + public void setManeuver(StepManeuver maneuver) { + this.maneuver = maneuver; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/StepManeuver.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/StepManeuver.java index eda00b569..11fea28ee 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/StepManeuver.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/StepManeuver.java @@ -7,89 +7,89 @@ */ public class StepManeuver { - private String type; - private ManeuverPoint location; - private String instruction; - private String mode; + private String type; + private ManeuverPoint location; + private String instruction; + private String mode; - /** - * A specific string describing the type of maneuver. The following types are currently used: - * continue, bear right, turn right, sharp right, u-turn, sharp left, turn left, bear left, - * waypoint, depart, enter roundabout, and arrive. Warning, new maneuver types may be introduced - * in the future however, so check here - * to ensure you don't miss any. - * - * @return string with possibly one of the maneuvers given above. - * @since 1.0.0 - */ - public String getType() { - return type; - } + /** + * A specific string describing the type of maneuver. The following types are currently used: + * continue, bear right, turn right, sharp right, u-turn, sharp left, turn left, bear left, + * waypoint, depart, enter roundabout, and arrive. Warning, new maneuver types may be introduced + * in the future however, so check here + * to ensure you don't miss any. + * + * @return string with possibly one of the maneuvers given above. + * @since 1.0.0 + */ + public String getType() { + return type; + } - /** - * @param type string with possibly one of the maneuvers given above. - * @since 1.0.0 - */ - public void setType(String type) { - this.type = type; - } + /** + * @param type string with possibly one of the maneuvers given above. + * @since 1.0.0 + */ + public void setType(String type) { + this.type = type; + } - /** - * {@link ManeuverPoint} object containing type and the coordinate. - * - * @return {@link ManeuverPoint} object. - * @since 1.0.0 - */ - public ManeuverPoint getLocation() { - return location; - } + /** + * {@link ManeuverPoint} object containing type and the coordinate. + * + * @return {@link ManeuverPoint} object. + * @since 1.0.0 + */ + public ManeuverPoint getLocation() { + return location; + } - /** - * @param location {@link ManeuverPoint} object. - * @since 1.0.0 - */ - public void setLocation(ManeuverPoint location) { - this.location = location; - } + /** + * @param location {@link ManeuverPoint} object. + * @since 1.0.0 + */ + public void setLocation(ManeuverPoint location) { + this.location = location; + } - /** - * Human-readable string describing the maneuver. typically combines {@link #getType()} and a - * street name. if within {@code MapboxDirections.Builder} you setInstructions to HTML, you'll - * relieve the instructions in HTML format. - * - * @return string typically the length of a sentence giving next maneuver instruction. - * @since 1.0.0 - */ - public String getInstruction() { - return instruction; - } + /** + * Human-readable string describing the maneuver. typically combines {@link #getType()} and a + * street name. if within {@code MapboxDirections.Builder} you setInstructions to HTML, you'll + * relieve the instructions in HTML format. + * + * @return string typically the length of a sentence giving next maneuver instruction. + * @since 1.0.0 + */ + public String getInstruction() { + return instruction; + } - /** - * @param instruction string typically the length of a sentence giving next maneuver instruction. - * @since 1.0.0 - */ - public void setInstruction(String instruction) { - this.instruction = instruction; - } + /** + * @param instruction string typically the length of a sentence giving next maneuver instruction. + * @since 1.0.0 + */ + public void setInstruction(String instruction) { + this.instruction = instruction; + } - /** - * A string signifying the mode of transportation. Possible values can be: - *

For driving: driving, ferry, movable bridge, unaccessible. - *

For walking: walking, ferry, unaccessible. - *

For cycling: cycling, walking, ferry, train, movable bridge, unaccessible. - * - * @return string with possibly one of the values given above. - * @since 1.0.0 - */ - public String getMode() { - return mode; - } + /** + * A string signifying the mode of transportation. Possible values can be: + *

For driving: driving, ferry, movable bridge, unaccessible. + *

For walking: walking, ferry, unaccessible. + *

For cycling: cycling, walking, ferry, train, movable bridge, unaccessible. + * + * @return string with possibly one of the values given above. + * @since 1.0.0 + */ + public String getMode() { + return mode; + } - /** - * @param mode string with possibly one of the values given above. - * @since 1.0.0 - */ - public void setMode(String mode) { - this.mode = mode; - } + /** + * @param mode string with possibly one of the values given above. + * @since 1.0.0 + */ + public void setMode(String mode) { + this.mode = mode; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/Waypoint.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/Waypoint.java index 7c876f3a7..467b879eb 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/Waypoint.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v4/models/Waypoint.java @@ -7,54 +7,54 @@ */ public class Waypoint { - private double latitude; - private double longitude; + private double latitude; + private double longitude; - /** - * Construct a location with a longitude latitude pair. - * - * @param longitude double value ranging from -180.0 to 180.0. - * @param latitude double value ranging from -90.0 to 90.0. - * @since 1.0.0 - */ - public Waypoint(double longitude, double latitude) { - this.longitude = longitude; - this.latitude = latitude; - } + /** + * Construct a location with a longitude latitude pair. + * + * @param longitude double value ranging from -180.0 to 180.0. + * @param latitude double value ranging from -90.0 to 90.0. + * @since 1.0.0 + */ + public Waypoint(double longitude, double latitude) { + this.longitude = longitude; + this.latitude = latitude; + } - /** - * The latitude of the location. - * - * @return double value ranging from -90.0 to 90.0. - * @since 1.0.0 - */ - public double getLatitude() { - return latitude; - } + /** + * The latitude of the location. + * + * @return double value ranging from -90.0 to 90.0. + * @since 1.0.0 + */ + public double getLatitude() { + return latitude; + } - /** - * @param latitude double value ranging from -90.0 to 90.0. - * @since 1.0.0 - */ - public void setLatitude(double latitude) { - this.latitude = latitude; - } + /** + * @param latitude double value ranging from -90.0 to 90.0. + * @since 1.0.0 + */ + public void setLatitude(double latitude) { + this.latitude = latitude; + } - /** - * The longitude of the location. - * - * @return double value ranging from -180.0 to 180.0. - * @since 1.0.0 - */ - public double getLongitude() { - return longitude; - } + /** + * The longitude of the location. + * + * @return double value ranging from -180.0 to 180.0. + * @since 1.0.0 + */ + public double getLongitude() { + return longitude; + } - /** - * @param longitude double value ranging from -180.0 to 180.0. - * @since 1.0.0 - */ - public void setLongitude(double longitude) { - this.longitude = longitude; - } + /** + * @param longitude double value ranging from -180.0 to 180.0. + * @since 1.0.0 + */ + public void setLongitude(double longitude) { + this.longitude = longitude; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsCriteria.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsCriteria.java index 2f076175c..f49dbda95 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsCriteria.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsCriteria.java @@ -7,93 +7,93 @@ */ public class DirectionsCriteria { - public static final String PROFILE_DEFAULT_USER = "mapbox"; + public static final String PROFILE_DEFAULT_USER = "mapbox"; - /** - * For car and motorcycle routing. This profile shows the fastest routes by preferring - * high-speed roads like highways. - * - * @since 1.0.0 - */ - public static final String PROFILE_DRIVING = "driving"; + /** + * For car and motorcycle routing. This profile shows the fastest routes by preferring + * high-speed roads like highways. + * + * @since 1.0.0 + */ + public static final String PROFILE_DRIVING = "driving"; - /** - * For pedestrian and hiking routing. This profile shows the shortest path by using sidewalks - * and trails. - * - * @since 1.0.0 - */ - public static final String PROFILE_WALKING = "walking"; + /** + * For pedestrian and hiking routing. This profile shows the shortest path by using sidewalks + * and trails. + * + * @since 1.0.0 + */ + public static final String PROFILE_WALKING = "walking"; - /** - * For bicycle routing. This profile shows routes that are short and safe for cyclist, avoiding - * highways and preferring streets with bike lanes. - * - * @since 1.0.0 - */ - public static final String PROFILE_CYCLING = "cycling"; + /** + * For bicycle routing. This profile shows routes that are short and safe for cyclist, avoiding + * highways and preferring streets with bike lanes. + * + * @since 1.0.0 + */ + public static final String PROFILE_CYCLING = "cycling"; - /** - * Format to return route geometry will be encoded polyline. - * - * @since 1.0.0 - */ - public final static String GEOMETRY_POLYLINE = "polyline"; + /** + * Format to return route geometry will be encoded polyline. + * + * @since 1.0.0 + */ + public static final String GEOMETRY_POLYLINE = "polyline"; - /** - * Format to return route geometry will be geojson. Note that this isn't supported by the SDK. - * - * @since 1.0.0 - */ - private final static String GEOMETRY_GEOJSON = "geojson"; + /** + * Format to return route geometry will be geojson. Note that this isn't supported by the SDK. + * + * @since 1.0.0 + */ + private static final String GEOMETRY_GEOJSON = "geojson"; - /** - * A simplified version of the {@link #OVERVIEW_FULL} geometry. If not specified simplified is the default. - * - * @since 1.0.0 - */ - public final static String OVERVIEW_SIMPLIFIED = "simplified"; + /** + * A simplified version of the {@link #OVERVIEW_FULL} geometry. If not specified simplified is the default. + * + * @since 1.0.0 + */ + public static final String OVERVIEW_SIMPLIFIED = "simplified"; - /** - * The most detailed geometry available. - * - * @since 1.0.0 - */ - public final static String OVERVIEW_FULL = "full"; + /** + * The most detailed geometry available. + * + * @since 1.0.0 + */ + public static final String OVERVIEW_FULL = "full"; - /** - * No overview geometry. - * - * @since 1.0.0 - */ - public final static String OVERVIEW_FALSE = "false"; + /** + * No overview geometry. + * + * @since 1.0.0 + */ + public static final String OVERVIEW_FALSE = "false"; - /** - * Server responds with no errors. - * - * @since 1.0.0 - */ - public final static String RESPONSE_OK = "Ok"; + /** + * Server responds with no errors. + * + * @since 1.0.0 + */ + public static final String RESPONSE_OK = "Ok"; - /** - * There was no route found for the given query. - * - * @since 1.0.0 - */ - public final static String RESPONSE_NO_ROUTE = "NoRoute"; + /** + * There was no route found for the given query. + * + * @since 1.0.0 + */ + public static final String RESPONSE_NO_ROUTE = "NoRoute"; - /** - * Use a valid profile as described above. - * - * @since 1.0.0 - */ - public final static String RESPONSE_PROFILE_NOT_FOUND = "ProfileNotFound"; + /** + * Use a valid profile as described above. + * + * @since 1.0.0 + */ + public static final String RESPONSE_PROFILE_NOT_FOUND = "ProfileNotFound"; - /** - * The given request was not valid. - * - * @since 1.0.0 - */ - public final static String RESPONSE_INVALID_INPUT = "InvalidInput"; + /** + * The given request was not valid. + * + * @since 1.0.0 + */ + public static final String RESPONSE_INVALID_INPUT = "InvalidInput"; } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsService.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsService.java index 2368c1f39..e17cda42d 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsService.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/DirectionsService.java @@ -15,36 +15,36 @@ */ public interface DirectionsService { - /** - * Call-based interface - * - * @param userAgent The user. - * @param user The user. - * @param profile The profile directions should use. - * @param coordinates The coordinates the route should follow. - * @param accessToken Mapbox access token. - * @param alternatives Define whether you want to recieve more then one route. - * @param geometries Route geometry. - * @param overview Route full, simplified, etc. - * @param radiuses start at the most efficient point within the radius. - * @param steps Define if you'd like the route steps. - * @param continueStraight Define whether the route should continue straight even if the route - * will be slower. - * @return A retrofit Call object - * @since 1.0.0 - */ - @GET("directions/v5/{user}/{profile}/{coordinates}") - Call getCall( - @Header("User-Agent") String userAgent, - @Path("user") String user, - @Path("profile") String profile, - @Path("coordinates") String coordinates, - @Query("access_token") String accessToken, - @Query("alternatives") Boolean alternatives, - @Query("geometries") String geometries, - @Query("overview") String overview, - @Query("radiuses") String radiuses, - @Query("steps") Boolean steps, - @Query("continue_straight") Boolean continueStraight - ); + /** + * Call-based interface + * + * @param userAgent The user. + * @param user The user. + * @param profile The profile directions should use. + * @param coordinates The coordinates the route should follow. + * @param accessToken Mapbox access token. + * @param alternatives Define whether you want to recieve more then one route. + * @param geometries Route geometry. + * @param overview Route full, simplified, etc. + * @param radiuses start at the most efficient point within the radius. + * @param steps Define if you'd like the route steps. + * @param continueStraight Define whether the route should continue straight even if the route + * will be slower. + * @return A retrofit Call object + * @since 1.0.0 + */ + @GET("directions/v5/{user}/{profile}/{coordinates}") + Call getCall( + @Header("User-Agent") String userAgent, + @Path("user") String user, + @Path("profile") String profile, + @Path("coordinates") String coordinates, + @Query("access_token") String accessToken, + @Query("alternatives") Boolean alternatives, + @Query("geometries") String geometries, + @Query("overview") String overview, + @Query("radiuses") String radiuses, + @Query("steps") Boolean steps, + @Query("continue_straight") Boolean continueStraight + ); } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/MapboxDirections.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/MapboxDirections.java index 444962c1d..4cbdd13d3 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/MapboxDirections.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/MapboxDirections.java @@ -28,447 +28,455 @@ */ public class MapboxDirections extends MapboxService { - private Builder builder = null; - private DirectionsService service = null; - private Call call = null; - - // Allows testing - private String baseUrl = Constants.BASE_API_URL; + private Builder builder = null; + private DirectionsService service = null; + private Call call = null; + + // Allows testing + private String baseUrl = Constants.BASE_API_URL; + + private MapboxDirections(Builder builder) { + this.builder = builder; + } + + /** + * Used internally. + * + * @param baseUrl the baseURL + * @since 1.0.0 + */ + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + private DirectionsService getService() { + // No need to recreate it + if (service != null) { + return service; + } - private MapboxDirections(Builder builder) { - this.builder = builder; + // Retrofit instance + Retrofit retrofit = new Retrofit.Builder() + .client(getOkHttpClient()) + .baseUrl(baseUrl) + .addConverterFactory(GsonConverterFactory.create()) + .build(); + + // Directions service + service = retrofit.create(DirectionsService.class); + return service; + } + + private Call getCall() { + // No need to recreate it + if (call != null) { + return call; } + call = getService().getCall( + getHeaderUserAgent(), + builder.getUser(), + builder.getProfile(), + builder.getCoordinates(), + builder.getAccessToken(), + builder.isAlternatives(), + builder.getGeometries(), + builder.getOverview(), + builder.getRadiuses(), + builder.isSteps(), + builder.isContinueStraight()); + + // Done + return call; + } + + /** + * Execute the call + * + * @return The Directions v5 response + * @throws IOException Signals that an I/O exception of some sort has occurred. + * @since 1.0.0 + */ + @Override + public Response executeCall() throws IOException { + return getCall().execute(); + } + + /** + * Execute the call + * + * @param callback A Retrofit callback. + * @since 1.0.0 + */ + @Override + public void enqueueCall(Callback callback) { + getCall().enqueue(callback); + } + + /** + * Cancel the call + * + * @since 1.0.0 + */ + @Override + public void cancelCall() { + getCall().cancel(); + } + + /** + * clone the call + * + * @return cloned call + * @since 1.0.0 + */ + @Override + public Call cloneCall() { + return getCall().clone(); + } + + /** + * Directions v5 builder + * + * @since 1.0.0 + */ + public static class Builder extends MapboxBuilder { + + // We use `Boolean` instead of `boolean` to allow unset (null) values. + private String user = null; + private String profile = null; + private ArrayList coordinates = null; + private String accessToken = null; + private Boolean alternatives = null; + private String geometries = null; + private String overview = null; + private double[] radiuses = null; + private Boolean steps = null; + private Boolean continueStraight = null; + /** - * Used internally. + * Constructor * - * @param baseUrl the baseURL * @since 1.0.0 */ - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; + public Builder() { + // Set defaults + this.user = DirectionsCriteria.PROFILE_DEFAULT_USER; + + // We only support polyline encoded geometries to reduce the size of the response. + // If we need the corresponding LineString object, this SDK can do the decoding with + // LineString.fromPolyline(String polyline, int precision). + this.geometries = DirectionsCriteria.GEOMETRY_POLYLINE; } - private DirectionsService getService() { - // No need to recreate it - if (service != null) return service; + /* + * Setters + */ - // Retrofit instance - Retrofit retrofit = new Retrofit.Builder() - .client(getOkHttpClient()) - .baseUrl(baseUrl) - .addConverterFactory(GsonConverterFactory.create()) - .build(); + /** + * @param user User string + * @return Builder + * @since 1.0.0 + */ + public Builder setUser(String user) { + this.user = user; + return this; + } + + /** + * @param profile Profile string + * @return Builder + * @since 1.0.0 + */ + public Builder setProfile(String profile) { + this.profile = profile; + return this; + } - // Directions service - service = retrofit.create(DirectionsService.class); - return service; + /** + * Set the list of coordinates for the directions service. If you've previously set an + * origin with setOrigin() or a destination with setDestination(), those will be + * overridden. + * + * @param coordinates List of {@link Position} giving origin and destination(s) coordinates. + * @return Builder + * @since 1.0.0 + */ + public Builder setCoordinates(ArrayList coordinates) { + this.coordinates = coordinates; + return this; } - private Call getCall() { - // No need to recreate it - if (call != null) return call; - - call = getService().getCall( - getHeaderUserAgent(), - builder.getUser(), - builder.getProfile(), - builder.getCoordinates(), - builder.getAccessToken(), - builder.isAlternatives(), - builder.getGeometries(), - builder.getOverview(), - builder.getRadiuses(), - builder.isSteps(), - builder.isContinueStraight()); - - // Done - return call; + /** + * Inserts the specified position at the beginning of the coordinates list. If you've + * set other coordinates previously with setCoordinates() those elements are kept + * and their index will be moved up by one (the coordinates are moved to the right). + * + * @param origin {@link Position} of route origin. + * @return Builder + * @since 1.0.0 + */ + public Builder setOrigin(Position origin) { + if (coordinates == null) { + coordinates = new ArrayList<>(); + } + + // The default behavior of ArrayList is to inserts the specified element at the + // specified position in this list (beginning) and to shift the element currently at + // that position (if any) and any subsequent elements to the right (adds one to + // their indices) + coordinates.add(0, origin); + + return this; } /** - * Execute the call + * Appends the specified destination to the end of the coordinates list. If you've + * set other coordinates previously with setCoordinates() those elements are kept + * and the destination is added at the end of the list. * - * @return The Directions v5 response - * @throws IOException Signals that an I/O exception of some sort has occurred. + * @param destination {@link Position} of route destination. + * @return Builder * @since 1.0.0 */ - @Override - public Response executeCall() throws IOException { - return getCall().execute(); + public Builder setDestination(Position destination) { + if (coordinates == null) { + coordinates = new ArrayList<>(); + } + + // The default behavior for ArrayList is to appends the specified element + // to the end of this list. + coordinates.add(destination); + + return this; } /** - * Execute the call + * Required to call when building {@link Builder}. * - * @param callback A Retrofit callback. + * @param accessToken Mapbox access token, You must have a Mapbox account inorder to use + * this library. + * @return Builder * @since 1.0.0 */ @Override - public void enqueueCall(Callback callback) { - getCall().enqueue(callback); + public Builder setAccessToken(String accessToken) { + this.accessToken = accessToken; + return this; } /** - * Cancel the call + * Optionally, call if you'd like to receive alternative routes besides just one. * + * @param alternatives true if you'd like alternative routes, else false. + * @return Builder * @since 1.0.0 */ - @Override - public void cancelCall() { - getCall().cancel(); + public Builder setAlternatives(Boolean alternatives) { + this.alternatives = alternatives; + return this; + } + + /** + * Optionally, set whether you want the route geometry to be full, simplified, etc. + * + * @param overview String defining type of overview you'd like the API to give. Use one of + * the constants. + * @return Builder + * @since 1.0.0 + */ + public Builder setOverview(String overview) { + this.overview = overview; + return this; + } + + /** + * Optionally, set a radius values for the coordinates to allow for a more flexible origin + * and destinations point locations. + * + * @param radiuses double array containing the radiuses + * @return Builder + */ + public Builder setRadiuses(double[] radiuses) { + this.radiuses = radiuses; + return this; + } + + /** + * Optionally, call if you'd like to include step information within route. + * + * @param steps true if you'd like step information. + * @return Builder + * @since 1.0.0 + */ + public Builder setSteps(Boolean steps) { + this.steps = steps; + return this; } /** - * clone the call + * Toggle whether you want the route to always continue straight toward the next destination + * or allow for backtracking. * - * @return cloned call + * @param continueStraight boolean true if you want to always continue straight, else false. + * @return Builder + * @since 1.0.0 + */ + public Builder setContinueStraight(Boolean continueStraight) { + this.continueStraight = continueStraight; + return this; + } + + /* + * Getters, they return the value in a format ready for the API to consume + */ + + /** + * @return the user as String + * @since 1.0.0 + */ + public String getUser() { + return user; + } + + /** + * @return {@link com.mapbox.services.directions.v4.DirectionsCriteria#PROFILE_DRIVING}, + * {@link com.mapbox.services.directions.v4.DirectionsCriteria#PROFILE_CYCLING}, + * or {@link com.mapbox.services.directions.v4.DirectionsCriteria#PROFILE_WALKING} + * @since 1.0.0 + */ + public String getProfile() { + return profile; + } + + /** + * The coordinates parameter denotes between which points routing happens. The coordinates + * must be in the format: + *

+ * {longitude},{latitude};{longitude},{latitude}[;{longitude},{latitude} ...] + *

+ * - Each coordinate is a pair of a longitude float and latitude float, which are separated by a , + * - Coordinates are separated by a ; from each other + * - A query must at minimum have 2 coordinates and may at maximum have 25 coordinates + * + * @return String containing coordinates formatted. + * @since 1.0.0 + */ + public String getCoordinates() { + List coordinatesFormatted = new ArrayList<>(); + for (Position coordinate : coordinates) { + coordinatesFormatted.add(String.format(Locale.US, "%f,%f", + coordinate.getLongitude(), + coordinate.getLatitude())); + } + + return TextUtils.join(";", coordinatesFormatted.toArray()); + } + + /** + * @return your Mapbox access token. * @since 1.0.0 */ @Override - public Call cloneCall() { - return getCall().clone(); + public String getAccessToken() { + return accessToken; } /** - * Directions v5 builder + * @return true if you {@link #setAlternatives(Boolean)} to true. + * @since 1.0.0 + */ + public Boolean isAlternatives() { + return alternatives; + } + + /** + * @return {@link com.mapbox.services.directions.v4.DirectionsCriteria#GEOMETRY_GEOJSON}, + * {@link com.mapbox.services.directions.v4.DirectionsCriteria#GEOMETRY_POLYLINE}, + * or {@link com.mapbox.services.directions.v4.DirectionsCriteria#GEOMETRY_FALSE} + * @since 1.0.0 + */ + public String getGeometries() { + return geometries; + } + + /** + * @return The overview, full, simplied, etc. + * @since 1.0.0 + */ + public String getOverview() { + return overview; + } + + /** + * Radiuses indicate how far from a coordinate a routeable way is searched. They + * are indicated like this: + *

+ * ?radiuses={radius};{radius}}[;{radius} ...]. + *

+ * If no routeble way can be found within the serach radius, a NoRoute error will be returned. + * - Radiuses are separated by a , + * - Each radius must be of a value {@code float >= 0} in meters or unlimited (default) + * - There must be as many radiuses as there are coordinates + * - It is possible to not specify radiuses via ;;, which result in the same behaviour as setting unlimited * + * @return String containing formatted radiuses. * @since 1.0.0 */ - public static class Builder extends MapboxBuilder { - - // We use `Boolean` instead of `boolean` to allow unset (null) values. - private String user = null; - private String profile = null; - private ArrayList coordinates = null; - private String accessToken = null; - private Boolean alternatives = null; - private String geometries = null; - private String overview = null; - private double[] radiuses = null; - private Boolean steps = null; - private Boolean continueStraight = null; - - /** - * Constructor - * - * @since 1.0.0 - */ - public Builder() { - // Set defaults - this.user = DirectionsCriteria.PROFILE_DEFAULT_USER; - - // We only support polyline encoded geometries to reduce the size of the response. - // If we need the corresponding LineString object, this SDK can do the decoding with - // LineString.fromPolyline(String polyline, int precision). - this.geometries = DirectionsCriteria.GEOMETRY_POLYLINE; - } - - /* - * Setters - */ - - /** - * @param user User string - * @return Builder - * @since 1.0.0 - */ - public Builder setUser(String user) { - this.user = user; - return this; - } - - /** - * @param profile Profile string - * @return Builder - * @since 1.0.0 - */ - public Builder setProfile(String profile) { - this.profile = profile; - return this; - } - - /** - * Set the list of coordinates for the directions service. If you've previously set an - * origin with setOrigin() or a destination with setDestination(), those will be - * overridden. - * - * @param coordinates List of {@link Position} giving origin and destination(s) coordinates. - * @return Builder - * @since 1.0.0 - */ - public Builder setCoordinates(ArrayList coordinates) { - this.coordinates = coordinates; - return this; - } - - /** - * Inserts the specified position at the beginning of the coordinates list. If you've - * set other coordinates previously with setCoordinates() those elements are kept - * and their index will be moved up by one (the coordinates are moved to the right). - * - * @param origin {@link Position} of route origin. - * @return Builder - * @since 1.0.0 - */ - public Builder setOrigin(Position origin) { - if (coordinates == null) { - coordinates = new ArrayList<>(); - } - - // The default behavior of ArrayList is to inserts the specified element at the - // specified position in this list (beginning) and to shift the element currently at - // that position (if any) and any subsequent elements to the right (adds one to - // their indices) - coordinates.add(0, origin); - - return this; - } - - /** - * Appends the specified destination to the end of the coordinates list. If you've - * set other coordinates previously with setCoordinates() those elements are kept - * and the destination is added at the end of the list. - * - * @param destination {@link Position} of route destination. - * @return Builder - * @since 1.0.0 - */ - public Builder setDestination(Position destination) { - if (coordinates == null) { - coordinates = new ArrayList<>(); - } - - // The default behavior for ArrayList is to appends the specified element - // to the end of this list. - coordinates.add(destination); - - return this; - } - - /** - * Required to call when building {@link Builder}. - * - * @param accessToken Mapbox access token, You must have a Mapbox account inorder to use - * this library. - * @return Builder - * @since 1.0.0 - */ - @Override - public Builder setAccessToken(String accessToken) { - this.accessToken = accessToken; - return this; - } - - /** - * Optionally, call if you'd like to receive alternative routes besides just one. - * - * @param alternatives true if you'd like alternative routes, else false. - * @return Builder - * @since 1.0.0 - */ - public Builder setAlternatives(Boolean alternatives) { - this.alternatives = alternatives; - return this; - } - - /** - * Optionally, set whether you want the route geometry to be full, simplified, etc. - * - * @param overview String defining type of overview you'd like the API to give. Use one of - * the constants. - * @return Builder - * @since 1.0.0 - */ - public Builder setOverview(String overview) { - this.overview = overview; - return this; - } - - /** - * Optionally, set a radius values for the coordinates to allow for a more flexible origin - * and destinations point locations. - * - * @param radiuses double array containing the radiuses - * @return Builder - */ - public Builder setRadiuses(double[] radiuses) { - this.radiuses = radiuses; - return this; - } - - /** - * Optionally, call if you'd like to include step information within route. - * - * @param steps true if you'd like step information. - * @return Builder - * @since 1.0.0 - */ - public Builder setSteps(Boolean steps) { - this.steps = steps; - return this; - } - - /** - * Toggle whether you want the route to always continue straight toward the next destination - * or allow for backtracking. - * - * @param continueStraight boolean true if you want to always continue straight, else false. - * @return Builder - * @since 1.0.0 - */ - public Builder setContinueStraight(Boolean continueStraight) { - this.continueStraight = continueStraight; - return this; - } - - /* - * Getters, they return the value in a format ready for the API to consume - */ - - /** - * @return the user as String - * @since 1.0.0 - */ - public String getUser() { - return user; - } - - /** - * @return {@link com.mapbox.services.directions.v4.DirectionsCriteria#PROFILE_DRIVING}, - * {@link com.mapbox.services.directions.v4.DirectionsCriteria#PROFILE_CYCLING}, or {@link com.mapbox.services.directions.v4.DirectionsCriteria#PROFILE_WALKING} - * @since 1.0.0 - */ - public String getProfile() { - return profile; - } - - /** - * The coordinates parameter denotes between which points routing happens. The coordinates - * must be in the format: - *

- * {longitude},{latitude};{longitude},{latitude}[;{longitude},{latitude} ...] - *

- * - Each coordinate is a pair of a longitude float and latitude float, which are separated by a , - * - Coordinates are separated by a ; from each other - * - A query must at minimum have 2 coordinates and may at maximum have 25 coordinates - * - * @return String containing coordinates formatted. - * @since 1.0.0 - */ - public String getCoordinates() { - List coordinatesFormatted = new ArrayList<>(); - for (Position coordinate : coordinates) { - coordinatesFormatted.add(String.format(Locale.US, "%f,%f", - coordinate.getLongitude(), - coordinate.getLatitude())); - } - - return TextUtils.join(";", coordinatesFormatted.toArray()); - } - - /** - * @return your Mapbox access token. - * @since 1.0.0 - */ - @Override - public String getAccessToken() { - return accessToken; - } - - /** - * @return true if you {@link #setAlternatives(Boolean)} to true. - * @since 1.0.0 - */ - public Boolean isAlternatives() { - return alternatives; - } - - /** - * @return {@link com.mapbox.services.directions.v4.DirectionsCriteria#GEOMETRY_GEOJSON}, - * {@link com.mapbox.services.directions.v4.DirectionsCriteria#GEOMETRY_POLYLINE}, or {@link com.mapbox.services.directions.v4.DirectionsCriteria#GEOMETRY_FALSE} - * @since 1.0.0 - */ - public String getGeometries() { - return geometries; - } - - /** - * @return The overview, full, simplied, etc. - * @since 1.0.0 - */ - public String getOverview() { - return overview; - } - - /** - * Radiuses indicate how far from a coordinate a routeable way is searched. They - * are indicated like this: - *

- * ?radiuses={radius};{radius}}[;{radius} ...]. - *

- * If no routeble way can be found within the serach radius, a NoRoute error will be returned. - * - Radiuses are separated by a , - * - Each radius must be of a value {@code float >= 0} in meters or unlimited (default) - * - There must be as many radiuses as there are coordinates - * - It is possible to not specify radiuses via ;;, which result in the same behaviour as setting unlimited - * - * @return String containing formatted radiuses. - * @since 1.0.0 - */ - public String getRadiuses() { - if (radiuses == null || radiuses.length == 0) return null; - - String[] radiusesFormatted = new String[radiuses.length]; - for (int i = 0; i < radiuses.length; i++) { - radiusesFormatted[i] = String.format(Locale.US, "%f", radiuses[i]); - } - - return TextUtils.join(";", radiusesFormatted); - } - - /** - * @return true if you requested step information in {@link #setSteps(Boolean)}. - * @since 1.0.0 - */ - public Boolean isSteps() { - return steps; - } - - /** - * Determine whether the route's been set to continue straight or not. - * - * @return true if continuing straight, otherwise false. - * @since 1.0.0 - */ - public Boolean isContinueStraight() { - return continueStraight; - } - - /** - * Build method - * - * @return MapboxDirections - * @throws ServicesException Generic Exception for all things directions. - * @since 1.0.0 - */ - @Override - public MapboxDirections build() throws ServicesException { - validateAccessToken(accessToken); - - if (coordinates == null || coordinates.size() < 2) { - throw new ServicesException( - "You should provide at least two coordinates (from/to)."); - } - - if (radiuses != null && radiuses.length != coordinates.size()) { - throw new ServicesException( - "There must be as many radiuses as there are coordinates."); - } - - return new MapboxDirections(this); - } + public String getRadiuses() { + if (radiuses == null || radiuses.length == 0) { + return null; + } + String[] radiusesFormatted = new String[radiuses.length]; + for (int i = 0; i < radiuses.length; i++) { + radiusesFormatted[i] = String.format(Locale.US, "%f", radiuses[i]); + } + + return TextUtils.join(";", radiusesFormatted); } + /** + * @return true if you requested step information in {@link #setSteps(Boolean)}. + * @since 1.0.0 + */ + public Boolean isSteps() { + return steps; + } + + /** + * Determine whether the route's been set to continue straight or not. + * + * @return true if continuing straight, otherwise false. + * @since 1.0.0 + */ + public Boolean isContinueStraight() { + return continueStraight; + } + + /** + * Build method + * + * @return MapboxDirections + * @throws ServicesException Generic Exception for all things directions. + * @since 1.0.0 + */ + @Override + public MapboxDirections build() throws ServicesException { + validateAccessToken(accessToken); + + if (coordinates == null || coordinates.size() < 2) { + throw new ServicesException( + "You should provide at least two coordinates (from/to)."); + } + + if (radiuses != null && radiuses.length != coordinates.size()) { + throw new ServicesException( + "There must be as many radiuses as there are coordinates."); + } + + return new MapboxDirections(this); + } + + } + } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsResponse.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsResponse.java index 2e4317b51..40d641c8e 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsResponse.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsResponse.java @@ -9,59 +9,59 @@ */ public class DirectionsResponse { - private String code; - private List routes; - private List waypoints; + private String code; + private List routes; + private List waypoints; - public DirectionsResponse(List routes, List waypoints) { - this.routes = routes; - this.waypoints = waypoints; - } + public DirectionsResponse(List routes, List waypoints) { + this.routes = routes; + this.waypoints = waypoints; + } - /** - * String indicating the state of the response. This is a separate code than the HTTP - * status code. - * - * @return "Ok", "NoRoute", "ProfileNotFound", or "InvalidInput". - * @since 1.0.0 - */ - public String getCode() { - return code; - } + /** + * String indicating the state of the response. This is a separate code than the HTTP + * status code. + * + * @return "Ok", "NoRoute", "ProfileNotFound", or "InvalidInput". + * @since 1.0.0 + */ + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - /** - * List with Waypoints of locations snapped to the road and path network and appear in the List - * in the order of the input coordinates. - * - * @return List of {@link DirectionsWaypoint} objects. - * @since 1.0.0 - */ - public List getWaypoints() { - return waypoints; - } + /** + * List with Waypoints of locations snapped to the road and path network and appear in the List + * in the order of the input coordinates. + * + * @return List of {@link DirectionsWaypoint} objects. + * @since 1.0.0 + */ + public List getWaypoints() { + return waypoints; + } - public void setWaypoints(List waypoints) { - this.waypoints = waypoints; - } + public void setWaypoints(List waypoints) { + this.waypoints = waypoints; + } - /** - * List containing all the different route options. It's ordered by descending recommendation - * rank. In other words, object 0 in the List is the highest recommended route. if you don't - * setAlternatives to true (default is false) in your builder this should always be a List of - * size 1. - * - * @return List of {@link DirectionsRoute} objects. - * @since 1.0.0 - */ - public List getRoutes() { - return routes; - } + /** + * List containing all the different route options. It's ordered by descending recommendation + * rank. In other words, object 0 in the List is the highest recommended route. if you don't + * setAlternatives to true (default is false) in your builder this should always be a List of + * size 1. + * + * @return List of {@link DirectionsRoute} objects. + * @since 1.0.0 + */ + public List getRoutes() { + return routes; + } - public void setRoutes(List routes) { - this.routes = routes; - } + public void setRoutes(List routes) { + this.routes = routes; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsRoute.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsRoute.java index 6335d3625..9f8ebbc13 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsRoute.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsRoute.java @@ -9,48 +9,48 @@ */ public class DirectionsRoute { - private double distance; - private double duration; - private String geometry; - private List legs; + private double distance; + private double duration; + private String geometry; + private List legs; - /** - * The distance traveled from origin to destination. - * - * @return a double number with unit meters. - * @since 1.0.0 - */ - public double getDistance() { - return distance; - } + /** + * The distance traveled from origin to destination. + * + * @return a double number with unit meters. + * @since 1.0.0 + */ + public double getDistance() { + return distance; + } - /** - * The estimated travel time from origin to destination. - * - * @return a double number with unit seconds. - * @since 1.0.0 - */ - public double getDuration() { - return duration; - } + /** + * The estimated travel time from origin to destination. + * + * @return a double number with unit seconds. + * @since 1.0.0 + */ + public double getDuration() { + return duration; + } - /** - * Gives the geometry of the route. Commonly used to draw the route on the map view. - * - * @return An encoded polyline string. - * @since 1.0.0 - */ - public String getGeometry() { - return geometry; - } + /** + * Gives the geometry of the route. Commonly used to draw the route on the map view. + * + * @return An encoded polyline string. + * @since 1.0.0 + */ + public String getGeometry() { + return geometry; + } - /** - * A Leg is a route between only two waypoints - * - * @return List of {@link RouteLeg} objects. - * @since 1.0.0 - */ - public List getLegs() { - return legs; - } + /** + * A Leg is a route between only two waypoints + * + * @return List of {@link RouteLeg} objects. + * @since 1.0.0 + */ + public List getLegs() { + return legs; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsWaypoint.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsWaypoint.java index 4fd56d680..50eb88a2b 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsWaypoint.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/DirectionsWaypoint.java @@ -9,33 +9,33 @@ */ public class DirectionsWaypoint { - private String name; - private double[] location; + private String name; + private double[] location; - /** - * @return String with the name of the way the coordinate snapped to. - * @since 1.0.0 - */ - public String getName() { - return name; - } + /** + * @return String with the name of the way the coordinate snapped to. + * @since 1.0.0 + */ + public String getName() { + return name; + } - /** - * @return double array of [longitude, latitude] for the snapped coordinate. - * @since 1.0.0 - */ - public double[] getLocation() { - return location; - } + /** + * @return double array of [longitude, latitude] for the snapped coordinate. + * @since 1.0.0 + */ + public double[] getLocation() { + return location; + } - /** - * Converts double array {@link #getLocation()} to a {@link Position}. You'll typically want to - * use this format instead of {@link #getLocation()} as it's easier to work with. - * - * @return {@link Position}. - * @since 1.0.0 - */ - public Position asPosition() { - return Position.fromCoordinates(location[0], location[1]); - } + /** + * Converts double array {@link #getLocation()} to a {@link Position}. You'll typically want to + * use this format instead of {@link #getLocation()} as it's easier to work with. + * + * @return {@link Position}. + * @since 1.0.0 + */ + public Position asPosition() { + return Position.fromCoordinates(location[0], location[1]); + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/LegStep.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/LegStep.java index 7f391497a..35706799b 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/LegStep.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/LegStep.java @@ -9,73 +9,73 @@ */ public class LegStep { - private double distance; - private double duration; - private String geometry; - private String name; - private String mode; - private StepManeuver maneuver; - private List intersections; + private double distance; + private double duration; + private String geometry; + private String name; + private String mode; + private StepManeuver maneuver; + private List intersections; - /** - * The distance traveled from the maneuver to the next {@link LegStep}. - * - * @return a double number with unit meters. - * @since 1.0.0 - */ - public double getDistance() { - return distance; - } + /** + * The distance traveled from the maneuver to the next {@link LegStep}. + * + * @return a double number with unit meters. + * @since 1.0.0 + */ + public double getDistance() { + return distance; + } - /** - * The estimated travel time from the maneuver to the next {@link LegStep}. - * - * @return a double number with unit seconds. - * @since 1.0.0 - */ - public double getDuration() { - return duration; - } + /** + * The estimated travel time from the maneuver to the next {@link LegStep}. + * + * @return a double number with unit seconds. + * @since 1.0.0 + */ + public double getDuration() { + return duration; + } - /** - * Gives the geometry of the leg step. - * - * @return An encoded polyline string. - * @since 1.0.0 - */ - public String getGeometry() { - return geometry; - } + /** + * Gives the geometry of the leg step. + * + * @return An encoded polyline string. + * @since 1.0.0 + */ + public String getGeometry() { + return geometry; + } - /** - * @return String with the name of the way along which the travel proceeds. - * @since 1.0.0 - */ - public String getName() { - return name; - } + /** + * @return String with the name of the way along which the travel proceeds. + * @since 1.0.0 + */ + public String getName() { + return name; + } - /** - * @return String indicating the mode of transportation. - * @since 1.0.0 - */ - public String getMode() { - return mode; - } + /** + * @return String indicating the mode of transportation. + * @since 1.0.0 + */ + public String getMode() { + return mode; + } - /** - * @return One {@link StepManeuver} object. - * @since 1.0.0 - */ - public StepManeuver getManeuver() { - return maneuver; - } + /** + * @return One {@link StepManeuver} object. + * @since 1.0.0 + */ + public StepManeuver getManeuver() { + return maneuver; + } - /** - * @return Array of objects representing all intersections along the step. - * @since 1.3.0 - */ - public List getIntersections() { - return intersections; - } + /** + * @return Array of objects representing all intersections along the step. + * @since 1.3.0 + */ + public List getIntersections() { + return intersections; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/RouteLeg.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/RouteLeg.java index 5a36c910d..fb07c8ec5 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/RouteLeg.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/RouteLeg.java @@ -9,48 +9,48 @@ */ public class RouteLeg { - private double distance; - private double duration; - private String summary; - private List steps; + private double distance; + private double duration; + private String summary; + private List steps; - /** - * The distance traveled from one waypoint to another. - * - * @return a double number with unit meters. - * @since 1.0.0 - */ - public double getDistance() { - return distance; - } + /** + * The distance traveled from one waypoint to another. + * + * @return a double number with unit meters. + * @since 1.0.0 + */ + public double getDistance() { + return distance; + } - /** - * The estimated travel time from one waypoint to another. - * - * @return a double number with unit seconds. - * @since 1.0.0 - */ - public double getDuration() { - return duration; - } + /** + * The estimated travel time from one waypoint to another. + * + * @return a double number with unit seconds. + * @since 1.0.0 + */ + public double getDuration() { + return duration; + } - /** - * A short human-readable summary of major roads traversed. Useful to distinguish alternatives. - * - * @return String with summary. - * @since 1.0.0 - */ - public String getSummary() { - return summary; - } + /** + * A short human-readable summary of major roads traversed. Useful to distinguish alternatives. + * + * @return String with summary. + * @since 1.0.0 + */ + public String getSummary() { + return summary; + } - /** - * Gives a List including all the steps to get from one waypoint to another. - * - * @return List of {@link LegStep}. - * @since 1.0.0 - */ - public List getSteps() { - return steps; - } + /** + * Gives a List including all the steps to get from one waypoint to another. + * + * @return List of {@link LegStep}. + * @since 1.0.0 + */ + public List getSteps() { + return steps; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepIntersection.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepIntersection.java index 7bd7f1fb9..fe11590bd 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepIntersection.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepIntersection.java @@ -7,69 +7,69 @@ */ public class StepIntersection { - private double[] location; - private int[] bearings; - private boolean[] entry; - private int in; - private int out; + private double[] location; + private int[] bearings; + private boolean[] entry; + private int in; + private int out; - /** - * @return A [longitude, latitude] pair describing the location of the turn. - * @since 1.3.0 - */ - public double[] getLocation() { - return location; - } + /** + * @return A [longitude, latitude] pair describing the location of the turn. + * @since 1.3.0 + */ + public double[] getLocation() { + return location; + } - /** - * @return A list of bearing values (for example [0,90,180,270]) that are available at the - * intersection. The bearings describe all available roads at the intersection. - * @since 1.3.0 - */ - public int[] getBearings() { - return bearings; - } + /** + * @return A list of bearing values (for example [0,90,180,270]) that are available at the + * intersection. The bearings describe all available roads at the intersection. + * @since 1.3.0 + */ + public int[] getBearings() { + return bearings; + } - /** - * @return A list of entry flags, corresponding in a 1:1 relationship to the bearings. A value - * of true indicates that the respective road could be entered on a valid route. false - * indicates that the turn onto the respective road would violate a restriction. - * @since 1.3.0 - */ - public boolean[] getEntry() { - return entry; - } + /** + * @return A list of entry flags, corresponding in a 1:1 relationship to the bearings. A value + * of true indicates that the respective road could be entered on a valid route. false + * indicates that the turn onto the respective road would violate a restriction. + * @since 1.3.0 + */ + public boolean[] getEntry() { + return entry; + } - /** - * @return Index into bearings/entry array. Used to calculate the bearing before the turn. - * Namely, the clockwise angle from true north to the direction of travel before the - * maneuver/passing the intersection. To get the bearing in the direction of driving, - * the bearing has to be rotated by a value of 180. The value is not supplied for departure - * maneuvers. - * @since 1.3.0 - */ - public int getIn() { - return in; - } + /** + * @return Index into bearings/entry array. Used to calculate the bearing before the turn. + * Namely, the clockwise angle from true north to the direction of travel before the + * maneuver/passing the intersection. To get the bearing in the direction of driving, + * the bearing has to be rotated by a value of 180. The value is not supplied for departure + * maneuvers. + * @since 1.3.0 + */ + public int getIn() { + return in; + } - /** - * @return Index into the bearings/entry array. Used to extract the bearing after the turn. - * Namely, The clockwise angle from true north to the direction of travel after the - * maneuver/passing the intersection. The value is not supplied for arrive maneuvers. - * @since 1.3.0 - */ - public int getOut() { - return out; - } + /** + * @return Index into the bearings/entry array. Used to extract the bearing after the turn. + * Namely, The clockwise angle from true north to the direction of travel after the + * maneuver/passing the intersection. The value is not supplied for arrive maneuvers. + * @since 1.3.0 + */ + public int getOut() { + return out; + } - /** - * Converts double array {@link #getLocation()} to a {@link Position}. You'll typically want to - * use this format instead of {@link #getLocation()} as it's easier to work with. - * - * @return {@link Position}. - * @since 1.3.0 - */ - public Position asPosition() { - return Position.fromCoordinates(location[0], location[1]); - } + /** + * Converts double array {@link #getLocation()} to a {@link Position}. You'll typically want to + * use this format instead of {@link #getLocation()} as it's easier to work with. + * + * @return {@link Position}. + * @since 1.3.0 + */ + public Position asPosition() { + return Position.fromCoordinates(location[0], location[1]); + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepManeuver.java b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepManeuver.java index 4667baaa1..778aed32b 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepManeuver.java +++ b/libjava/lib/src/main/java/com/mapbox/services/directions/v5/models/StepManeuver.java @@ -12,125 +12,126 @@ */ public class StepManeuver { - private double[] location; - @SerializedName("bearing_before") - private double bearingBefore; - @SerializedName("bearing_after") - private double bearingAfter; - private String type; - private String pronunciation; - private String modifier; - private String instruction; + private double[] location; + @SerializedName("bearing_before") + private double bearingBefore; + @SerializedName("bearing_after") + private double bearingAfter; + private String type; + private String pronunciation; + private String modifier; + private String instruction; - /** - * @return double array of [longitude, latitude] for the snapped coordinate. - * @since 1.0.0 - */ - public double[] getLocation() { - return location; - } + /** + * @return double array of [longitude, latitude] for the snapped coordinate. + * @since 1.0.0 + */ + public double[] getLocation() { + return location; + } - /** - * Number between 0 and 360 indicating the clockwise angle from true north to the direction of - * travel right before the maneuver. - * - * @return double with value from 0 to 360. - * @since 1.0.0 - */ - public double getBearingBefore() { - return bearingBefore; - } + /** + * Number between 0 and 360 indicating the clockwise angle from true north to the direction of + * travel right before the maneuver. + * + * @return double with value from 0 to 360. + * @since 1.0.0 + */ + public double getBearingBefore() { + return bearingBefore; + } - /** - * Number between 0 and 360 indicating the clockwise angle from true north to the direction of - * travel right after the maneuver. - * - * @return double with value from 0 to 360. - * @since 1.0.0 - */ - public double getBearingAfter() { - return bearingAfter; - } + /** + * Number between 0 and 360 indicating the clockwise angle from true north to the direction of + * travel right after the maneuver. + * + * @return double with value from 0 to 360. + * @since 1.0.0 + */ + public double getBearingAfter() { + return bearingAfter; + } - /** - * This indicates the type of maneuver. It can be any of these listed: - *
- *

    - *
  • turn - a basic turn into direction of the modifier
  • - *
  • new name - the road name changes (after a mandatory turn)
  • - *
  • depart - indicates departure from a leg
  • - *
  • arrive - indicates arrival to a destination of a leg
  • - *
  • merge - merge onto a street
  • - *
  • ramp - take a ramp
  • - *
  • fork
  • - *
  • end of road - road ends in a T intersection
  • - *
  • continue - continue on a street after a turn
  • - *
  • roundabout - traverse roundabout
  • - *
- * - * @return String with type of maneuver. - * @since 1.0.0 - */ - public String getType() { - return type; - } + /** + * This indicates the type of maneuver. It can be any of these listed: + *
+ *
    + *
  • turn - a basic turn into direction of the modifier
  • + *
  • new name - the road name changes (after a mandatory turn)
  • + *
  • depart - indicates departure from a leg
  • + *
  • arrive - indicates arrival to a destination of a leg
  • + *
  • merge - merge onto a street
  • + *
  • ramp - take a ramp
  • + *
  • fork
  • + *
  • end of road - road ends in a T intersection
  • + *
  • continue - continue on a street after a turn
  • + *
  • roundabout - traverse roundabout
  • + *
+ * + * @return String with type of maneuver. + * @since 1.0.0 + */ + public String getType() { + return type; + } - /** - * The pronunciation hint of the way name. Will be undefined if no pronunciation is hit. - * @since 1.3.0 - * @return String with the pronunciation - */ - public String getPronunciation() { - return pronunciation; - } + /** + * The pronunciation hint of the way name. Will be undefined if no pronunciation is hit. + * + * @return String with the pronunciation + * @since 1.3.0 + */ + public String getPronunciation() { + return pronunciation; + } - /** - * This indicates the mode of the maneuver. If type is of turn, the modifier indicates the - * change in direction accomplished through the turn. If the type is of depart/arrive, the - * modifier indicates the position of waypoint from the current direction of travel. - * - * @return String with modifier. - * @since 1.0.0 - */ - public String getModifier() { - return modifier; - } + /** + * This indicates the mode of the maneuver. If type is of turn, the modifier indicates the + * change in direction accomplished through the turn. If the type is of depart/arrive, the + * modifier indicates the position of waypoint from the current direction of travel. + * + * @return String with modifier. + * @since 1.0.0 + */ + public String getModifier() { + return modifier; + } - /** - * A human-readable instruction of how to execute the returned maneuver. - * - * @return String with instruction. - * @since 1.0.0 - */ - public String getInstruction() { - return instruction; - } + /** + * A human-readable instruction of how to execute the returned maneuver. + * + * @return String with instruction. + * @since 1.0.0 + */ + public String getInstruction() { + return instruction; + } - /** - * Converts double array {@link #getLocation()} to a {@link Position}. You'll typically want to - * use this format instead of {@link #getLocation()} as it's easier to work with. - * - * @return {@link Position}. - * @since 1.0.0 - */ - public Position asPosition() { - return Position.fromCoordinates(location[0], location[1]); - } + /** + * Converts double array {@link #getLocation()} to a {@link Position}. You'll typically want to + * use this format instead of {@link #getLocation()} as it's easier to work with. + * + * @return {@link Position}. + * @since 1.0.0 + */ + public Position asPosition() { + return Position.fromCoordinates(location[0], location[1]); + } - /** - * @return String with all {@link StepManeuver} information within. - * @since 1.0.0 - */ - @Override - public String toString() { - return "StepManeuver{" + - "location=" + Arrays.toString(location) + - ", bearingBefore=" + bearingBefore + - ", bearingAfter=" + bearingAfter + - ", instruction='" + instruction + '\'' + - ", type='" + type + '\'' + - ", pronunciation='" + pronunciation + '\'' + - ", modifier='" + modifier + '\'' + - '}'; - } + /** + * @return String with all {@link StepManeuver} information within. + * @since 1.0.0 + */ + @Override + public String toString() { + return "StepManeuver{" + + "location=" + Arrays.toString(location) + + ", bearingBefore=" + bearingBefore + + ", bearingAfter=" + bearingAfter + + ", instruction='" + instruction + '\'' + + ", type='" + type + '\'' + + ", pronunciation='" + pronunciation + '\'' + + ", modifier='" + modifier + '\'' + + '}'; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingCriteria.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingCriteria.java index 9bae6fa12..93b7af60f 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingCriteria.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingCriteria.java @@ -7,67 +7,67 @@ */ public final class GeocodingCriteria { - /** - * Default geocoding mode. - * - * @since 1.0.0 - */ - public static final String MODE_PLACES = "mapbox.places"; + /** + * Default geocoding mode. + * + * @since 1.0.0 + */ + public static final String MODE_PLACES = "mapbox.places"; - /** - * Geocoding mode for for enterprise/batch geocoding. - * - * @since 1.0.0 - */ - public static final String MODE_PLACES_PERMANENT = "mapbox.places-permanent"; + /** + * Geocoding mode for for enterprise/batch geocoding. + * + * @since 1.0.0 + */ + public static final String MODE_PLACES_PERMANENT = "mapbox.places-permanent"; - /** - * Filter results by country. - * - * @since 1.0.0 - */ - public static final String TYPE_COUNTRY = "country"; + /** + * Filter results by country. + * + * @since 1.0.0 + */ + public static final String TYPE_COUNTRY = "country"; - /** - * Filter results by region. - * - * @since 1.0.0 - */ - public static final String TYPE_REGION = "region"; + /** + * Filter results by region. + * + * @since 1.0.0 + */ + public static final String TYPE_REGION = "region"; - /** - * Filter results by postcode. - * - * @since 1.0.0 - */ - public static final String TYPE_POSTCODE = "postcode"; + /** + * Filter results by postcode. + * + * @since 1.0.0 + */ + public static final String TYPE_POSTCODE = "postcode"; - /** - * Filter results by place. - * - * @since 1.0.0 - */ - public static final String TYPE_PLACE = "place"; + /** + * Filter results by place. + * + * @since 1.0.0 + */ + public static final String TYPE_PLACE = "place"; - /** - * Filter results by neighborhood. - * - * @since 1.0.0 - */ - public static final String TYPE_NEIGHBORHOOD = "neighborhood"; + /** + * Filter results by neighborhood. + * + * @since 1.0.0 + */ + public static final String TYPE_NEIGHBORHOOD = "neighborhood"; - /** - * Filter results by address. - * - * @since 1.0.0 - */ - public static final String TYPE_ADDRESS = "address"; + /** + * Filter results by address. + * + * @since 1.0.0 + */ + public static final String TYPE_ADDRESS = "address"; - /** - * Filter results by POI. - * - * @since 1.0.0 - */ - public static final String TYPE_POI = "poi"; + /** + * Filter results by POI. + * + * @since 1.0.0 + */ + public static final String TYPE_POI = "poi"; } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingService.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingService.java index 9e8c64891..94573dc88 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingService.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/GeocodingService.java @@ -15,31 +15,31 @@ */ public interface GeocodingService { - /** - * Call-based interface - * - * @param userAgent The user - * @param mode mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. - * @param query a location; a place name for forward geocoding or a coordinate pair - * (longitude, latitude location) for reverse geocoding - * @param accessToken Mapbox access token. - * @param country ISO 3166 alpha 2 country codes, separated by commas. - * @param proximity Location around which to bias results. - * @param types Filter results by one or more type. - * @param autocomplete True if you want auto complete. - * @param bbox Optionally pass in a bounding box to limit results in. - * @return A retrofit Call object - * @since 1.0.0 - */ - @GET("/geocoding/v5/{mode}/{query}.json") - Call getCall( - @Header("User-Agent") String userAgent, - @Path("mode") String mode, - @Path("query") String query, - @Query("access_token") String accessToken, - @Query("country") String country, - @Query("proximity") String proximity, - @Query("types") String types, - @Query("autocomplete") Boolean autocomplete, - @Query("bbox") String bbox); + /** + * Call-based interface + * + * @param userAgent The user + * @param mode mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. + * @param query a location; a place name for forward geocoding or a coordinate pair + * (longitude, latitude location) for reverse geocoding + * @param accessToken Mapbox access token. + * @param country ISO 3166 alpha 2 country codes, separated by commas. + * @param proximity Location around which to bias results. + * @param types Filter results by one or more type. + * @param autocomplete True if you want auto complete. + * @param bbox Optionally pass in a bounding box to limit results in. + * @return A retrofit Call object + * @since 1.0.0 + */ + @GET("/geocoding/v5/{mode}/{query}.json") + Call getCall( + @Header("User-Agent") String userAgent, + @Path("mode") String mode, + @Path("query") String query, + @Query("access_token") String accessToken, + @Query("country") String country, + @Query("proximity") String proximity, + @Query("types") String types, + @Query("autocomplete") Boolean autocomplete, + @Query("bbox") String bbox); } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/MapboxGeocoding.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/MapboxGeocoding.java index 8e5de21ac..856afbba6 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/MapboxGeocoding.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/MapboxGeocoding.java @@ -28,398 +28,406 @@ */ public class MapboxGeocoding extends MapboxService { - private Builder builder = null; - private GeocodingService service = null; - private Call call = null; + private Builder builder = null; + private GeocodingService service = null; + private Call call = null; + + // Allows testing + private String baseUrl = Constants.BASE_API_URL; + + /** + * Public constructor. + * + * @param builder {@link Builder} object. + * @since 1.0.0 + */ + public MapboxGeocoding(Builder builder) { + this.builder = builder; + } + + /** + * Used internally. + * + * @param baseUrl the baseURL. + * @since 1.0.0 + */ + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + /** + * Used internally. + * + * @return Geocoding service. + * @since 1.0.0 + */ + public GeocodingService getService() { + // No need to recreate it + if (service != null) { + return service; + } + + // Gson instance with type adapters + Gson gson = new GsonBuilder() + .registerTypeAdapter(Geometry.class, new CarmenGeometryDeserializer()) + .create(); + + Retrofit retrofit = new Retrofit.Builder() + .client(getOkHttpClient()) + .baseUrl(baseUrl) + .addConverterFactory(GsonConverterFactory.create(gson)) + .build(); + + service = retrofit.create(GeocodingService.class); + return service; + } + + /** + * Used internally. + * + * @return call + * @since 1.0.0 + */ + public Call getCall() { + // No need to recreate it + if (call != null) { + return call; + } - // Allows testing - private String baseUrl = Constants.BASE_API_URL; + call = getService().getCall( + getHeaderUserAgent(), + builder.getMode(), + builder.getQuery(), + builder.getAccessToken(), + builder.getCountry(), + builder.getProximity(), + builder.getGeocodingTypes(), + builder.getAutocomplete(), + builder.getBbox()); + + return call; + } + + /** + * Execute the call + * + * @return The Geocoding v5 response + * @throws IOException Signals that an I/O exception of some sort has occurred. + * @since 1.0.0 + */ + @Override + public Response executeCall() throws IOException { + return getCall().execute(); + } + + /** + * Execute the call + * + * @param callback A Retrofit callback. + * @since 1.0.0 + */ + @Override + public void enqueueCall(Callback callback) { + getCall().enqueue(callback); + } + + /** + * Cancel the call + * + * @since 1.0.0 + */ + @Override + public void cancelCall() { + getCall().cancel(); + } + + /** + * clone the call + * + * @return cloned call + * @since 1.0.0 + */ + @Override + public Call cloneCall() { + return getCall().clone(); + } + + /** + * Builds your geocoder query by adding parameters. + * + * @since 1.0.0 + */ + public static class Builder extends MapboxBuilder { + + // Required + private String accessToken; + private String query; + private String mode; + + // Optional (Retrofit will omit these from the request if they remain null) + private String country = null; + private String proximity = null; + private String geocodingTypes = null; + private Boolean autocomplete = null; + private String bbox = null; /** - * Public constructor. + * Constructor * - * @param builder {@link Builder} object. * @since 1.0.0 */ - public MapboxGeocoding(Builder builder) { - this.builder = builder; + public Builder() { + // Defaults + mode = GeocodingCriteria.MODE_PLACES; } /** - * Used internally. + * Required to call when building {@link MapboxGeocoding.Builder} * - * @param baseUrl the baseURL. + * @param accessToken Mapbox access token, you must have a Mapbox account in order to use + * this library. + * @return Builder * @since 1.0.0 */ - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; + @Override + public Builder setAccessToken(String accessToken) { + this.accessToken = accessToken; + return this; } /** - * Used internally. + * The location equals the query. * - * @return Geocoding service. + * @param location query + * @return Builder + * @since 1.0.0 + */ + public Builder setLocation(String location) { + query = location; + return this; + } + + /** + * @param position {@link Position} + * @return Builder * @since 1.0.0 */ - public GeocodingService getService() { - // No need to recreate it - if (service != null) return service; - - // Gson instance with type adapters - Gson gson = new GsonBuilder() - .registerTypeAdapter(Geometry.class, new CarmenGeometryDeserializer()) - .create(); - - Retrofit retrofit = new Retrofit.Builder() - .client(getOkHttpClient()) - .baseUrl(baseUrl) - .addConverterFactory(GsonConverterFactory.create(gson)) - .build(); - - service = retrofit.create(GeocodingService.class); - return service; + public Builder setCoordinates(Position position) { + if (position == null) { + return this; + } + query = String.format(Locale.US, "%f,%f", + position.getLongitude(), + position.getLatitude()); + return this; } /** - * Used internally. + * mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. * - * @return call + * @param mode mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. + * @return Builder * @since 1.0.0 */ - public Call getCall() { - // No need to recreate it - if (call != null) return call; - - call = getService().getCall( - getHeaderUserAgent(), - builder.getMode(), - builder.getQuery(), - builder.getAccessToken(), - builder.getCountry(), - builder.getProximity(), - builder.getGeocodingTypes(), - builder.getAutocomplete(), - builder.getBbox()); - - return call; + public Builder setMode(String mode) { + this.mode = mode; + return this; } /** - * Execute the call + * Country which you want the results to show up in. * - * @return The Geocoding v5 response - * @throws IOException Signals that an I/O exception of some sort has occurred. + * @param country ISO 3166 alpha 2 country code + * @return Builder * @since 1.0.0 */ - @Override - public Response executeCall() throws IOException { - return getCall().execute(); + public Builder setCountry(String country) { + this.country = country; + return this; } /** - * Execute the call + * Countries which you want the results to show up in. * - * @param callback A Retrofit callback. + * @param countries ISO 3166 alpha 2 country codes, separated by commas. + * @return Builder * @since 1.0.0 */ - @Override - public void enqueueCall(Callback callback) { - getCall().enqueue(callback); + public Builder setCountries(String[] countries) { + this.country = TextUtils.join(",", countries); + return this; } /** - * Cancel the call + * Location around which to bias results. * + * @param position A {@link Position}. + * @return Builder * @since 1.0.0 */ - @Override - public void cancelCall() { - getCall().cancel(); + public Builder setProximity(Position position) { + if (position == null) { + return this; + } + proximity = String.format(Locale.US, "%f,%f", + position.getLongitude(), + position.getLatitude()); + return this; + } + + /** + * Filter results by one or more type. Options are country, region, postcode, place, + * locality, neighborhood, address, poi. Multiple options can be comma-separated. + * + * @param geocodingType String filtering the geocoder result types. + * @return Builder + * @since 1.0.0 + */ + public Builder setGeocodingType(String geocodingType) { + this.geocodingTypes = geocodingType; + return this; + } + + /** + * Filter results by one or more type. Options are country, region, postcode, place, + * locality, neighborhood, address, poi. Multiple options can be comma-separated. + * + * @param geocodingType String array filtering the geocoder result types. + * @return Builder + * @since 1.0.0 + */ + public Builder setGeocodingTypes(String[] geocodingType) { + this.geocodingTypes = TextUtils.join(",", geocodingType); + return this; + } + + /** + * Whether or not to return autocomplete results. + * + * @param autocomplete true, if you want autocomplete results, else false. (Defaults true) + * @return Builder + * @since 1.0.0 + */ + public Builder setAutocomplete(boolean autocomplete) { + this.autocomplete = autocomplete; + return this; } /** - * clone the call + * Bounding box within which to limit results. * - * @return cloned call + * @param northeast The northeast corner of the bounding box as {@link Position}. + * @param southwest The southwest corner of the bounding box as {@link Position}. + * @return Builder + * @throws ServicesException Generic Exception for all things geocoding. + * @since 1.0.0 + */ + public Builder setBbox(Position northeast, Position southwest) throws ServicesException { + return setBbox(southwest.getLongitude(), southwest.getLatitude(), + northeast.getLongitude(), northeast.getLatitude()); + } + + /** + * Bounding box within which to limit results. + * + * @param minX The minX of bounding box when maps facing north. + * @param minY The minY of bounding box when maps facing north. + * @param maxX The maxX of bounding box when maps facing north. + * @param maxY The maxY of bounding box when maps facing north. + * @return Builder + * @throws ServicesException Generic Exception for all things geocoding. + * @since 1.0.0 + */ + public Builder setBbox(double minX, double minY, double maxX, double maxY) throws ServicesException { + if (minX == 0 && minY == 0 && maxX == 0 && maxY == 0) { + throw new ServicesException("You provided an empty bounding box"); + } + + this.bbox = String.format(Locale.US, "%f,%f,%f,%f", minX, minY, maxX, maxY); + return this; + } + + /** + * @return your Mapbox access token. * @since 1.0.0 */ @Override - public Call cloneCall() { - return getCall().clone(); + public String getAccessToken() { + return accessToken; + } + + /** + * @return your geocoder query. + * @since 1.0.0 + */ + public String getQuery() { + return query; + } + + /** + * @return mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. + * @since 1.0.0 + */ + public String getMode() { + return mode; + } + + /** + * @return ISO 3166 alpha 2 country codes, separated by commas + * @since 1.0.0 + */ + public String getCountry() { + return country; + } + + /** + * Location around which you biased the results. + * + * @return String with the format longitude, latitude. + * @since 1.0.0 + */ + public String getProximity() { + return proximity; + } + + /** + * If you filtered your results by one or more types you can get what those filters are by + * using this method. + * + * @return String with list of filters you used. + * @since 1.0.0 + */ + public String getGeocodingTypes() { + return geocodingTypes; + } + + /** + * @return true if autocomplete results, else false. + * @since 1.0.0 + */ + public Boolean getAutocomplete() { + return autocomplete; + } + + /** + * @return Bounding box within which the results are limited + * @since 1.0.0 + */ + public String getBbox() { + return bbox; } /** - * Builds your geocoder query by adding parameters. + * Build method * + * @return MapboxGeocoding + * @throws ServicesException Generic Exception for all things geocoding. * @since 1.0.0 */ - public static class Builder extends MapboxBuilder { - - // Required - private String accessToken; - private String query; - private String mode; - - // Optional (Retrofit will omit these from the request if they remain null) - private String country = null; - private String proximity = null; - private String geocodingTypes = null; - private Boolean autocomplete = null; - private String bbox = null; - - /** - * Constructor - * - * @since 1.0.0 - */ - public Builder() { - // Defaults - mode = GeocodingCriteria.MODE_PLACES; - } - - /** - * Required to call when building {@link MapboxGeocoding.Builder} - * - * @param accessToken Mapbox access token, you must have a Mapbox account in order to use - * this library. - * @return Builder - * @since 1.0.0 - */ - @Override - public Builder setAccessToken(String accessToken) { - this.accessToken = accessToken; - return this; - } - - /** - * The location equals the query. - * - * @param location query - * @return Builder - * @since 1.0.0 - */ - public Builder setLocation(String location) { - query = location; - return this; - } - - /** - * @param position {@link Position} - * @return Builder - * @since 1.0.0 - */ - public Builder setCoordinates(Position position) { - if (position == null) return this; - query = String.format(Locale.US, "%f,%f", - position.getLongitude(), - position.getLatitude()); - return this; - } - - /** - * mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. - * - * @param mode mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. - * @return Builder - * @since 1.0.0 - */ - public Builder setMode(String mode) { - this.mode = mode; - return this; - } - - /** - * Country which you want the results to show up in. - * - * @param country ISO 3166 alpha 2 country code - * @return Builder - * @since 1.0.0 - */ - public Builder setCountry(String country) { - this.country = country; - return this; - } - - /** - * Countries which you want the results to show up in. - * - * @param countries ISO 3166 alpha 2 country codes, separated by commas. - * @return Builder - * @since 1.0.0 - */ - public Builder setCountries(String[] countries) { - this.country = TextUtils.join(",", countries); - return this; - } - - /** - * Location around which to bias results. - * - * @param position A {@link Position}. - * @return Builder - * @since 1.0.0 - */ - public Builder setProximity(Position position) { - if (position == null) return this; - proximity = String.format(Locale.US, "%f,%f", - position.getLongitude(), - position.getLatitude()); - return this; - } - - /** - * Filter results by one or more type. Options are country, region, postcode, place, - * locality, neighborhood, address, poi. Multiple options can be comma-separated. - * - * @param geocodingType String filtering the geocoder result types. - * @return Builder - * @since 1.0.0 - */ - public Builder setGeocodingType(String geocodingType) { - this.geocodingTypes = geocodingType; - return this; - } - - /** - * Filter results by one or more type. Options are country, region, postcode, place, - * locality, neighborhood, address, poi. Multiple options can be comma-separated. - * - * @param geocodingType String array filtering the geocoder result types. - * @return Builder - * @since 1.0.0 - */ - public Builder setGeocodingTypes(String[] geocodingType) { - this.geocodingTypes = TextUtils.join(",", geocodingType); - return this; - } - - /** - * Whether or not to return autocomplete results. - * - * @param autocomplete true, if you want autocomplete results, else false. (Defaults true) - * @return Builder - * @since 1.0.0 - */ - public Builder setAutocomplete(boolean autocomplete) { - this.autocomplete = autocomplete; - return this; - } - - /** - * Bounding box within which to limit results. - * - * @param northeast The northeast corner of the bounding box as {@link Position}. - * @param southwest The southwest corner of the bounding box as {@link Position}. - * @return Builder - * @throws ServicesException Generic Exception for all things geocoding. - * @since 1.0.0 - */ - public Builder setBbox(Position northeast, Position southwest) throws ServicesException { - return setBbox(southwest.getLongitude(), southwest.getLatitude(), - northeast.getLongitude(), northeast.getLatitude()); - } - - /** - * Bounding box within which to limit results. - * - * @param minX The minX of bounding box when maps facing north. - * @param minY The minY of bounding box when maps facing north. - * @param maxX The maxX of bounding box when maps facing north. - * @param maxY The maxY of bounding box when maps facing north. - * @return Builder - * @throws ServicesException Generic Exception for all things geocoding. - * @since 1.0.0 - */ - public Builder setBbox(double minX, double minY, double maxX, double maxY) throws ServicesException { - if (minX == 0 && minY == 0 && maxX == 0 && maxY == 0) { - throw new ServicesException("You provided an empty bounding box"); - } - - this.bbox = String.format(Locale.US, "%f,%f,%f,%f", minX, minY, maxX, maxY); - return this; - } - - /** - * @return your Mapbox access token. - * @since 1.0.0 - */ - @Override - public String getAccessToken() { - return accessToken; - } - - /** - * @return your geocoder query. - * @since 1.0.0 - */ - public String getQuery() { - return query; - } - - /** - * @return mapbox.places or mapbox.places-permanent for enterprise/batch geocoding. - * @since 1.0.0 - */ - public String getMode() { - return mode; - } - - /** - * @return ISO 3166 alpha 2 country codes, separated by commas - * @since 1.0.0 - */ - public String getCountry() { - return country; - } - - /** - * Location around which you biased the results. - * - * @return String with the format longitude, latitude. - * @since 1.0.0 - */ - public String getProximity() { - return proximity; - } - - /** - * If you filtered your results by one or more types you can get what those filters are by - * using this method. - * - * @return String with list of filters you used. - * @since 1.0.0 - */ - public String getGeocodingTypes() { - return geocodingTypes; - } - - /** - * @return true if autocomplete results, else false. - * @since 1.0.0 - */ - public Boolean getAutocomplete() { - return autocomplete; - } - - /** - * @return Bounding box within which the results are limited - * @since 1.0.0 - */ - public String getBbox() { - return bbox; - } - - /** - * Build method - * - * @return MapboxGeocoding - * @throws ServicesException Generic Exception for all things geocoding. - * @since 1.0.0 - */ - @Override - public MapboxGeocoding build() throws ServicesException { - validateAccessToken(accessToken); - return new MapboxGeocoding(this); - } + @Override + public MapboxGeocoding build() throws ServicesException { + validateAccessToken(accessToken); + return new MapboxGeocoding(this); } + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/gson/CarmenGeometryDeserializer.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/gson/CarmenGeometryDeserializer.java index 25bf91822..f3c604372 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/gson/CarmenGeometryDeserializer.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/gson/CarmenGeometryDeserializer.java @@ -19,29 +19,30 @@ */ public class CarmenGeometryDeserializer implements JsonDeserializer { - /** - * A custom deserializer for Gson, used for the Geocoder. - * - * @param json The Json data being deserialized. - * @param typeOfT The type of the Object to deserialize to. - * @param context Context for deserialization. - * @return Deserialized Geometry. - * @throws JsonParseException This exception is raised if there is a serious issue that occurs - * during parsing of a Json string. - * @since 1.0.0 - */ - @Override - public Geometry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - JsonObject jsonObject = (JsonObject) json; - String geometryType = jsonObject.get("type").getAsString(); - if (geometryType.equals("Point")) { - JsonArray coordinates = jsonObject.getAsJsonArray("coordinates"); - return Point.fromCoordinates(Position.fromCoordinates( - coordinates.get(0).getAsDouble(), - coordinates.get(1).getAsDouble())); - } else { - throw new JsonParseException("Unexpected geometry found: " + geometryType); - } + /** + * A custom deserializer for Gson, used for the Geocoder. + * + * @param json The Json data being deserialized. + * @param typeOfT The type of the Object to deserialize to. + * @param context Context for deserialization. + * @return Deserialized Geometry. + * @throws JsonParseException This exception is raised if there is a serious issue that occurs + * during parsing of a Json string. + * @since 1.0.0 + */ + @Override + public Geometry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + JsonObject jsonObject = (JsonObject) json; + String geometryType = jsonObject.get("type").getAsString(); + if (geometryType.equals("Point")) { + JsonArray coordinates = jsonObject.getAsJsonArray("coordinates"); + return Point.fromCoordinates(Position.fromCoordinates( + coordinates.get(0).getAsDouble(), + coordinates.get(1).getAsDouble())); + } else { + throw new JsonParseException("Unexpected geometry found: " + geometryType); } + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenContext.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenContext.java index e33abed1d..9ae464314 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenContext.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenContext.java @@ -12,66 +12,66 @@ */ public class CarmenContext { - private String id; - private String text; + private String id; + private String text; - @SerializedName("short_code") - private String shortCode; - private String wikidata; - private String category; - private String maki; + @SerializedName("short_code") + private String shortCode; + private String wikidata; + private String category; + private String maki; - /** - * ID of the feature of the form {index}.{id} where index is the id/handle of the datasource - * that contributed the result. - * - * @return String containing the ID. - * @since 1.0.0 - */ - public String getId() { - return id; - } + /** + * ID of the feature of the form {index}.{id} where index is the id/handle of the datasource + * that contributed the result. + * + * @return String containing the ID. + * @since 1.0.0 + */ + public String getId() { + return id; + } - /** - * @return Text representing the feature (e.g. "Austin"). - * @since 1.0.0 - */ - public String getText() { - return text; - } + /** + * @return Text representing the feature (e.g. "Austin"). + * @since 1.0.0 + */ + public String getText() { + return text; + } - /** - * @return String containing ISO 3166-1 country and ISO 3166-2 region codes - * @since 1.0.0 - */ - public String getShortCode() { - return shortCode; - } + /** + * @return String containing ISO 3166-1 country and ISO 3166-2 region codes + * @since 1.0.0 + */ + public String getShortCode() { + return shortCode; + } - /** - * @return The Wikidata identifier for a country, region or place - * @since 1.2.0 - */ - public String getWikidata() { - return wikidata; - } + /** + * @return The Wikidata identifier for a country, region or place + * @since 1.2.0 + */ + public String getWikidata() { + return wikidata; + } - /** - * @return Comma-separated list of categories applicable to a poi - * @since 1.0.0 - */ - public String getCategory() { - return category; - } + /** + * @return Comma-separated list of categories applicable to a poi + * @since 1.0.0 + */ + public String getCategory() { + return category; + } - /** - * Suggested icon mapping from the most current version of the Maki project for a poi feature, - * based on its category - * - * @return String containing recommendation - * @since 1.2.0 - */ - public String getMaki() { - return maki; - } + /** + * Suggested icon mapping from the most current version of the Maki project for a poi feature, + * based on its category + * + * @return String containing recommendation + * @since 1.2.0 + */ + public String getMaki() { + return maki; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeature.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeature.java index eee0104a4..b2e717bff 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeature.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeature.java @@ -19,133 +19,133 @@ */ public class CarmenFeature extends Feature { - private String text; - @SerializedName("place_name") - private String placeName; - private double[] bbox; - private String address; - private double[] center; - private List context; - - private double relevance; - - /** - * Private constructor. - */ - private CarmenFeature(Geometry geometry, JsonObject properties, String id) { - super(geometry, properties, id); - } - - public CarmenFeature() { - super(null, null, null); - } - - /** - * @return Text representing the feature (e.g. "Austin"). - * @since 1.0.0 - */ - public String getText() { - return text; - } - - /** - * @return Human-readable text representing the full result hierarchy (e.g. "Austin, Texas, United States"). - * @since 1.0.0 - */ - public String getPlaceName() { - return placeName; - } - - /** - * @return Array bounding box of the form [minx, miny, maxx, maxy]. - * @since 1.0.0 - */ - public double[] getBbox() { - return bbox; - } - - /** - * @return Where applicable. Contains the housenumber for the returned feature - * @since 1.0.0 - */ - public String getAddress() { - return address; - } - - /** - * @return Array of the form [lon, lat]. - * @since 1.0.0 - */ - public double[] getCenter() { - return center; - } - - /** - * @return Array representing a hierarchy of parents. Each parent includes id, text keys. - * @since 1.0.0 - */ - public List getContext() { - return context; - } - - /** - * You can use the relevance property to remove rough results if you require a response that - * matches your whole query. - * - * @return double value between 0 and 1. - * @since 1.0.0 - */ - public double getRelevance() { - return relevance; - } - - public void setText(String text) { - this.text = text; - } - - public void setPlaceName(String placeName) { - this.placeName = placeName; - } - - public void setBbox(double[] bbox) { - this.bbox = bbox; - } - - public void setAddress(String address) { - this.address = address; - } - - public void setCenter(double[] center) { - this.center = center; - } - - public void setContext(List context) { - this.context = context; - } - - public void setRelevance(double relevance) { - this.relevance = relevance; - } - - /** - * Util to transform center into a Position object - * - * @return a {@link Position} representing the center. - * @since 1.0.0 - */ - public Position asPosition() { - return Position.fromCoordinates(center[0], center[1]); - } - - /** - * Human-readable text representing the full result hierarchy - * (e.g. "Austin, Texas, United States"). - * - * @return String with human-readable text. - * @since 1.0.0 - */ - @Override - public String toString() { - return getPlaceName(); - } + private String text; + @SerializedName("place_name") + private String placeName; + private double[] bbox; + private String address; + private double[] center; + private List context; + + private double relevance; + + /** + * Private constructor. + */ + private CarmenFeature(Geometry geometry, JsonObject properties, String id) { + super(geometry, properties, id); + } + + public CarmenFeature() { + super(null, null, null); + } + + /** + * @return Text representing the feature (e.g. "Austin"). + * @since 1.0.0 + */ + public String getText() { + return text; + } + + /** + * @return Human-readable text representing the full result hierarchy (e.g. "Austin, Texas, United States"). + * @since 1.0.0 + */ + public String getPlaceName() { + return placeName; + } + + /** + * @return Array bounding box of the form [minx, miny, maxx, maxy]. + * @since 1.0.0 + */ + public double[] getBbox() { + return bbox; + } + + /** + * @return Where applicable. Contains the housenumber for the returned feature + * @since 1.0.0 + */ + public String getAddress() { + return address; + } + + /** + * @return Array of the form [lon, lat]. + * @since 1.0.0 + */ + public double[] getCenter() { + return center; + } + + /** + * @return Array representing a hierarchy of parents. Each parent includes id, text keys. + * @since 1.0.0 + */ + public List getContext() { + return context; + } + + /** + * You can use the relevance property to remove rough results if you require a response that + * matches your whole query. + * + * @return double value between 0 and 1. + * @since 1.0.0 + */ + public double getRelevance() { + return relevance; + } + + public void setText(String text) { + this.text = text; + } + + public void setPlaceName(String placeName) { + this.placeName = placeName; + } + + public void setBbox(double[] bbox) { + this.bbox = bbox; + } + + public void setAddress(String address) { + this.address = address; + } + + public void setCenter(double[] center) { + this.center = center; + } + + public void setContext(List context) { + this.context = context; + } + + public void setRelevance(double relevance) { + this.relevance = relevance; + } + + /** + * Util to transform center into a Position object + * + * @return a {@link Position} representing the center. + * @since 1.0.0 + */ + public Position asPosition() { + return Position.fromCoordinates(center[0], center[1]); + } + + /** + * Human-readable text representing the full result hierarchy + * (e.g. "Austin, Texas, United States"). + * + * @return String with human-readable text. + * @since 1.0.0 + */ + @Override + public String toString() { + return getPlaceName(); + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeatureCollection.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeatureCollection.java index 596459f93..1957defcb 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeatureCollection.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/CarmenFeatureCollection.java @@ -13,81 +13,81 @@ */ public class CarmenFeatureCollection extends BaseFeatureCollection { - private List query; - private String attribution; - private final List features; + private List query; + private String attribution; + private final List features; - /** - * Protected constructor. - * Unlike other GeoJSON objects, this constructor is protected to enable the deserialization - * of the Geocoding service responses. - * - * @param features List of {@link Feature}. - * @since 1.0.0 - */ - protected CarmenFeatureCollection(List features) { - this.features = features; - } + /** + * Protected constructor. + * Unlike other GeoJSON objects, this constructor is protected to enable the deserialization + * of the Geocoding service responses. + * + * @param features List of {@link Feature}. + * @since 1.0.0 + */ + protected CarmenFeatureCollection(List features) { + this.features = features; + } - /** - * A place name for forward geocoding or a coordinate pair (longitude, latitude location) for - * reverse geocoding. - * - * @return a List containing your search query. - * @since 1.0.0 - */ - public List getQuery() { - return this.query; - } + /** + * A place name for forward geocoding or a coordinate pair (longitude, latitude location) for + * reverse geocoding. + * + * @return a List containing your search query. + * @since 1.0.0 + */ + public List getQuery() { + return this.query; + } - /** - * A place name for forward geocoding or a coordinate pair (longitude, latitude location) - * for reverse geocoding. - * - * @param query The search terms used. - * @since 1.0.0 - */ - public void setQuery(List query) { - this.query = query; - } + /** + * A place name for forward geocoding or a coordinate pair (longitude, latitude location) + * for reverse geocoding. + * + * @param query The search terms used. + * @since 1.0.0 + */ + public void setQuery(List query) { + this.query = query; + } - /** - * Mapbox attribution. - * - * @return String with Mapbox attribution. - * @since 1.0.0 - */ - public String getAttribution() { - return this.attribution; - } + /** + * Mapbox attribution. + * + * @return String with Mapbox attribution. + * @since 1.0.0 + */ + public String getAttribution() { + return this.attribution; + } - /** - * @param attribution String with Mapbox attribution. - * @since 1.0.0 - */ - public void setAttribution(String attribution) { - this.attribution = attribution; - } + /** + * @param attribution String with Mapbox attribution. + * @since 1.0.0 + */ + public void setAttribution(String attribution) { + this.attribution = attribution; + } - /** - * Get the List containing all the features within collection. - * - * @return List of features within collection. - * @since 1.0.0 - */ - public List getFeatures() { - return features; - } + /** + * Get the List containing all the features within collection. + * + * @return List of features within collection. + * @since 1.0.0 + */ + public List getFeatures() { + return features; + } - /** - * Create a {@link FeatureCollection} from a List of features. - * - * @param features List of {@link Feature} - * @return new {@link FeatureCollection} - * @since 1.0.0 - */ - public static CarmenFeatureCollection fromFeatures(List features) { - return new CarmenFeatureCollection(features); - } + /** + * Create a {@link FeatureCollection} from a List of features. + * + * @param features List of {@link Feature} + * @return new {@link FeatureCollection} + * @since 1.0.0 + */ + public static CarmenFeatureCollection fromFeatures(List features) { + return new CarmenFeatureCollection(features); + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/GeocodingResponse.java b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/GeocodingResponse.java index ac46869ac..d60bc8996 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/GeocodingResponse.java +++ b/libjava/lib/src/main/java/com/mapbox/services/geocoding/v5/models/GeocodingResponse.java @@ -9,8 +9,8 @@ */ public class GeocodingResponse extends CarmenFeatureCollection { - public GeocodingResponse(List features) { - super(features); - } + public GeocodingResponse(List features) { + super(features); + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapMatchingService.java b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapMatchingService.java index 45476e727..5ce71c380 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapMatchingService.java +++ b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapMatchingService.java @@ -17,24 +17,24 @@ */ public interface MapMatchingService { - /** - * Call based interface - * - * @param userAgent user - * @param profile directions profile id - * @param accessToken Mapbox access token - * @param geometry format for the returned geometry (optional) - * @param gpsPrecision assumed precission in meters of the used tracking device - * @param trace The trace wanting to be matched - * @return The MapMatchingResponse in a Call wrapper - * @since 1.2.0 - */ - @POST("matching/v4/{profile}.json") - Call getCall( - @Header("User-Agent") String userAgent, - @Path("profile") String profile, - @Query("access_token") String accessToken, - @Query("geometry") String geometry, - @Query("gps_precision") Integer gpsPrecision, - @Body RequestBody trace); + /** + * Call based interface + * + * @param userAgent user + * @param profile directions profile id + * @param accessToken Mapbox access token + * @param geometry format for the returned geometry (optional) + * @param gpsPrecision assumed precission in meters of the used tracking device + * @param trace The trace wanting to be matched + * @return The MapMatchingResponse in a Call wrapper + * @since 1.2.0 + */ + @POST("matching/v4/{profile}.json") + Call getCall( + @Header("User-Agent") String userAgent, + @Path("profile") String profile, + @Query("access_token") String accessToken, + @Query("geometry") String geometry, + @Query("gps_precision") Integer gpsPrecision, + @Body RequestBody trace); } diff --git a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapboxMapMatching.java b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapboxMapMatching.java index ac1441895..3619b61be 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapboxMapMatching.java +++ b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/MapboxMapMatching.java @@ -35,300 +35,302 @@ */ public class MapboxMapMatching extends MapboxService { - private Builder builder = null; - private MapMatchingService service = null; - private Call call = null; - - // Allows testing - private String baseUrl = Constants.BASE_API_URL; + private Builder builder = null; + private MapMatchingService service = null; + private Call call = null; + + // Allows testing + private String baseUrl = Constants.BASE_API_URL; + + private MapboxMapMatching(Builder builder) { + this.builder = builder; + } + + /** + * Used internally. + * + * @param baseUrl the baseURL. + * @since 1.2.0 + */ + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + + private MapMatchingService getService() { + // No need to recreate it + if (service != null) { + return service; + } - private MapboxMapMatching(Builder builder) { - this.builder = builder; + // Gson instance with type adapters + Gson gson = new GsonBuilder() + .registerTypeAdapter(Geometry.class, new MapMatchingGeometryDeserializer()) + .create(); + + // Retrofit instance + Retrofit retrofit = new Retrofit.Builder() + .client(getOkHttpClient()) + .baseUrl(baseUrl) + .addConverterFactory(GsonConverterFactory.create(gson)) + .build(); + + // MapMatching service + service = retrofit.create(MapMatchingService.class); + return service; + } + + /** + * Used internally. + * + * @return call + * @since 1.2.0 + */ + public Call getCall() { + // No need to recreate it + if (call != null) { + return call; } + call = getService().getCall( + getHeaderUserAgent(), + builder.getProfile(), + builder.getAccessToken(), + builder.getGeometry(), + builder.getGpsPrecison(), + builder.getTrace() + ); + + return call; + } + + /** + * Execute the call + * + * @return The map matching v4 response + * @throws IOException Signals that an I/O exception of some sort has occurred. + * @since 1.2.0 + */ + @Override + public Response executeCall() throws IOException { + return getCall().execute(); + } + + /** + * Execute the call + * + * @param callback A Retrofit callback. + * @since 1.2.0 + */ + @Override + public void enqueueCall(Callback callback) { + getCall().enqueue(callback); + } + + /** + * Cancel the call + * + * @since 1.2.0 + */ + @Override + public void cancelCall() { + getCall().cancel(); + } + + /** + * clone the call + * + * @return cloned call + * @since 1.2.0 + */ + @Override + public Call cloneCall() { + return getCall().clone(); + } + + /** + * Builds your map matching query by adding parameters. + * + * @since 1.2.0 + */ + public static class Builder extends MapboxBuilder { + + private String accessToken; + private String profile; + private String geometry; + private Integer gpsPrecison; + + private LineString trace; + /** - * Used internally. + * Constructor * - * @param baseUrl the baseURL. * @since 1.2.0 */ - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; + public Builder() { + // Use polyline by default as the return format + this.geometry = DirectionsCriteria.GEOMETRY_POLYLINE; } + /** + * Required to call when building {@link Builder} + * + * @param accessToken Mapbox access token, you must have a Mapbox account in order to use + * this API. + * @return Builder + * @since 1.2.0 + */ + @Override + public Builder setAccessToken(String accessToken) { + this.accessToken = accessToken; + return this; + } - private MapMatchingService getService() { - // No need to recreate it - if (service != null) { - return service; - } - - // Gson instance with type adapters - Gson gson = new GsonBuilder() - .registerTypeAdapter(Geometry.class, new MapMatchingGeometryDeserializer()) - .create(); + /** + * @return Mapbox access token + * @since 1.2.0 + */ + @Override + public String getAccessToken() { + return this.accessToken; + } - // Retrofit instance - Retrofit retrofit = new Retrofit.Builder() - .client(getOkHttpClient()) - .baseUrl(baseUrl) - .addConverterFactory(GsonConverterFactory.create(gson)) - .build(); + /** + * Set a map matching profile. You should use one of the constants in Directions v4 + * com.mapbox.services.directions.v4.DirectionsCriteria + * + * @param profile String containg A directions profile ID; either {@code mapbox.driving}, + * {@code mapbox.walking}, or {@code mapbox.cycling}. Use one of the + * {@link DirectionsCriteria} constants. + * @return Builder + * @since 1.2.0 + */ + public Builder setProfile(String profile) { + this.profile = profile; + return this; + } - // MapMatching service - service = retrofit.create(MapMatchingService.class); - return service; + /** + * @return String containg A directions profile ID; either {@code mapbox.driving}, + * {@code mapbox.walking}, or {@code mapbox.cycling}. + * @since 1.2.0 + */ + public String getProfile() { + return profile; } /** - * Used internally. + * Format of the returned geometry. Allowed values are: {@code geojson} (default, as + * LineString), {@code polyline} (documentation) with precision 6, {@code false} (no + * geometry, but matched points). * - * @return call + * @return String containing one of the values allowed. * @since 1.2.0 */ - public Call getCall() { - // No need to recreate it - if (call != null) return call; - - call = getService().getCall( - getHeaderUserAgent(), - builder.getProfile(), - builder.getAccessToken(), - builder.getGeometry(), - builder.getGpsPrecison(), - builder.getTrace() - ); - - return call; + public String getGeometry() { + return geometry; } /** - * Execute the call + * Set the geometry to {@code false}. * - * @return The map matching v4 response - * @throws IOException Signals that an I/O exception of some sort has occurred. + * @return Builder * @since 1.2.0 */ - @Override - public Response executeCall() throws IOException { - return getCall().execute(); + public Builder setNoGeometry() { + this.geometry = DirectionsCriteria.GEOMETRY_FALSE; + return this; } /** - * Execute the call + * An integer in meters indicating the assumed precision of the used tracking device. Use + * higher numbers (5-10) for noisy traces and lower numbers (1-3) for clean traces. The + * default value is 4. * - * @param callback A Retrofit callback. + * @return integer value representing the GPS precision. * @since 1.2.0 */ - @Override - public void enqueueCall(Callback callback) { - getCall().enqueue(callback); + public Integer getGpsPrecison() { + return gpsPrecison; } /** - * Cancel the call - * + * @return Returns a new request body that transmits {@code content}. If {@code contentType} + * is non-null and lacks a charset, this will use UTF-8. * @since 1.2.0 */ - @Override - public void cancelCall() { - getCall().cancel(); + public RequestBody getTrace() { + return RequestBody.create( + MediaType.parse("application/json"), + Feature.fromGeometry(trace).toJson()); } /** - * clone the call - * - * @return cloned call + * @param gpsPrecison Assumed accuracy of the tracking device in meters + * (1-10 inclusive, default 4) + * @return Builder * @since 1.2.0 */ - @Override - public Call cloneCall() { - return getCall().clone(); + public Builder setGpsPrecison(Integer gpsPrecison) { + this.gpsPrecison = gpsPrecison; + return this; } /** - * Builds your map matching query by adding parameters. - * + * @param trace A {@link LineString} representing the route geometry you want to match. + * @return Builder * @since 1.2.0 */ - public static class Builder extends MapboxBuilder { - - private String accessToken; - private String profile; - private String geometry; - private Integer gpsPrecison; - - private LineString trace; - - /** - * Constructor - * - * @since 1.2.0 - */ - public Builder() { - // Use polyline by default as the return format - this.geometry = DirectionsCriteria.GEOMETRY_POLYLINE; - } - - /** - * Required to call when building {@link Builder} - * - * @param accessToken Mapbox access token, you must have a Mapbox account in order to use - * this API. - * @return Builder - * @since 1.2.0 - */ - @Override - public Builder setAccessToken(String accessToken) { - this.accessToken = accessToken; - return this; - } - - /** - * @return Mapbox access token - * @since 1.2.0 - */ - @Override - public String getAccessToken() { - return this.accessToken; - } - - /** - * Set a map matching profile. You should use one of the constants in Directions v4 - * com.mapbox.services.directions.v4.DirectionsCriteria - * - * @param profile String containg A directions profile ID; either {@code mapbox.driving}, - * {@code mapbox.walking}, or {@code mapbox.cycling}. Use one of the - * {@link DirectionsCriteria} constants. - * @return Builder - * @since 1.2.0 - */ - public Builder setProfile(String profile) { - this.profile = profile; - return this; - } - - /** - * @return String containg A directions profile ID; either {@code mapbox.driving}, - * {@code mapbox.walking}, or {@code mapbox.cycling}. - * @since 1.2.0 - */ - public String getProfile() { - return profile; - } - - /** - * Format of the returned geometry. Allowed values are: {@code geojson} (default, as - * LineString), {@code polyline} (documentation) with precision 6, {@code false} (no - * geometry, but matched points). - * - * @return String containing one of the values allowed. - * @since 1.2.0 - */ - public String getGeometry() { - return geometry; - } - - /** - * Set the geometry to {@code false}. - * - * @return Builder - * @since 1.2.0 - */ - public Builder setNoGeometry() { - this.geometry = DirectionsCriteria.GEOMETRY_FALSE; - return this; - } - - /** - * An integer in meters indicating the assumed precision of the used tracking device. Use - * higher numbers (5-10) for noisy traces and lower numbers (1-3) for clean traces. The - * default value is 4. - * - * @return integer value representing the GPS precision. - * @since 1.2.0 - */ - public Integer getGpsPrecison() { - return gpsPrecison; - } - - /** - * @return Returns a new request body that transmits {@code content}. If {@code contentType} - * is non-null and lacks a charset, this will use UTF-8. - * @since 1.2.0 - */ - public RequestBody getTrace() { - return RequestBody.create( - MediaType.parse("application/json"), - Feature.fromGeometry(trace).toJson()); - } - - /** - * @param gpsPrecison Assumed accuracy of the tracking device in meters - * (1-10 inclusive, default 4) - * @return Builder - * @since 1.2.0 - */ - public Builder setGpsPrecison(Integer gpsPrecison) { - this.gpsPrecison = gpsPrecison; - return this; - } - - /** - * @param trace A {@link LineString} representing the route geometry you want to match. - * @return Builder - * @since 1.2.0 - */ - public Builder setTrace(LineString trace) { - this.trace = trace; - return this; - } - - private void validateProfile() throws ServicesException { - if (profile == null || !(profile.equals(DirectionsCriteria.PROFILE_CYCLING) - || profile.equals(DirectionsCriteria.PROFILE_DRIVING) - || profile.equals(DirectionsCriteria.PROFILE_WALKING))) { - throw new ServicesException( - "Using Mapbox Map Matching requires setting a valid profile."); - } - } - - private void validateGpsPrecision() throws ServicesException { - if (gpsPrecison != null && (gpsPrecison < 1 || gpsPrecison > 10)) { - throw new ServicesException( - "Using Mapbox Map Matching requires setting a valid GPS precision."); - } - } - - private void validateTrace() throws ServicesException { - if (trace == null || trace.getCoordinates() == null) { - throw new ServicesException("Using Mapbox Map Matching requires to set some " + - "coordinates representing the trace."); - } - - if (trace.getCoordinates().size() > 100) { - throw new ServicesException("The Map Matching API is limited to processing traces " + - "with up to 100 coordinates. If you need to process longer traces, you can " + - "split the trace and make multiple requests."); - } - } - - /** - * Builder method - * - * @return MapboxMapMatching - * @throws ServicesException Generic Exception occuring when something with map matching - * goes wrong. - * @since 1.2.0 - */ - @Override - public MapboxMapMatching build() throws ServicesException { - validateAccessToken(accessToken); - validateProfile(); - validateGpsPrecision(); - validateTrace(); - return new MapboxMapMatching(this); - } + public Builder setTrace(LineString trace) { + this.trace = trace; + return this; + } + + private void validateProfile() throws ServicesException { + if (profile == null || !(profile.equals(DirectionsCriteria.PROFILE_CYCLING) + || profile.equals(DirectionsCriteria.PROFILE_DRIVING) + || profile.equals(DirectionsCriteria.PROFILE_WALKING))) { + throw new ServicesException( + "Using Mapbox Map Matching requires setting a valid profile."); + } + } + private void validateGpsPrecision() throws ServicesException { + if (gpsPrecison != null && (gpsPrecison < 1 || gpsPrecison > 10)) { + throw new ServicesException( + "Using Mapbox Map Matching requires setting a valid GPS precision."); + } } + + private void validateTrace() throws ServicesException { + if (trace == null || trace.getCoordinates() == null) { + throw new ServicesException("Using Mapbox Map Matching requires to set some " + + "coordinates representing the trace."); + } + + if (trace.getCoordinates().size() > 100) { + throw new ServicesException("The Map Matching API is limited to processing traces " + + "with up to 100 coordinates. If you need to process longer traces, you can " + + "split the trace and make multiple requests."); + } + } + + /** + * Builder method + * + * @return MapboxMapMatching + * @throws ServicesException Generic Exception occuring when something with map matching + * goes wrong. + * @since 1.2.0 + */ + @Override + public MapboxMapMatching build() throws ServicesException { + validateAccessToken(accessToken); + validateProfile(); + validateGpsPrecision(); + validateTrace(); + return new MapboxMapMatching(this); + } + + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/gson/MapMatchingGeometryDeserializer.java b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/gson/MapMatchingGeometryDeserializer.java index 2af1c81b6..fc4a6926f 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/gson/MapMatchingGeometryDeserializer.java +++ b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/gson/MapMatchingGeometryDeserializer.java @@ -20,26 +20,27 @@ */ public class MapMatchingGeometryDeserializer implements JsonDeserializer { - /** - * A custom deserializer that assumes a Polyline string. - *

- * In case of a json object, null is returned to support the {@code geometry=false} option - * (empty object is returned instead of null) - * - * @param json The Json data being deserialized. - * @param typeOfT The type of the Object to deserialize to. - * @param context Context for deserialization. - * @return Deserialized Geometry. - * @throws JsonParseException This exception is raised if there is a serious issue that occurs - * during parsing of a Json string. - * @since 1.2.0 - */ - @Override - public Geometry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - if (json.isJsonObject()) { - return null; - } else { - return LineString.fromPolyline(json.getAsString(), Constants.OSRM_PRECISION_V4); - } + /** + * A custom deserializer that assumes a Polyline string. + *

+ * In case of a json object, null is returned to support the {@code geometry=false} option + * (empty object is returned instead of null) + * + * @param json The Json data being deserialized. + * @param typeOfT The type of the Object to deserialize to. + * @param context Context for deserialization. + * @return Deserialized Geometry. + * @throws JsonParseException This exception is raised if there is a serious issue that occurs + * during parsing of a Json string. + * @since 1.2.0 + */ + @Override + public Geometry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + if (json.isJsonObject()) { + return null; + } else { + return LineString.fromPolyline(json.getAsString(), Constants.OSRM_PRECISION_V4); } + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/models/MapMatchingResponse.java b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/models/MapMatchingResponse.java index 31c3ed10a..231ebad2c 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/models/MapMatchingResponse.java +++ b/libjava/lib/src/main/java/com/mapbox/services/mapmatching/v4/models/MapMatchingResponse.java @@ -15,70 +15,71 @@ */ public class MapMatchingResponse extends FeatureCollection { - private static final String KEY_MATCHED_POINTS = "matchedPoints"; + private static final String KEY_MATCHED_POINTS = "matchedPoints"; - private String code; + private String code; - public MapMatchingResponse(List features) { - super(features); - } + public MapMatchingResponse(List features) { + super(features); + } - /** - * A string depicting the state of the response. - *

    - *
  • "Ok" - Normal case
  • - *
  • "NoMatch" - The input did not produce any matches. {@link Feature} will be an empty array.
  • - *
  • "TooManyCoordinates" - There are more than 100 points in the request.
  • - *
  • "InvalidInput" - message will hold an explanation of the invalid input.
  • - *
  • "ProfileNotFound" - Profile should be {@code mapbox.driving} , {@code mapbox.walking} , or {@code mapbox.cycling}.
  • - *
- * - * @return String containing the code. - * @since 1.2.0 - */ - public String getCode() { - return code; - } + /** + * A string depicting the state of the response. + *
    + *
  • "Ok" - Normal case
  • + *
  • "NoMatch" - The input did not produce any matches. {@link Feature} will be an empty array.
  • + *
  • "TooManyCoordinates" - There are more than 100 points in the request.
  • + *
  • "InvalidInput" - message will hold an explanation of the invalid input.
  • + *
  • "ProfileNotFound" - Profile should be {@code mapbox.driving}, {@code mapbox.walking}, + * or {@code mapbox.cycling}.
  • + *
+ * + * @return String containing the code. + * @since 1.2.0 + */ + public String getCode() { + return code; + } - /** - * @param code String containing the code. - * @since 1.2.0 - */ - public void setCode(String code) { - this.code = code; - } + /** + * @param code String containing the code. + * @since 1.2.0 + */ + public void setCode(String code) { + this.code = code; + } - /** - * Convenience method to obtain the list of matched points. - * - * @return Array of {@link Position} that have been map matched. - * @since 1.2.0 - */ - public Position[] getMatchedPoints() { - return getMatchedPoints(0); - } + /** + * Convenience method to obtain the list of matched points. + * + * @return Array of {@link Position} that have been map matched. + * @since 1.2.0 + */ + public Position[] getMatchedPoints() { + return getMatchedPoints(0); + } - /** - * Convenience method to obtain the list of matched points for other matches. When the matching - * algorithm cannot decide the correct match between two points, it will omit that line and - * create several sub-matches, each as a feature. The higher the number of features, the more - * likely that the input traces are poorly aligned to the road network. - * - * @param submatch Which sub-match you want to get the position for. - * @return Array of {@link Position} that have been map matched. - * @since 1.2.0 - */ - public Position[] getMatchedPoints(int submatch) { - JsonObject properties = getFeatures().get(submatch).getProperties(); - JsonArray points = properties.getAsJsonArray(KEY_MATCHED_POINTS); + /** + * Convenience method to obtain the list of matched points for other matches. When the matching + * algorithm cannot decide the correct match between two points, it will omit that line and + * create several sub-matches, each as a feature. The higher the number of features, the more + * likely that the input traces are poorly aligned to the road network. + * + * @param submatch Which sub-match you want to get the position for. + * @return Array of {@link Position} that have been map matched. + * @since 1.2.0 + */ + public Position[] getMatchedPoints(int submatch) { + JsonObject properties = getFeatures().get(submatch).getProperties(); + JsonArray points = properties.getAsJsonArray(KEY_MATCHED_POINTS); - Position[] positions = new Position[points.size()]; - for (int i = 0; i < points.size(); i++) { - positions[i] = Position.fromCoordinates( - points.get(i).getAsJsonArray().get(0).getAsDouble(), - points.get(i).getAsJsonArray().get(1).getAsDouble()); - } - return positions; + Position[] positions = new Position[points.size()]; + for (int i = 0; i < points.size(); i++) { + positions[i] = Position.fromCoordinates( + points.get(i).getAsJsonArray().get(0).getAsDouble(), + points.get(i).getAsJsonArray().get(1).getAsDouble()); } + return positions; + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/navigation/v5/RouteUtils.java b/libjava/lib/src/main/java/com/mapbox/services/navigation/v5/RouteUtils.java index 5ec2d83a5..c4e692959 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/navigation/v5/RouteUtils.java +++ b/libjava/lib/src/main/java/com/mapbox/services/navigation/v5/RouteUtils.java @@ -23,164 +23,166 @@ */ public class RouteUtils { - // Default threshold for the user to be considered to be off-route (100 meters) - public static final double DEFAULT_OFF_ROUTE_THRESHOLD_KM = 0.1; - - private double offRouteThresholdKm; - - /** - * RouteUtils constructor using default threshold of 100 meters. - * - * @since 1.3.0 - */ - public RouteUtils() { - this.offRouteThresholdKm = DEFAULT_OFF_ROUTE_THRESHOLD_KM; + // Default threshold for the user to be considered to be off-route (100 meters) + public static final double DEFAULT_OFF_ROUTE_THRESHOLD_KM = 0.1; + + private double offRouteThresholdKm; + + /** + * RouteUtils constructor using default threshold of 100 meters. + * + * @since 1.3.0 + */ + public RouteUtils() { + this.offRouteThresholdKm = DEFAULT_OFF_ROUTE_THRESHOLD_KM; + } + + /** + * RouteUtils constructor allowing you to pass in a threshold value. + * + * @param offRouteThresholdKm Double value using unit kilometers. This value determines the + * distance till you are notified. + * @since 1.3.0 + */ + public RouteUtils(double offRouteThresholdKm) { + this.offRouteThresholdKm = offRouteThresholdKm; + } + + /** + * @return the RouteUtils threshold as a double value; defaults 100 meters. + * @since 1.3.0 + */ + public double getOffRouteThresholdKm() { + return offRouteThresholdKm; + } + + /** + * Compute the distance between the position and the step line (the closest point), and checks + * if it's within the off-route threshold. + * + * @param position you want to verify is on or near the route step. If using for navigation, + * this would typically be the users current location. + * @param route a directions route. + * @param stepIndex integer index for step in route. + * @return true if the position is outside the OffRoute threshold. + * @throws ServicesException if error occurs Mapbox API related. + * @throws TurfException signals that a Turf exception of some sort has occurred. + * @since 1.3.0 + */ + public boolean isInStep(Position position, RouteLeg route, int stepIndex) throws ServicesException, TurfException { + double distance = getDistanceToStep(position, route, stepIndex); + return (distance <= offRouteThresholdKm); + } + + /** + * Computes the distance between the position and the closest point in route step. + * + * @param position you want to measure distance to from route. If using for navigation, this + * would typically be the users current location. + * @param route a directions route. + * @param stepIndex integer index for step in route. + * @return double value giving distance in kilometers. + * @throws ServicesException if error occurs Mapbox API related. + * @throws TurfException signals that a Turf exception of some sort has occurred. + * @since 1.3.0 + */ + public double getDistanceToStep(Position position, RouteLeg route, int stepIndex) throws ServicesException, + TurfException { + Position closestPoint = getSnapToRoute(position, route, stepIndex); + return TurfMeasurement.distance( + Point.fromCoordinates(position), + Point.fromCoordinates(closestPoint), + TurfConstants.UNIT_DEFAULT + ); + } + + /** + * Snaps given position to a {@link RouteLeg} step. + * + * @param position that you want to snap to route. If using for navigation, this would + * typically be the users current location. + * @param route that you want to snap position to. + * @param stepIndex integer index for step in route. + * @return your position snapped to the route. + * @throws ServicesException if error occurs Mapbox API related. + * @throws TurfException signals that a Turf exception of some sort has occurred. + * @since 1.3.0 + */ + public Position getSnapToRoute(Position position, RouteLeg route, int stepIndex) throws ServicesException, TurfException { + LegStep step = validateStep(route, stepIndex); + + // Decode the geometry + List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); + + // No need to do the math if the step has one coordinate only + if (coords.size() == 1) { + return coords.get(0); } - /** - * RouteUtils constructor allowing you to pass in a threshold value. - * - * @param offRouteThresholdKm Double value using unit kilometers. This value determines the - * distance till you are notified. - * @since 1.3.0 - */ - public RouteUtils(double offRouteThresholdKm) { - this.offRouteThresholdKm = offRouteThresholdKm; + // Uses Turf's pointOnLine, which takes a Point and a LineString to calculate the closest + // Point on the LineString. + Feature point = TurfMisc.pointOnLine(Point.fromCoordinates(position), coords); + return ((Point) point.getGeometry()).getCoordinates(); + } + + /** + * Method to check whether the position given is outside the route using the threshold. + * + * @param position you want to verify is on or near the route. If using for navigation, this + * would typically be the users current location. + * @param route a directions route. + * @return true if the position is beyond the threshold limit from the route. + * @throws ServicesException if error occurs Mapbox API related. + * @throws TurfException signals that a Turf exception of some sort has occurred. + * @since 1.3.0 + */ + public boolean isOffRoute(Position position, RouteLeg route) throws ServicesException, TurfException { + for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { + if (isInStep(position, route, stepIndex)) { + // We aren't off-route if we're close to at least one route step + return false; + } } - /** - * @return the RouteUtils threshold as a double value; defaults 100 meters. - * @since 1.3.0 - */ - public double getOffRouteThresholdKm() { - return offRouteThresholdKm; + return true; + } + + /** + * Get the closest route step to the given position. + * + * @param position that you want to get closest route step to. + * @param route a directions route. + * @return integer step index in route leg. + * @throws ServicesException if error occurs Mapbox API related. + * @throws TurfException signals that a Turf exception of some sort has occurred. + * @since 1.3.0 + */ + public int getClosestStep(Position position, RouteLeg route) throws ServicesException, TurfException { + double minDistance = Double.MAX_VALUE; + int closestIndex = 0; + + double distance; + for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { + distance = getDistanceToStep(position, route, stepIndex); + if (distance < minDistance) { + minDistance = distance; + closestIndex = stepIndex; + } } - /** - * Compute the distance between the position and the step line (the closest point), and checks - * if it's within the off-route threshold. - * - * @param position you want to verify is on or near the route step. If using for navigation, - * this would typically be the users current location. - * @param route a directions route. - * @param stepIndex integer index for step in route. - * @return true if the position is outside the OffRoute threshold. - * @throws ServicesException if error occurs Mapbox API related. - * @throws TurfException signals that a Turf exception of some sort has occurred. - * @since 1.3.0 - */ - public boolean isInStep(Position position, RouteLeg route, int stepIndex) throws ServicesException, TurfException { - double distance = getDistanceToStep(position, route, stepIndex); - return (distance <= offRouteThresholdKm); + return closestIndex; + } + + private LegStep validateStep(RouteLeg route, int stepIndex) throws ServicesException { + if (route == null) { + throw new ServicesException("The provided route is empty."); + } else if (route.getSteps() == null || route.getSteps().size() == 0) { + throw new ServicesException("The provided route has an empty set of steps."); + } else if (stepIndex >= route.getSteps().size()) { + throw new ServicesException(String.format( + Locale.US, "The provided route doesn't have so many steps (%d).", stepIndex)); } - /** - * Computes the distance between the position and the closest point in route step. - * - * @param position you want to measure distance to from route. If using for navigation, this - * would typically be the users current location. - * @param route a directions route. - * @param stepIndex integer index for step in route. - * @return double value giving distance in kilometers. - * @throws ServicesException if error occurs Mapbox API related. - * @throws TurfException signals that a Turf exception of some sort has occurred. - * @since 1.3.0 - */ - public double getDistanceToStep(Position position, RouteLeg route, int stepIndex) throws ServicesException, TurfException { - Position closestPoint = getSnapToRoute(position, route, stepIndex); - return TurfMeasurement.distance( - Point.fromCoordinates(position), - Point.fromCoordinates(closestPoint), - TurfConstants.UNIT_DEFAULT - ); - } - - /** - * Snaps given position to a {@link RouteLeg} step. - * - * @param position that you want to snap to route. If using for navigation, this would - * typically be the users current location. - * @param route that you want to snap position to. - * @param stepIndex integer index for step in route. - * @return your position snapped to the route. - * @throws ServicesException if error occurs Mapbox API related. - * @throws TurfException signals that a Turf exception of some sort has occurred. - * @since 1.3.0 - */ - public Position getSnapToRoute(Position position, RouteLeg route, int stepIndex) throws ServicesException, TurfException { - LegStep step = validateStep(route, stepIndex); - - // Decode the geometry - List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); - - // No need to do the math if the step has one coordinate only - if (coords.size() == 1) { - return coords.get(0); - } - - // Uses Turf's pointOnLine, which takes a Point and a LineString to calculate the closest - // Point on the LineString. - Feature point = TurfMisc.pointOnLine(Point.fromCoordinates(position), coords); - return ((Point) point.getGeometry()).getCoordinates(); - } - - /** - * Method to check whether the position given is outside the route using the threshold. - * - * @param position you want to verify is on or near the route. If using for navigation, this - * would typically be the users current location. - * @param route a directions route. - * @return true if the position is beyond the threshold limit from the route. - * @throws ServicesException if error occurs Mapbox API related. - * @throws TurfException signals that a Turf exception of some sort has occurred. - * @since 1.3.0 - */ - public boolean isOffRoute(Position position, RouteLeg route) throws ServicesException, TurfException { - for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { - if (isInStep(position, route, stepIndex)) { - // We aren't off-route if we're close to at least one route step - return false; - } - } - - return true; - } - - /** - * Get the closest route step to the given position. - * - * @param position that you want to get closest route step to. - * @param route a directions route. - * @return integer step index in route leg. - * @throws ServicesException if error occurs Mapbox API related. - * @throws TurfException signals that a Turf exception of some sort has occurred. - * @since 1.3.0 - */ - public int getClosestStep(Position position, RouteLeg route) throws ServicesException, TurfException { - double minDistance = Double.MAX_VALUE; - int closestIndex = 0; - - double distance; - for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { - distance = getDistanceToStep(position, route, stepIndex); - if (distance < minDistance) { - minDistance = distance; - closestIndex = stepIndex; - } - } - - return closestIndex; - } - - private LegStep validateStep(RouteLeg route, int stepIndex) throws ServicesException { - if (route == null) { - throw new ServicesException("The provided route is empty."); - } else if (route.getSteps() == null || route.getSteps().size() == 0) { - throw new ServicesException("The provided route has an empty set of steps."); - } else if (stepIndex >= route.getSteps().size()) { - throw new ServicesException(String.format(Locale.US, "The provided route doesn't have so many steps (%d).", stepIndex)); - } - - return route.getSteps().get(stepIndex); - } + return route.getSteps().get(stepIndex); + } } diff --git a/libjava/lib/src/main/java/com/mapbox/services/staticimage/v1/MapboxStaticImage.java b/libjava/lib/src/main/java/com/mapbox/services/staticimage/v1/MapboxStaticImage.java index c4a29646e..bfdf4f404 100644 --- a/libjava/lib/src/main/java/com/mapbox/services/staticimage/v1/MapboxStaticImage.java +++ b/libjava/lib/src/main/java/com/mapbox/services/staticimage/v1/MapboxStaticImage.java @@ -21,390 +21,390 @@ */ public class MapboxStaticImage { - private HttpUrl url; + private HttpUrl url; + + /** + * Build the static image API URL using the builder. + * + * @param builder The MapboxStaticImage builder. + * @since 1.0.0 + */ + public MapboxStaticImage(Builder builder) { + HttpUrl.Builder urlBuilder = new HttpUrl.Builder() + .scheme("https") + .host("api.mapbox.com") + .addPathSegment("styles") + .addPathSegment("v1") + .addPathSegment(builder.getUsername()) + .addPathSegment(builder.getStyleId()) + .addPathSegment("static") + .addPathSegment(builder.getLocationPathSegment()) + .addPathSegment(builder.getSizePathSegment()) + .addQueryParameter("access_token", builder.getAccessToken()); + + if (!builder.isAttribution()) { + // Default is true + urlBuilder.addQueryParameter("attribution", "false"); + } + + if (!builder.isLogo()) { + // Default is true + urlBuilder.addQueryParameter("logo", "false"); + } + + url = urlBuilder.build(); + } + + /** + * If you need the API URL you can request it with this method. + * + * @return the built API URL. + * @since 1.0.0 + */ + public HttpUrl getUrl() { + return url; + } + + /** + * Static image builder used to customize the image, including location, image width/height, + * and camera position. + * + * @since 1.0.0 + */ + public static class Builder extends MapboxBuilder { + + // Set defaults for optional fields + private String accessToken; + private String username = Constants.MAPBOX_USER; + private String styleId; + private Double lon; + private Double lat; + private Double zoom; + private double bearing = 0; + private double pitch = 0; + private Integer width; + private Integer height; + private boolean retina = false; + private boolean attribution = true; + private boolean logo = true; + + // This field isn't part of the URL + private int precision = -1; + + /** + * Required to call when building {@link com.mapbox.services.staticimage.v1.MapboxStaticImage.Builder}. + * + * @param accessToken Mapbox access token, you must have a Mapbox account in order to use + * this library. + * @return Builder + * @since 1.0.0 + */ + @Override + public Builder setAccessToken(String accessToken) { + this.accessToken = accessToken; + return this; + } + + /** + * Set the map style username. Typically will either be your Mapbox username or if you are + * using one of the defaults Mapbox + * styles, the username will be "mapbox". + * + * @param username You will need to pass in your Mapbox username. + * @return Builder + * @since 1.0.0 + */ + public Builder setUsername(String username) { + this.username = username; + return this; + } + + /** + * You'll need to set what map style you'd like the static image to display. + * + * @param styleId can be one of the defaults or your own. + * @return Builder + * @since 1.0.0 + */ + public Builder setStyleId(String styleId) { + this.styleId = styleId; + return this; + } + + /** + * Longitude for the center point of the static map. + * + * @param lon double number between -180 and 180. + * @return Builder + * @since 1.0.0 + */ + public Builder setLon(double lon) { + this.lon = lon; + return this; + } + + /** + * Latitude for the center point of the static map. + * + * @param lat double number between -90 and 90. + * @return Builder + * @since 1.0.0 + */ + public Builder setLat(double lat) { + this.lat = lat; + return this; + } + + /** + * Location for the center point of the static map. + * + * @param position Position object with valid latitude and longitude values + * @return Builder + * @since 1.2.0 + */ + public Builder setLocation(Position position) { + this.lat = position.getLatitude(); + this.lon = position.getLongitude(); + return this; + } + + /** + * static map zoom level. Fractional zoom levels will be rounded to two decimal places. + * + * @param zoom double number between 0 and 22. + * @return Builder + * @since 1.0.0 + */ + public Builder setZoom(double zoom) { + this.zoom = zoom; + return this; + } + + /** + * Optionally, bearing rotates the map around its center. A value of 90 rotates the map 90° + * to the left. 180 flips the map. Defaults is 0. + * + * @param bearing double number between 0 and 360, interpreted as decimal degrees. + * @return Builder + * @since 1.0.0 + */ + public Builder setBearing(double bearing) { + this.bearing = bearing; + return this; + } + + /** + * Optionally, pitch tilts the map, producing a perspective effect. Defaults is 0. + * + * @param pitch double number between 0 and 60. + * @return Builder + * @since 1.0.0 + */ + public Builder setPitch(double pitch) { + this.pitch = pitch; + return this; + } + + /** + * width of the image. + * + * @param width int number between 1 and 1280. + * @return Builder + * @since 1.0.0 + */ + public Builder setWidth(int width) { + this.width = width; + return this; + } + + /** + * Height of the image. + * + * @param height int number between 1 and 1280. + * @return Builder + * @since 1.0.0 + */ + public Builder setHeight(int height) { + this.height = height; + return this; + } + + /** + * Optionally, use to request a retina 2x image that will be returned. + * + * @param retina true if you'd like a retina image. + * @return Builder + * @since 1.0.0 + */ + public Builder setRetina(boolean retina) { + this.retina = retina; + return this; + } + + /** + * Optionally, control whether there is attribution on the image. Default is true. + * + * @param attribution true places attribution on image. + * @return Builder + * @since 1.0.0 + */ + public Builder setAttribution(boolean attribution) { + this.attribution = attribution; + return this; + } + + /** + * Optionally, control whether there is a Mapbox logo on the image. Default is true. + * + * @param logo true places Mapbox logo on image. + * @return Builder + * @since 1.0.0 + */ + public Builder setLogo(boolean logo) { + this.logo = logo; + return this; + } /** - * Build the static image API URL using the builder. + * In order to make the returned images better cacheable on the client, you can set the + * precision in decimals instead of manually rounding the parameters. * - * @param builder The MapboxStaticImage builder. + * @param precision int number representing the precision for the formatter + * @return Builder * @since 1.0.0 */ - public MapboxStaticImage(Builder builder) { - HttpUrl.Builder urlBuilder = new HttpUrl.Builder() - .scheme("https") - .host("api.mapbox.com") - .addPathSegment("styles") - .addPathSegment("v1") - .addPathSegment(builder.getUsername()) - .addPathSegment(builder.getStyleId()) - .addPathSegment("static") - .addPathSegment(builder.getLocationPathSegment()) - .addPathSegment(builder.getSizePathSegment()) - .addQueryParameter("access_token", builder.getAccessToken()); - - if (!builder.isAttribution()) { - // Default is true - urlBuilder.addQueryParameter("attribution", "false"); - } - - if (!builder.isLogo()) { - // Default is true - urlBuilder.addQueryParameter("logo", "false"); - } - - url = urlBuilder.build(); + public Builder setPrecision(int precision) { + this.precision = precision; + return this; } /** - * If you need the API URL you can request it with this method. + * Get the access token * - * @return the built API URL. + * @return String with the access token * @since 1.0.0 */ - public HttpUrl getUrl() { - return url; + @Override + public String getAccessToken() { + return accessToken; } /** - * Static image builder used to customize the image, including location, image width/height, - * and camera position. + * Get the username you set within the builder. Typically your own Mapbox username or if you + * used a defaults Mapbox style, it will be "mapbox". * + * @return String with the username. * @since 1.0.0 */ - public static class Builder extends MapboxBuilder { - - // Set defaults for optional fields - private String accessToken; - private String username = Constants.MAPBOX_USER; - private String styleId; - private Double lon; - private Double lat; - private Double zoom; - private double bearing = 0; - private double pitch = 0; - private Integer width; - private Integer height; - private boolean retina = false; - private boolean attribution = true; - private boolean logo = true; - - // This field isn't part of the URL - private int precision = -1; - - /** - * Required to call when building {@link com.mapbox.services.staticimage.v1.MapboxStaticImage.Builder}. - * - * @param accessToken Mapbox access token, you must have a Mapbox account in order to use - * this library. - * @return Builder - * @since 1.0.0 - */ - @Override - public Builder setAccessToken(String accessToken) { - this.accessToken = accessToken; - return this; - } - - /** - * Set the map style username. Typically will either be your Mapbox username or if you are - * using one of the defaults Mapbox - * styles, the username will be "mapbox". - * - * @param username You will need to pass in your Mapbox username. - * @return Builder - * @since 1.0.0 - */ - public Builder setUsername(String username) { - this.username = username; - return this; - } - - /** - * You'll need to set what map style you'd like the static image to display. - * - * @param styleId can be one of the defaults or your own. - * @return Builder - * @since 1.0.0 - */ - public Builder setStyleId(String styleId) { - this.styleId = styleId; - return this; - } - - /** - * Longitude for the center point of the static map. - * - * @param lon double number between -180 and 180. - * @return Builder - * @since 1.0.0 - */ - public Builder setLon(double lon) { - this.lon = lon; - return this; - } - - /** - * Latitude for the center point of the static map. - * - * @param lat double number between -90 and 90. - * @return Builder - * @since 1.0.0 - */ - public Builder setLat(double lat) { - this.lat = lat; - return this; - } - - /** - * Location for the center point of the static map. - * - * @param position Position object with valid latitude and longitude values - * @return Builder - * @since 1.2.0 - */ - public Builder setLocation(Position position) { - this.lat = position.getLatitude(); - this.lon = position.getLongitude(); - return this; - } - - /** - * static map zoom level. Fractional zoom levels will be rounded to two decimal places. - * - * @param zoom double number between 0 and 22. - * @return Builder - * @since 1.0.0 - */ - public Builder setZoom(double zoom) { - this.zoom = zoom; - return this; - } - - /** - * Optionally, bearing rotates the map around its center. A value of 90 rotates the map 90° - * to the left. 180 flips the map. Defaults is 0. - * - * @param bearing double number between 0 and 360, interpreted as decimal degrees. - * @return Builder - * @since 1.0.0 - */ - public Builder setBearing(double bearing) { - this.bearing = bearing; - return this; - } - - /** - * Optionally, pitch tilts the map, producing a perspective effect. Defaults is 0. - * - * @param pitch double number between 0 and 60. - * @return Builder - * @since 1.0.0 - */ - public Builder setPitch(double pitch) { - this.pitch = pitch; - return this; - } - - /** - * width of the image. - * - * @param width int number between 1 and 1280. - * @return Builder - * @since 1.0.0 - */ - public Builder setWidth(int width) { - this.width = width; - return this; - } - - /** - * Height of the image. - * - * @param height int number between 1 and 1280. - * @return Builder - * @since 1.0.0 - */ - public Builder setHeight(int height) { - this.height = height; - return this; - } - - /** - * Optionally, use to request a retina 2x image that will be returned. - * - * @param retina true if you'd like a retina image. - * @return Builder - * @since 1.0.0 - */ - public Builder setRetina(boolean retina) { - this.retina = retina; - return this; - } - - /** - * Optionally, control whether there is attribution on the image. Default is true. - * - * @param attribution true places attribution on image. - * @return Builder - * @since 1.0.0 - */ - public Builder setAttribution(boolean attribution) { - this.attribution = attribution; - return this; - } - - /** - * Optionally, control whether there is a Mapbox logo on the image. Default is true. - * - * @param logo true places Mapbox logo on image. - * @return Builder - * @since 1.0.0 - */ - public Builder setLogo(boolean logo) { - this.logo = logo; - return this; - } - - /** - * In order to make the returned images better cacheable on the client, you can set the - * precision in decimals instead of manually rounding the parameters. - * - * @param precision int number representing the precision for the formatter - * @return Builder - * @since 1.0.0 - */ - public Builder setPrecision(int precision) { - this.precision = precision; - return this; - } - - /** - * Get the access token - * - * @return String with the access token - * @since 1.0.0 - */ - @Override - public String getAccessToken() { - return accessToken; - } - - /** - * Get the username you set within the builder. Typically your own Mapbox username or if you - * used a defaults Mapbox style, it will be "mapbox". - * - * @return String with the username. - * @since 1.0.0 - */ - public String getUsername() { - return username; - } - - /** - * Get what map style your static image will display. - * - * @return String containing static map id. - * @since 1.0.0 - */ - public String getStyleId() { - return styleId; - } - - /** - * Gives location information about the static image including longitude, latitude, zoom, - * bearing, and pitch. - * - * @return String value with static image location information. - * @since 1.0.0 - */ - public String getLocationPathSegment() { - if (precision > 0) { - String pattern = "0." + new String(new char[precision]).replace("\0", "0"); - DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - df.applyPattern(pattern); - df.setRoundingMode(RoundingMode.FLOOR); - return String.format(Locale.US, "%s,%s,%s,%s,%s", - df.format(lon), df.format(lat), df.format(zoom), - df.format(bearing), df.format(pitch)); - } else { - return String.format(Locale.US, "%f,%f,%f,%f,%f", lon, lat, zoom, bearing, pitch); - } - } - - /** - * Gives the height and width of the static image. - * - * @return String giving width, height and retina. - * @since 1.0.0 - */ - public String getSizePathSegment() { - String retinaPath = retina ? "@2x" : ""; - return String.format(Locale.US, "%dx%d%s", width, height, retinaPath); - } - - /** - * Determine if the static image will contain attribution. - * - * @return true if attribution will be on static image. - * @since 1.0.0 - */ - public boolean isAttribution() { - return attribution; - } - - /** - * Determine if the static image will contain Mapbox logo. - * - * @return true if Mapbox logo will be on static image. - * @since 1.0.0 - */ - public boolean isLogo() { - return logo; - } - - /** - * @return int number representing the precision for the formatter - * @since 1.0.0 - */ - public int getPrecision() { - return precision; - } - - /** - * Build the client when all user parameters have been set. - * - * @return MapboxStaticImage - * @since 1.0.0 - */ - @Override - public MapboxStaticImage build() throws ServicesException { - validateAccessToken(accessToken); - - if (styleId == null || styleId.isEmpty()) { - throw new ServicesException("You need to set a map style."); - } - - if (lon == null || lat == null) { - throw new ServicesException("You need to set the map lon/lat coordinates."); - } - - if (zoom == null) { - throw new ServicesException("You need to set the map zoom level."); - } - - if (width == null || width < 1 || width > 1280) { - throw new ServicesException( - "You need to set a valid image width (between 1 and 1280)."); - } - - if (height == null || height < 1 || height > 1280) { - throw new ServicesException( - "You need to set a valid image height (between 1 and 1280)."); - } - - return new MapboxStaticImage(this); - } + public String getUsername() { + return username; + } + /** + * Get what map style your static image will display. + * + * @return String containing static map id. + * @since 1.0.0 + */ + public String getStyleId() { + return styleId; } + /** + * Gives location information about the static image including longitude, latitude, zoom, + * bearing, and pitch. + * + * @return String value with static image location information. + * @since 1.0.0 + */ + public String getLocationPathSegment() { + if (precision > 0) { + String pattern = "0." + new String(new char[precision]).replace("\0", "0"); + DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.US); + df.applyPattern(pattern); + df.setRoundingMode(RoundingMode.FLOOR); + return String.format(Locale.US, "%s,%s,%s,%s,%s", + df.format(lon), df.format(lat), df.format(zoom), + df.format(bearing), df.format(pitch)); + } else { + return String.format(Locale.US, "%f,%f,%f,%f,%f", lon, lat, zoom, bearing, pitch); + } + } + + /** + * Gives the height and width of the static image. + * + * @return String giving width, height and retina. + * @since 1.0.0 + */ + public String getSizePathSegment() { + String retinaPath = retina ? "@2x" : ""; + return String.format(Locale.US, "%dx%d%s", width, height, retinaPath); + } + + /** + * Determine if the static image will contain attribution. + * + * @return true if attribution will be on static image. + * @since 1.0.0 + */ + public boolean isAttribution() { + return attribution; + } + + /** + * Determine if the static image will contain Mapbox logo. + * + * @return true if Mapbox logo will be on static image. + * @since 1.0.0 + */ + public boolean isLogo() { + return logo; + } + + /** + * @return int number representing the precision for the formatter + * @since 1.0.0 + */ + public int getPrecision() { + return precision; + } + + /** + * Build the client when all user parameters have been set. + * + * @return MapboxStaticImage + * @since 1.0.0 + */ + @Override + public MapboxStaticImage build() throws ServicesException { + validateAccessToken(accessToken); + + if (styleId == null || styleId.isEmpty()) { + throw new ServicesException("You need to set a map style."); + } + + if (lon == null || lat == null) { + throw new ServicesException("You need to set the map lon/lat coordinates."); + } + + if (zoom == null) { + throw new ServicesException("You need to set the map zoom level."); + } + + if (width == null || width < 1 || width > 1280) { + throw new ServicesException( + "You need to set a valid image width (between 1 and 1280)."); + } + + if (height == null || height < 1 || height > 1280) { + throw new ServicesException( + "You need to set a valid image height (between 1 and 1280)."); + } + + return new MapboxStaticImage(this); + } + + } + } diff --git a/libjava/lib/src/test/java/com/mapbox/services/BaseTest.java b/libjava/lib/src/test/java/com/mapbox/services/BaseTest.java index d1989e4c8..e2e886f6f 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/BaseTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/BaseTest.java @@ -9,21 +9,18 @@ import static org.junit.Assert.assertEquals; -/** - * Created by antonio on 7/15/16. - */ public class BaseTest { - protected final static double DELTA = 1E-10; + protected final static double DELTA = 1E-10; - public void compareJson(String json1, String json2) { - JsonParser parser = new JsonParser(); - assertEquals(parser.parse(json1), parser.parse(json2)); - } + public void compareJson(String json1, String json2) { + JsonParser parser = new JsonParser(); + assertEquals(parser.parse(json1), parser.parse(json2)); + } - protected String loadJsonFixture(String folder, String filename) throws IOException { - byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/" + folder + "/" + filename)); - return new String(content, StandardCharsets.UTF_8); - } + protected String loadJsonFixture(String folder, String filename) throws IOException { + byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/" + folder + "/" + filename)); + return new String(content, StandardCharsets.UTF_8); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/ConstantsTest.java b/libjava/lib/src/test/java/com/mapbox/services/ConstantsTest.java index 9105f72fb..3c806bcfd 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/ConstantsTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/ConstantsTest.java @@ -6,18 +6,15 @@ import static org.junit.Assert.*; -/** - * Created by antonio on 1/30/16. - */ public class ConstantsTest { - @Test - public void testApiSecure() { - assertTrue(Constants.BASE_API_URL.startsWith("https")); - } + @Test + public void testApiSecure() { + assertTrue(Constants.BASE_API_URL.startsWith("https")); + } - @Test - public void testUserAgent() { - assertTrue(MapboxService.getHeaderUserAgent().startsWith(Constants.HEADER_USER_AGENT)); - } + @Test + public void testUserAgent() { + assertTrue(MapboxService.getHeaderUserAgent().startsWith(Constants.HEADER_USER_AGENT)); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/directions/v5/MapboxDirectionsTest.java b/libjava/lib/src/test/java/com/mapbox/services/directions/v5/MapboxDirectionsTest.java index 016f6bf4f..116298c53 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/directions/v5/MapboxDirectionsTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/directions/v5/MapboxDirectionsTest.java @@ -34,260 +34,257 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -/** - * Created by antonio on 4/7/16. - */ public class MapboxDirectionsTest { - private final static double DELTA = 1E-10; - - private MockWebServer server; - private HttpUrl mockUrl; - - private ArrayList positions; - - @Before - public void setUp() throws IOException { - server = new MockWebServer(); - - byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/directions_v5.json")); - String body = new String(content, StandardCharsets.UTF_8); - server.enqueue(new MockResponse().setBody(body)); - - server.start(); - - mockUrl = server.url(""); - - positions = new ArrayList<>(); - positions.add(Position.fromCoordinates(-122.416667, 37.783333)); // SF - positions.add(Position.fromCoordinates(-121.9, 37.333333)); // SJ - } - - @After - public void tearDown() throws IOException { - server.shutdown(); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void requiredAccessToken() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Services requires setting a valid access token")); - new MapboxDirections.Builder().build(); - } - - @Test - public void requiredCoordinates() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You should provide at least two coordinates (from/to)")); - new MapboxDirections.Builder().setAccessToken("pk.XXX").build(); - } - - @Test - public void testSanity() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - assertEquals(response.code(), 200); - assertEquals(response.body().getCode(), DirectionsCriteria.RESPONSE_OK); - } - - @Test - public void testDirectionsResponse() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - DirectionsResponse body = response.body(); - assertEquals(body.getCode(), DirectionsCriteria.RESPONSE_OK); - assertEquals(body.getRoutes().size(), 1); - assertEquals(body.getWaypoints().size(), 2); - } - - @Test - public void testDirectionsRoute() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - DirectionsRoute route = response.body().getRoutes().get(0); - assertEquals(route.getDistance(), 77274.3, DELTA); - assertEquals(route.getDuration(), 3444.2, DELTA); - assertTrue(route.getGeometry().startsWith("kqreFhodjVhh")); - assertEquals(route.getLegs().size(), 1); - } - - @Test - public void testDirectionsWaypoint() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - DirectionsWaypoint waypoint = response.body().getWaypoints().get(0); - assertEquals(waypoint.getName(), "Eddy Street"); - assertEquals(waypoint.asPosition().getLongitude(), -122.416685, DELTA); - assertEquals(waypoint.asPosition().getLatitude(), 37.783424, DELTA); - } - - @Test - public void testRouteLeg() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - RouteLeg leg = response.body().getRoutes().get(0).getLegs().get(0); - assertEquals(leg.getDistance(), 77274.3, DELTA); - assertEquals(leg.getDuration(), 3444.2, DELTA); - assertEquals(leg.getSummary(), "James Lick Freeway (US 101), Bayshore Freeway (US 101)"); - assertEquals(leg.getSteps().size(), 14); - } - - @Test - public void testLegStep() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - LegStep step = response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(0); - assertEquals(step.getDistance(), 223.1, DELTA); - assertEquals(step.getDuration(), 52.0, DELTA); - assertEquals(step.getGeometry(), "kqreFhodjVRjDh@fI"); - assertEquals(step.getName(), "Eddy Street"); - assertEquals(step.getMode(), "driving"); - assertNotEquals(step.getManeuver(), null); - assertEquals(step.getIntersections().size(), 2); - } - - @Test - public void testStepIntersection() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - StepIntersection intersection = response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(0).getIntersections().get(1); - assertEquals(intersection.asPosition().getLongitude(), -122.417548, DELTA); - assertEquals(intersection.asPosition().getLatitude(), 37.783315, DELTA); - assertArrayEquals(intersection.getBearings(), new int[] {75, 165, 255, 345}); - assertArrayEquals(intersection.getEntry(), new boolean[] {false, false, true, true}); - assertEquals(intersection.getIn(), 0); - assertEquals(intersection.getOut(), 2); - } - - @Test - public void testStepManeuver() throws ServicesException, IOException { - MapboxDirections client = new MapboxDirections.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(positions) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - StepManeuver maneuver = response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(0).getManeuver(); - assertEquals(maneuver.asPosition().getLongitude(), -122.416685, DELTA); - assertEquals(maneuver.asPosition().getLatitude(), 37.783424, DELTA); - assertEquals(maneuver.getBearingBefore(), 0, DELTA); - assertEquals(maneuver.getBearingAfter(), 261, DELTA); - assertEquals(maneuver.getType(), "depart"); - assertEquals(maneuver.getModifier(), "left"); - assertEquals(maneuver.getInstruction(), "Head west on Eddy Street"); - } - - @Test - public void testSetCoordinates() { - ArrayList test = new ArrayList<>(); - test.add(Position.fromCoordinates(2.1, 2.2)); - test.add(Position.fromCoordinates(3.1, 3.2)); - - String coordinates = new MapboxDirections.Builder() - .setCoordinates(test) - .getCoordinates(); - assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); - } - - @Test - public void setOriginDestination() { - String coordinates = new MapboxDirections.Builder() - .setOrigin(Position.fromCoordinates(2.1, 2.2)) - .setDestination(Position.fromCoordinates(3.1, 3.2)) - .getCoordinates(); - assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); - } - - @Test - public void testSetCoordinatesMixed() { - ArrayList test = new ArrayList<>(); - test.add(Position.fromCoordinates(2.1, 2.2)); - test.add(Position.fromCoordinates(3.1, 3.2)); - - // Respect previously entered coordinates - String coordinates = new MapboxDirections.Builder() - .setCoordinates(test) - .setOrigin(Position.fromCoordinates(1.1, 1.2)) - .setDestination(Position.fromCoordinates(4.1, 4.2)) - .getCoordinates(); - assertEquals(coordinates, "1.100000,1.200000;2.100000,2.200000;3.100000,3.200000;4.100000,4.200000"); - } - - @Test - public void testSetCoordinatesMixedHidden() { - ArrayList test = new ArrayList<>(); - test.add(Position.fromCoordinates(2.1, 2.2)); - test.add(Position.fromCoordinates(3.1, 3.2)); - - // The order matters - String coordinates = new MapboxDirections.Builder() - .setOrigin(Position.fromCoordinates(1.1, 1.2)) - .setDestination(Position.fromCoordinates(4.1, 4.2)) - .setCoordinates(test) - .getCoordinates(); - assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); - } - - @Test - public void TestLocale() { - ArrayList test = new ArrayList<>(); - test.add(Position.fromCoordinates(2.1, 2.2)); - test.add(Position.fromCoordinates(3.1, 3.2)); - - // Locale shouldn't matter (#39) - Locale.setDefault(Locale.GERMANY); - String coordinates = new MapboxDirections.Builder() - .setOrigin(Position.fromCoordinates(1.1, 1.2)) - .setDestination(Position.fromCoordinates(4.1, 4.2)) - .setCoordinates(test) - .getCoordinates(); - assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); - } + private final static double DELTA = 1E-10; + + private MockWebServer server; + private HttpUrl mockUrl; + + private ArrayList positions; + + @Before + public void setUp() throws IOException { + server = new MockWebServer(); + + byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/directions_v5.json")); + String body = new String(content, StandardCharsets.UTF_8); + server.enqueue(new MockResponse().setBody(body)); + + server.start(); + + mockUrl = server.url(""); + + positions = new ArrayList<>(); + positions.add(Position.fromCoordinates(-122.416667, 37.783333)); // SF + positions.add(Position.fromCoordinates(-121.9, 37.333333)); // SJ + } + + @After + public void tearDown() throws IOException { + server.shutdown(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void requiredAccessToken() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Services requires setting a valid access token")); + new MapboxDirections.Builder().build(); + } + + @Test + public void requiredCoordinates() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You should provide at least two coordinates (from/to)")); + new MapboxDirections.Builder().setAccessToken("pk.XXX").build(); + } + + @Test + public void testSanity() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + assertEquals(response.code(), 200); + assertEquals(response.body().getCode(), DirectionsCriteria.RESPONSE_OK); + } + + @Test + public void testDirectionsResponse() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + DirectionsResponse body = response.body(); + assertEquals(body.getCode(), DirectionsCriteria.RESPONSE_OK); + assertEquals(body.getRoutes().size(), 1); + assertEquals(body.getWaypoints().size(), 2); + } + + @Test + public void testDirectionsRoute() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + DirectionsRoute route = response.body().getRoutes().get(0); + assertEquals(route.getDistance(), 77274.3, DELTA); + assertEquals(route.getDuration(), 3444.2, DELTA); + assertTrue(route.getGeometry().startsWith("kqreFhodjVhh")); + assertEquals(route.getLegs().size(), 1); + } + + @Test + public void testDirectionsWaypoint() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + DirectionsWaypoint waypoint = response.body().getWaypoints().get(0); + assertEquals(waypoint.getName(), "Eddy Street"); + assertEquals(waypoint.asPosition().getLongitude(), -122.416685, DELTA); + assertEquals(waypoint.asPosition().getLatitude(), 37.783424, DELTA); + } + + @Test + public void testRouteLeg() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + RouteLeg leg = response.body().getRoutes().get(0).getLegs().get(0); + assertEquals(leg.getDistance(), 77274.3, DELTA); + assertEquals(leg.getDuration(), 3444.2, DELTA); + assertEquals(leg.getSummary(), "James Lick Freeway (US 101), Bayshore Freeway (US 101)"); + assertEquals(leg.getSteps().size(), 14); + } + + @Test + public void testLegStep() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + LegStep step = response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(0); + assertEquals(step.getDistance(), 223.1, DELTA); + assertEquals(step.getDuration(), 52.0, DELTA); + assertEquals(step.getGeometry(), "kqreFhodjVRjDh@fI"); + assertEquals(step.getName(), "Eddy Street"); + assertEquals(step.getMode(), "driving"); + assertNotEquals(step.getManeuver(), null); + assertEquals(step.getIntersections().size(), 2); + } + + @Test + public void testStepIntersection() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + StepIntersection intersection = response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(0).getIntersections().get(1); + assertEquals(intersection.asPosition().getLongitude(), -122.417548, DELTA); + assertEquals(intersection.asPosition().getLatitude(), 37.783315, DELTA); + assertArrayEquals(intersection.getBearings(), new int[] {75, 165, 255, 345}); + assertArrayEquals(intersection.getEntry(), new boolean[] {false, false, true, true}); + assertEquals(intersection.getIn(), 0); + assertEquals(intersection.getOut(), 2); + } + + @Test + public void testStepManeuver() throws ServicesException, IOException { + MapboxDirections client = new MapboxDirections.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(positions) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + StepManeuver maneuver = response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(0).getManeuver(); + assertEquals(maneuver.asPosition().getLongitude(), -122.416685, DELTA); + assertEquals(maneuver.asPosition().getLatitude(), 37.783424, DELTA); + assertEquals(maneuver.getBearingBefore(), 0, DELTA); + assertEquals(maneuver.getBearingAfter(), 261, DELTA); + assertEquals(maneuver.getType(), "depart"); + assertEquals(maneuver.getModifier(), "left"); + assertEquals(maneuver.getInstruction(), "Head west on Eddy Street"); + } + + @Test + public void testSetCoordinates() { + ArrayList test = new ArrayList<>(); + test.add(Position.fromCoordinates(2.1, 2.2)); + test.add(Position.fromCoordinates(3.1, 3.2)); + + String coordinates = new MapboxDirections.Builder() + .setCoordinates(test) + .getCoordinates(); + assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); + } + + @Test + public void setOriginDestination() { + String coordinates = new MapboxDirections.Builder() + .setOrigin(Position.fromCoordinates(2.1, 2.2)) + .setDestination(Position.fromCoordinates(3.1, 3.2)) + .getCoordinates(); + assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); + } + + @Test + public void testSetCoordinatesMixed() { + ArrayList test = new ArrayList<>(); + test.add(Position.fromCoordinates(2.1, 2.2)); + test.add(Position.fromCoordinates(3.1, 3.2)); + + // Respect previously entered coordinates + String coordinates = new MapboxDirections.Builder() + .setCoordinates(test) + .setOrigin(Position.fromCoordinates(1.1, 1.2)) + .setDestination(Position.fromCoordinates(4.1, 4.2)) + .getCoordinates(); + assertEquals(coordinates, "1.100000,1.200000;2.100000,2.200000;3.100000,3.200000;4.100000,4.200000"); + } + + @Test + public void testSetCoordinatesMixedHidden() { + ArrayList test = new ArrayList<>(); + test.add(Position.fromCoordinates(2.1, 2.2)); + test.add(Position.fromCoordinates(3.1, 3.2)); + + // The order matters + String coordinates = new MapboxDirections.Builder() + .setOrigin(Position.fromCoordinates(1.1, 1.2)) + .setDestination(Position.fromCoordinates(4.1, 4.2)) + .setCoordinates(test) + .getCoordinates(); + assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); + } + + @Test + public void TestLocale() { + ArrayList test = new ArrayList<>(); + test.add(Position.fromCoordinates(2.1, 2.2)); + test.add(Position.fromCoordinates(3.1, 3.2)); + + // Locale shouldn't matter (#39) + Locale.setDefault(Locale.GERMANY); + String coordinates = new MapboxDirections.Builder() + .setOrigin(Position.fromCoordinates(1.1, 1.2)) + .setDestination(Position.fromCoordinates(4.1, 4.2)) + .setCoordinates(test) + .getCoordinates(); + assertEquals(coordinates, "2.100000,2.200000;3.100000,3.200000"); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/CarmenFeatureTest.java b/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/CarmenFeatureTest.java index 325ad4c75..db7cbc17d 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/CarmenFeatureTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/CarmenFeatureTest.java @@ -7,50 +7,47 @@ import static org.junit.Assert.assertEquals; -/** - * Created by antonio on 7/25/16. - */ public class CarmenFeatureTest { - private final static double DELTA = 1E-10; - - @Test - public void testAllowStandalone() { - // Build the standalone object - double[] bbox = new double[]{1.2, 3.4, 5.6, 7.8}; - double[] center = new double[]{1.2, 3.4}; - double relevance = 1.2; - JsonObject properties = new JsonObject(); - properties.addProperty("foo1", "bar"); - CarmenFeature feature = new CarmenFeature(); - - // Type specific - feature.setText("Text field 1"); - feature.setPlaceName("Text field 2"); - feature.setBbox(bbox); - feature.setAddress("Text field 3"); - feature.setCenter(center); - feature.setContext(null); - feature.setRelevance(relevance); - - // Inherited - feature.setGeometry(null); - feature.setProperties(properties); - feature.setId("Text field 4"); - - // Checks - assertEquals(feature.getText(), "Text field 1"); - assertEquals(feature.getPlaceName(), "Text field 2"); - assertEquals(feature.getBbox(), bbox); - assertEquals(feature.getAddress(), "Text field 3"); - assertEquals(feature.getCenter(), center); - assertEquals(feature.getContext(), null); - assertEquals(feature.getRelevance(), relevance, DELTA); - assertEquals(feature.getGeometry(), null); - assertEquals(feature.getProperties(), properties); - assertEquals(feature.getStringProperty("foo1"), "bar"); - assertEquals(feature.hasNonNullValueForProperty("foo1"), true); - assertEquals(feature.hasNonNullValueForProperty("foo2"), false); - assertEquals(feature.getId(), "Text field 4"); - } + private final static double DELTA = 1E-10; + + @Test + public void testAllowStandalone() { + // Build the standalone object + double[] bbox = new double[] {1.2, 3.4, 5.6, 7.8}; + double[] center = new double[] {1.2, 3.4}; + double relevance = 1.2; + JsonObject properties = new JsonObject(); + properties.addProperty("foo1", "bar"); + CarmenFeature feature = new CarmenFeature(); + + // Type specific + feature.setText("Text field 1"); + feature.setPlaceName("Text field 2"); + feature.setBbox(bbox); + feature.setAddress("Text field 3"); + feature.setCenter(center); + feature.setContext(null); + feature.setRelevance(relevance); + + // Inherited + feature.setGeometry(null); + feature.setProperties(properties); + feature.setId("Text field 4"); + + // Checks + assertEquals(feature.getText(), "Text field 1"); + assertEquals(feature.getPlaceName(), "Text field 2"); + assertEquals(feature.getBbox(), bbox); + assertEquals(feature.getAddress(), "Text field 3"); + assertEquals(feature.getCenter(), center); + assertEquals(feature.getContext(), null); + assertEquals(feature.getRelevance(), relevance, DELTA); + assertEquals(feature.getGeometry(), null); + assertEquals(feature.getProperties(), properties); + assertEquals(feature.getStringProperty("foo1"), "bar"); + assertEquals(feature.hasNonNullValueForProperty("foo1"), true); + assertEquals(feature.hasNonNullValueForProperty("foo2"), false); + assertEquals(feature.getId(), "Text field 4"); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingReverseTest.java b/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingReverseTest.java index 71057023b..c44240dc3 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingReverseTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingReverseTest.java @@ -28,120 +28,117 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -/** - * Created by antonio on 4/14/16. - */ public class MapboxGeocodingReverseTest { - private final static double DELTA = 1E-10; - - private MockWebServer server; - private HttpUrl mockUrl; - - @Before - public void setUp() throws IOException { - server = new MockWebServer(); - - byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/geocoding_reverse.json")); - String body = new String(content, StandardCharsets.UTF_8); - server.enqueue(new MockResponse().setBody(body)); - - server.start(); - - mockUrl = server.url(""); - } - - @After - public void tearDown() throws IOException { - server.shutdown(); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testSanity() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setCoordinates(Position.fromCoordinates(-77.0366, 38.8971)) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - assertEquals(response.code(), 200); - } - - @Test - public void testBody() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - GeocodingResponse body = response.body(); - assertEquals(body.getType(), "FeatureCollection"); - - assertEquals(body.getQuery().get(0), String.valueOf(-77.0366)); - assertEquals(body.getQuery().get(1), String.valueOf(38.8971)); - - assertEquals(body.getFeatures().size(), 6); - assertTrue(body.getAttribution().startsWith("NOTICE")); - } - - @Test - public void testFeature() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - CarmenFeature feature = response.body().getFeatures().get(1); - assertEquals(feature.getId(), "neighborhood.7130293780113160"); - assertEquals(feature.getType(), "Feature"); - assertEquals(feature.getText(), "Franklin Mcpherson Square"); - assertEquals(feature.getPlaceName(), "Franklin Mcpherson Square, Washington, 20006, District of Columbia, United States"); - assertEquals(feature.getRelevance(), 1, DELTA); - assertEquals(feature.getProperties(), new JsonObject()); - assertEquals(feature.getBbox()[0], -77.0375061034999, DELTA); - assertEquals(feature.getBbox()[1], 38.8942394196779, DELTA); - assertEquals(feature.getBbox()[2], -77.0302262036302, DELTA); - assertEquals(feature.getBbox()[3], 38.9038583397001, DELTA); - assertEquals(feature.asPosition().getLongitude(), -77.033, DELTA); - assertEquals(feature.asPosition().getLatitude(), 38.9015, DELTA); - assertEquals(feature.getContext().size(), 4); - } - - @Test - public void testGeometry() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - Point point = (Point) response.body().getFeatures().get(1).getGeometry(); - assertEquals(point.getType(), "Point"); - assertEquals(point.getCoordinates().getLongitude(), -77.033, DELTA); - assertEquals(point.getCoordinates().getLatitude(), 38.9015, DELTA); - } - - @Test - public void testContext() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - List contexts = response.body().getFeatures().get(1).getContext(); - assertEquals(contexts.get(3).getId(), "country.12862386939497690"); - assertEquals(contexts.get(3).getText(), "United States"); - assertEquals(contexts.get(3).getShortCode(), "us"); - } + private final static double DELTA = 1E-10; + + private MockWebServer server; + private HttpUrl mockUrl; + + @Before + public void setUp() throws IOException { + server = new MockWebServer(); + + byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/geocoding_reverse.json")); + String body = new String(content, StandardCharsets.UTF_8); + server.enqueue(new MockResponse().setBody(body)); + + server.start(); + + mockUrl = server.url(""); + } + + @After + public void tearDown() throws IOException { + server.shutdown(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testSanity() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setCoordinates(Position.fromCoordinates(-77.0366, 38.8971)) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + assertEquals(response.code(), 200); + } + + @Test + public void testBody() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + GeocodingResponse body = response.body(); + assertEquals(body.getType(), "FeatureCollection"); + + assertEquals(body.getQuery().get(0), String.valueOf(-77.0366)); + assertEquals(body.getQuery().get(1), String.valueOf(38.8971)); + + assertEquals(body.getFeatures().size(), 6); + assertTrue(body.getAttribution().startsWith("NOTICE")); + } + + @Test + public void testFeature() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + CarmenFeature feature = response.body().getFeatures().get(1); + assertEquals(feature.getId(), "neighborhood.7130293780113160"); + assertEquals(feature.getType(), "Feature"); + assertEquals(feature.getText(), "Franklin Mcpherson Square"); + assertEquals(feature.getPlaceName(), "Franklin Mcpherson Square, Washington, 20006, District of Columbia, United States"); + assertEquals(feature.getRelevance(), 1, DELTA); + assertEquals(feature.getProperties(), new JsonObject()); + assertEquals(feature.getBbox()[0], -77.0375061034999, DELTA); + assertEquals(feature.getBbox()[1], 38.8942394196779, DELTA); + assertEquals(feature.getBbox()[2], -77.0302262036302, DELTA); + assertEquals(feature.getBbox()[3], 38.9038583397001, DELTA); + assertEquals(feature.asPosition().getLongitude(), -77.033, DELTA); + assertEquals(feature.asPosition().getLatitude(), 38.9015, DELTA); + assertEquals(feature.getContext().size(), 4); + } + + @Test + public void testGeometry() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + Point point = (Point) response.body().getFeatures().get(1).getGeometry(); + assertEquals(point.getType(), "Point"); + assertEquals(point.getCoordinates().getLongitude(), -77.033, DELTA); + assertEquals(point.getCoordinates().getLatitude(), 38.9015, DELTA); + } + + @Test + public void testContext() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + List contexts = response.body().getFeatures().get(1).getContext(); + assertEquals(contexts.get(3).getId(), "country.12862386939497690"); + assertEquals(contexts.get(3).getText(), "United States"); + assertEquals(contexts.get(3).getShortCode(), "us"); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingTest.java b/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingTest.java index 90ef735e2..64234b171 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geocoding/v5/MapboxGeocodingTest.java @@ -29,126 +29,126 @@ public class MapboxGeocodingTest { - private final static double DELTA = 1E-10; - - private MockWebServer server; - private HttpUrl mockUrl; - - @Before - public void setUp() throws IOException { - server = new MockWebServer(); - - byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/geocoding.json")); - String body = new String(content, StandardCharsets.UTF_8); - server.enqueue(new MockResponse().setBody(body)); - - server.start(); - - mockUrl = server.url(""); - } - - @After - public void tearDown() throws IOException { - server.shutdown(); - } - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testSanity() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - assertEquals(response.code(), 200); - } - - @Test - public void testBody() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - GeocodingResponse body = response.body(); - assertEquals(body.getType(), "FeatureCollection"); - - assertEquals(body.getQuery().get(0), "1600"); - assertEquals(body.getQuery().get(1), "pennsylvania"); - assertEquals(body.getQuery().get(2), "ave"); - assertEquals(body.getQuery().get(3), "nw"); - - assertEquals(body.getFeatures().size(), 5); - assertTrue(body.getAttribution().startsWith("NOTICE")); - } - - @Test - public void testFeature() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - CarmenFeature feature = response.body().getFeatures().get(0); - assertEquals(feature.getId(), "address.7626097581139850"); - assertEquals(feature.getType(), "Feature"); - assertEquals(feature.getText(), "Pennsylvania Ave NW"); - assertEquals(feature.getPlaceName(), "1600 Pennsylvania Ave NW, Washington, District of Columbia 20006, United States"); - assertEquals(feature.getRelevance(), 0.99, DELTA); - assertEquals(feature.getProperties(), new JsonObject()); - assertEquals(feature.asPosition().getLongitude(), -77.036543, DELTA); - assertEquals(feature.asPosition().getLatitude(), 38.897702, DELTA); - assertEquals(feature.getAddress(), "1600"); - assertEquals(feature.getContext().size(), 5); - } - - @Test - public void testGeometry() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - Point point = (Point) response.body().getFeatures().get(3).getGeometry(); - assertEquals(point.getType(), "Point"); - assertEquals(point.getCoordinates().getLongitude(), -74.236513, DELTA); - assertEquals(point.getCoordinates().getLatitude(), 40.644412, DELTA); - } - - @Test - public void testContext() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - List contexts = response.body().getFeatures().get(0).getContext(); - assertEquals(contexts.get(4).getId(), "country.12862386939497690"); - assertEquals(contexts.get(4).getText(), "United States"); - assertEquals(contexts.get(4).getShortCode(), "us"); - } - - @Test - public void testWikidata() throws ServicesException, IOException { - MapboxGeocoding client = new MapboxGeocoding.Builder() - .setAccessToken("pk.XXX") - .setLocation("1600 pennsylvania ave nw") - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - - CarmenContext context = response.body().getFeatures().get(0).getContext().get(1); - assertEquals(context.getWikidata(), "Q61"); - } + private final static double DELTA = 1E-10; + + private MockWebServer server; + private HttpUrl mockUrl; + + @Before + public void setUp() throws IOException { + server = new MockWebServer(); + + byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/geocoding.json")); + String body = new String(content, StandardCharsets.UTF_8); + server.enqueue(new MockResponse().setBody(body)); + + server.start(); + + mockUrl = server.url(""); + } + + @After + public void tearDown() throws IOException { + server.shutdown(); + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testSanity() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + assertEquals(response.code(), 200); + } + + @Test + public void testBody() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + GeocodingResponse body = response.body(); + assertEquals(body.getType(), "FeatureCollection"); + + assertEquals(body.getQuery().get(0), "1600"); + assertEquals(body.getQuery().get(1), "pennsylvania"); + assertEquals(body.getQuery().get(2), "ave"); + assertEquals(body.getQuery().get(3), "nw"); + + assertEquals(body.getFeatures().size(), 5); + assertTrue(body.getAttribution().startsWith("NOTICE")); + } + + @Test + public void testFeature() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + CarmenFeature feature = response.body().getFeatures().get(0); + assertEquals(feature.getId(), "address.7626097581139850"); + assertEquals(feature.getType(), "Feature"); + assertEquals(feature.getText(), "Pennsylvania Ave NW"); + assertEquals(feature.getPlaceName(), "1600 Pennsylvania Ave NW, Washington, District of Columbia 20006, United States"); + assertEquals(feature.getRelevance(), 0.99, DELTA); + assertEquals(feature.getProperties(), new JsonObject()); + assertEquals(feature.asPosition().getLongitude(), -77.036543, DELTA); + assertEquals(feature.asPosition().getLatitude(), 38.897702, DELTA); + assertEquals(feature.getAddress(), "1600"); + assertEquals(feature.getContext().size(), 5); + } + + @Test + public void testGeometry() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + Point point = (Point) response.body().getFeatures().get(3).getGeometry(); + assertEquals(point.getType(), "Point"); + assertEquals(point.getCoordinates().getLongitude(), -74.236513, DELTA); + assertEquals(point.getCoordinates().getLatitude(), 40.644412, DELTA); + } + + @Test + public void testContext() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + List contexts = response.body().getFeatures().get(0).getContext(); + assertEquals(contexts.get(4).getId(), "country.12862386939497690"); + assertEquals(contexts.get(4).getText(), "United States"); + assertEquals(contexts.get(4).getShortCode(), "us"); + } + + @Test + public void testWikidata() throws ServicesException, IOException { + MapboxGeocoding client = new MapboxGeocoding.Builder() + .setAccessToken("pk.XXX") + .setLocation("1600 pennsylvania ave nw") + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + + CarmenContext context = response.body().getFeatures().get(0).getContext().get(1); + assertEquals(context.getWikidata(), "Q61"); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/BaseGeoJSON.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/BaseGeoJSON.java index d7ea86035..ad631ea82 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/BaseGeoJSON.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/BaseGeoJSON.java @@ -1,14 +1,7 @@ package com.mapbox.services.geojson; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; import com.mapbox.services.BaseTest; -import static org.junit.Assert.assertEquals; - -/** - * Created by antonio on 1/30/16. - */ public class BaseGeoJSON extends BaseTest { /* @@ -16,98 +9,98 @@ public class BaseGeoJSON extends BaseTest { * http://geojson.org */ - public static final String SAMPLE_POINT = "{ \"type\": \"Point\", \"coordinates\": [100.0, 0.0] }"; + public static final String SAMPLE_POINT = "{ \"type\": \"Point\", \"coordinates\": [100.0, 0.0] }"; - public static final String SAMPLE_MULTIPOINT = "{ \"type\": \"MultiPoint\",\n" + - " \"coordinates\": [ [100.0, 0.0], [101.0, 1.0] ]\n" + - " }"; + public static final String SAMPLE_MULTIPOINT = "{ \"type\": \"MultiPoint\",\n" + + " \"coordinates\": [ [100.0, 0.0], [101.0, 1.0] ]\n" + + " }"; - public static final String SAMPLE_LINESTRING = "{ \"type\": \"LineString\",\n" + - " \"coordinates\": [ [100.0, 0.0], [101.0, 1.0] ]\n" + - " }"; + public static final String SAMPLE_LINESTRING = "{ \"type\": \"LineString\",\n" + + " \"coordinates\": [ [100.0, 0.0], [101.0, 1.0] ]\n" + + " }"; - public static final String SAMPLE_MULTILINESTRING = "{ \"type\": \"MultiLineString\",\n" + - " \"coordinates\": [\n" + - " [ [100.0, 0.0], [101.0, 1.0] ],\n" + - " [ [102.0, 2.0], [103.0, 3.0] ]\n" + - " ]\n" + - " }"; + public static final String SAMPLE_MULTILINESTRING = "{ \"type\": \"MultiLineString\",\n" + + " \"coordinates\": [\n" + + " [ [100.0, 0.0], [101.0, 1.0] ],\n" + + " [ [102.0, 2.0], [103.0, 3.0] ]\n" + + " ]\n" + + " }"; - public static final String SAMPLE_POLYGON = "{ \"type\": \"Polygon\",\n" + - " \"coordinates\": [\n" + - " [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]\n" + - " ]\n" + - " }"; + public static final String SAMPLE_POLYGON = "{ \"type\": \"Polygon\",\n" + + " \"coordinates\": [\n" + + " [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]\n" + + " ]\n" + + " }"; - public static final String SAMPLE_POLYGON_HOLES = "{ \"type\": \"Polygon\",\n" + - " \"coordinates\": [\n" + - " [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],\n" + - " [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]\n" + - " ]\n" + - " }"; + public static final String SAMPLE_POLYGON_HOLES = "{ \"type\": \"Polygon\",\n" + + " \"coordinates\": [\n" + + " [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],\n" + + " [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]\n" + + " ]\n" + + " }"; - public static final String SAMPLE_MULTIPOLYGON = "{ \"type\": \"MultiPolygon\",\n" + - " \"coordinates\": [\n" + - " [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],\n" + - " [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],\n" + - " [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]\n" + - " ]\n" + - " }"; + public static final String SAMPLE_MULTIPOLYGON = "{ \"type\": \"MultiPolygon\",\n" + + " \"coordinates\": [\n" + + " [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],\n" + + " [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],\n" + + " [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]\n" + + " ]\n" + + " }"; - public static final String SAMPLE_GEOMETRYCOLLECTION = "{ \"type\": \"GeometryCollection\",\n" + - " \"geometries\": [\n" + - " { \"type\": \"Point\",\n" + - " \"coordinates\": [100.0, 0.0]\n" + - " },\n" + - " { \"type\": \"LineString\",\n" + - " \"coordinates\": [ [101.0, 0.0], [102.0, 1.0] ]\n" + - " }\n" + - " ]\n" + - " }"; + public static final String SAMPLE_GEOMETRYCOLLECTION = "{ \"type\": \"GeometryCollection\",\n" + + " \"geometries\": [\n" + + " { \"type\": \"Point\",\n" + + " \"coordinates\": [100.0, 0.0]\n" + + " },\n" + + " { \"type\": \"LineString\",\n" + + " \"coordinates\": [ [101.0, 0.0], [102.0, 1.0] ]\n" + + " }\n" + + " ]\n" + + " }"; - public static final String SAMPLE_FEATURE = "{\n" + - " \"type\": \"Feature\",\n" + - " \"geometry\": {\n" + - " \"type\": \"Point\",\n" + - " \"coordinates\": [125.6, 10.1]\n" + - " },\n" + - " \"properties\": {\n" + - " \"name\": \"Dinagat Islands\"\n" + - " }\n" + - "}"; + public static final String SAMPLE_FEATURE = "{\n" + + " \"type\": \"Feature\",\n" + + " \"geometry\": {\n" + + " \"type\": \"Point\",\n" + + " \"coordinates\": [125.6, 10.1]\n" + + " },\n" + + " \"properties\": {\n" + + " \"name\": \"Dinagat Islands\"\n" + + " }\n" + + "}"; - public static final String SAMPLE_FEATURECOLLECTION = "{ \"type\": \"FeatureCollection\",\n" + - " \"features\": [\n" + - " { \"type\": \"Feature\",\n" + - " \"geometry\": {\"type\": \"Point\", \"coordinates\": [102.0, 0.5]},\n" + - " \"properties\": {\"prop0\": \"value0\"}\n" + - " },\n" + - " { \"type\": \"Feature\",\n" + - " \"geometry\": {\n" + - " \"type\": \"LineString\",\n" + - " \"coordinates\": [\n" + - " [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]\n" + - " ]\n" + - " },\n" + - " \"properties\": {\n" + - " \"prop0\": \"value0\",\n" + - " \"prop1\": 0.0\n" + - " }\n" + - " },\n" + - " { \"type\": \"Feature\",\n" + - " \"geometry\": {\n" + - " \"type\": \"Polygon\",\n" + - " \"coordinates\": [\n" + - " [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],\n" + - " [100.0, 1.0], [100.0, 0.0] ]\n" + - " ]\n" + - " },\n" + - " \"properties\": {\n" + - " \"prop0\": \"value0\",\n" + - " \"prop1\": {\"this\": \"that\"}\n" + - " }\n" + - " }\n" + - " ]\n" + - " }"; + public static final String SAMPLE_FEATURECOLLECTION = "{ \"type\": \"FeatureCollection\",\n" + + " \"features\": [\n" + + " { \"type\": \"Feature\",\n" + + " \"geometry\": {\"type\": \"Point\", \"coordinates\": [102.0, 0.5]},\n" + + " \"properties\": {\"prop0\": \"value0\"}\n" + + " },\n" + + " { \"type\": \"Feature\",\n" + + " \"geometry\": {\n" + + " \"type\": \"LineString\",\n" + + " \"coordinates\": [\n" + + " [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]\n" + + " ]\n" + + " },\n" + + " \"properties\": {\n" + + " \"prop0\": \"value0\",\n" + + " \"prop1\": 0.0\n" + + " }\n" + + " },\n" + + " { \"type\": \"Feature\",\n" + + " \"geometry\": {\n" + + " \"type\": \"Polygon\",\n" + + " \"coordinates\": [\n" + + " [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],\n" + + " [100.0, 1.0], [100.0, 0.0] ]\n" + + " ]\n" + + " },\n" + + " \"properties\": {\n" + + " \"prop0\": \"value0\",\n" + + " \"prop1\": {\"this\": \"that\"}\n" + + " }\n" + + " }\n" + + " ]\n" + + " }"; } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureCollectionTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureCollectionTest.java index 1b01aa8eb..239295599 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureCollectionTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureCollectionTest.java @@ -6,28 +6,25 @@ import static org.junit.Assert.assertEquals; -/** - * Created by antonio on 1/30/16. - */ public class FeatureCollectionTest extends BaseGeoJSON { - @Test - public void fromJson() { - FeatureCollection geo = FeatureCollection.fromJson(BaseGeoJSON.SAMPLE_FEATURECOLLECTION); - assertEquals(geo.getType(), "FeatureCollection"); - assertEquals(geo.getFeatures().size(), 3); - assertEquals(geo.getFeatures().get(0).getType(), "Feature"); - assertEquals(geo.getFeatures().get(0).getGeometry().getType(), "Point"); - assertEquals(geo.getFeatures().get(1).getType(), "Feature"); - assertEquals(geo.getFeatures().get(1).getGeometry().getType(), "LineString"); - assertEquals(geo.getFeatures().get(2).getType(), "Feature"); - assertEquals(geo.getFeatures().get(2).getGeometry().getType(), "Polygon"); - } + @Test + public void fromJson() { + FeatureCollection geo = FeatureCollection.fromJson(BaseGeoJSON.SAMPLE_FEATURECOLLECTION); + assertEquals(geo.getType(), "FeatureCollection"); + assertEquals(geo.getFeatures().size(), 3); + assertEquals(geo.getFeatures().get(0).getType(), "Feature"); + assertEquals(geo.getFeatures().get(0).getGeometry().getType(), "Point"); + assertEquals(geo.getFeatures().get(1).getType(), "Feature"); + assertEquals(geo.getFeatures().get(1).getGeometry().getType(), "LineString"); + assertEquals(geo.getFeatures().get(2).getType(), "Feature"); + assertEquals(geo.getFeatures().get(2).getGeometry().getType(), "Polygon"); + } - @Test - public void toJson() { - FeatureCollection geo = FeatureCollection.fromJson(BaseGeoJSON.SAMPLE_FEATURECOLLECTION); - compareJson(BaseGeoJSON.SAMPLE_FEATURECOLLECTION, geo.toJson()); - } + @Test + public void toJson() { + FeatureCollection geo = FeatureCollection.fromJson(BaseGeoJSON.SAMPLE_FEATURECOLLECTION); + compareJson(BaseGeoJSON.SAMPLE_FEATURECOLLECTION, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureTest.java index a2ac37e8d..786e40c8f 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/FeatureTest.java @@ -6,23 +6,20 @@ import static org.junit.Assert.assertEquals; -/** - * Created by antonio on 1/30/16. - */ public class FeatureTest extends BaseGeoJSON { - @Test - public void fromJson() { - Feature geo = Feature.fromJson(BaseGeoJSON.SAMPLE_FEATURE); - assertEquals(geo.getType(), "Feature"); - assertEquals(geo.getGeometry().getType(), "Point"); - assertEquals(geo.getProperties().get("name").getAsString(), "Dinagat Islands"); - } + @Test + public void fromJson() { + Feature geo = Feature.fromJson(BaseGeoJSON.SAMPLE_FEATURE); + assertEquals(geo.getType(), "Feature"); + assertEquals(geo.getGeometry().getType(), "Point"); + assertEquals(geo.getProperties().get("name").getAsString(), "Dinagat Islands"); + } - @Test - public void toJson() { - Feature geo = Feature.fromJson(BaseGeoJSON.SAMPLE_FEATURE); - compareJson(BaseGeoJSON.SAMPLE_FEATURE, geo.toJson()); - } + @Test + public void toJson() { + Feature geo = Feature.fromJson(BaseGeoJSON.SAMPLE_FEATURE); + compareJson(BaseGeoJSON.SAMPLE_FEATURE, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/GeometryCollectionTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/GeometryCollectionTest.java index b0c9f13c4..6408d8e6f 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/GeometryCollectionTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/GeometryCollectionTest.java @@ -6,23 +6,20 @@ import static org.junit.Assert.*; -/** - * Created by antonio on 1/30/16. - */ public class GeometryCollectionTest extends BaseGeoJSON { - @Test - public void fromJson() { - GeometryCollection geo = GeometryCollection.fromJson(BaseGeoJSON.SAMPLE_GEOMETRYCOLLECTION); - assertEquals(geo.getType(), "GeometryCollection"); - assertEquals(geo.getGeometries().get(0).getType(), "Point"); - assertEquals(geo.getGeometries().get(1).getType(), "LineString"); - } + @Test + public void fromJson() { + GeometryCollection geo = GeometryCollection.fromJson(BaseGeoJSON.SAMPLE_GEOMETRYCOLLECTION); + assertEquals(geo.getType(), "GeometryCollection"); + assertEquals(geo.getGeometries().get(0).getType(), "Point"); + assertEquals(geo.getGeometries().get(1).getType(), "LineString"); + } - @Test - public void toJson() { - GeometryCollection geo = GeometryCollection.fromJson(BaseGeoJSON.SAMPLE_GEOMETRYCOLLECTION); - compareJson(BaseGeoJSON.SAMPLE_GEOMETRYCOLLECTION, geo.toJson()); - } + @Test + public void toJson() { + GeometryCollection geo = GeometryCollection.fromJson(BaseGeoJSON.SAMPLE_GEOMETRYCOLLECTION); + compareJson(BaseGeoJSON.SAMPLE_GEOMETRYCOLLECTION, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/LineStringTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/LineStringTest.java index 0e8898d10..223ad2fc7 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/LineStringTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/LineStringTest.java @@ -7,24 +7,21 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -/** - * Created by antonio on 1/30/16. - */ public class LineStringTest extends BaseGeoJSON { - @Test - public void fromJson() { - LineString geo = LineString.fromJson(BaseGeoJSON.SAMPLE_LINESTRING); - assertEquals(geo.getType(), "LineString"); - assertEquals(geo.getCoordinates().get(0).getLongitude(), 100.0, 0.0); - assertEquals(geo.getCoordinates().get(0).getLatitude(), 0.0, 0.0); - assertFalse(geo.getCoordinates().get(0).hasAltitude()); - } + @Test + public void fromJson() { + LineString geo = LineString.fromJson(BaseGeoJSON.SAMPLE_LINESTRING); + assertEquals(geo.getType(), "LineString"); + assertEquals(geo.getCoordinates().get(0).getLongitude(), 100.0, 0.0); + assertEquals(geo.getCoordinates().get(0).getLatitude(), 0.0, 0.0); + assertFalse(geo.getCoordinates().get(0).hasAltitude()); + } - @Test - public void toJson() { - LineString geo = LineString.fromJson(BaseGeoJSON.SAMPLE_LINESTRING); - compareJson(BaseGeoJSON.SAMPLE_LINESTRING, geo.toJson()); - } + @Test + public void toJson() { + LineString geo = LineString.fromJson(BaseGeoJSON.SAMPLE_LINESTRING); + compareJson(BaseGeoJSON.SAMPLE_LINESTRING, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiLineStringTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiLineStringTest.java index 0a179fc79..e339f2420 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiLineStringTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiLineStringTest.java @@ -5,24 +5,21 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -/** - * Created by antonio on 1/30/16. - */ public class MultiLineStringTest extends BaseGeoJSON { - @Test - public void fromJson() { - com.mapbox.services.commons.geojson.MultiLineString geo = com.mapbox.services.commons.geojson.MultiLineString.fromJson(BaseGeoJSON.SAMPLE_MULTILINESTRING); - assertEquals(geo.getType(), "MultiLineString"); - assertEquals(geo.getCoordinates().get(0).get(0).getLongitude(), 100.0, 0.0); - assertEquals(geo.getCoordinates().get(0).get(0).getLatitude(), 0.0, 0.0); - assertFalse(geo.getCoordinates().get(0).get(0).hasAltitude()); - } - - @Test - public void toJson() { - com.mapbox.services.commons.geojson.MultiLineString geo = com.mapbox.services.commons.geojson.MultiLineString.fromJson(BaseGeoJSON.SAMPLE_MULTILINESTRING); - compareJson(BaseGeoJSON.SAMPLE_MULTILINESTRING, geo.toJson()); - } + @Test + public void fromJson() { + com.mapbox.services.commons.geojson.MultiLineString geo = com.mapbox.services.commons.geojson.MultiLineString.fromJson(BaseGeoJSON.SAMPLE_MULTILINESTRING); + assertEquals(geo.getType(), "MultiLineString"); + assertEquals(geo.getCoordinates().get(0).get(0).getLongitude(), 100.0, 0.0); + assertEquals(geo.getCoordinates().get(0).get(0).getLatitude(), 0.0, 0.0); + assertFalse(geo.getCoordinates().get(0).get(0).hasAltitude()); + } + + @Test + public void toJson() { + com.mapbox.services.commons.geojson.MultiLineString geo = com.mapbox.services.commons.geojson.MultiLineString.fromJson(BaseGeoJSON.SAMPLE_MULTILINESTRING); + compareJson(BaseGeoJSON.SAMPLE_MULTILINESTRING, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPointTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPointTest.java index 333348b70..84ebeeca6 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPointTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPointTest.java @@ -5,24 +5,21 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -/** - * Created by antonio on 1/30/16. - */ public class MultiPointTest extends BaseGeoJSON { - @Test - public void fromJson() { - com.mapbox.services.commons.geojson.MultiPoint geo = com.mapbox.services.commons.geojson.MultiPoint.fromJson(BaseGeoJSON.SAMPLE_MULTIPOINT); - assertEquals(geo.getType(), "MultiPoint"); - assertEquals(geo.getCoordinates().get(0).getLongitude(), 100.0, 0.0); - assertEquals(geo.getCoordinates().get(0).getLatitude(), 0.0, 0.0); - assertFalse(geo.getCoordinates().get(0).hasAltitude()); - } + @Test + public void fromJson() { + com.mapbox.services.commons.geojson.MultiPoint geo = com.mapbox.services.commons.geojson.MultiPoint.fromJson(BaseGeoJSON.SAMPLE_MULTIPOINT); + assertEquals(geo.getType(), "MultiPoint"); + assertEquals(geo.getCoordinates().get(0).getLongitude(), 100.0, 0.0); + assertEquals(geo.getCoordinates().get(0).getLatitude(), 0.0, 0.0); + assertFalse(geo.getCoordinates().get(0).hasAltitude()); + } - @Test - public void toJson() { - com.mapbox.services.commons.geojson.MultiPoint geo = com.mapbox.services.commons.geojson.MultiPoint.fromJson(BaseGeoJSON.SAMPLE_MULTIPOINT); - compareJson(BaseGeoJSON.SAMPLE_MULTIPOINT, geo.toJson()); - } + @Test + public void toJson() { + com.mapbox.services.commons.geojson.MultiPoint geo = com.mapbox.services.commons.geojson.MultiPoint.fromJson(BaseGeoJSON.SAMPLE_MULTIPOINT); + compareJson(BaseGeoJSON.SAMPLE_MULTIPOINT, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPolygonTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPolygonTest.java index a66278310..712a51005 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPolygonTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/MultiPolygonTest.java @@ -7,24 +7,21 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -/** - * Created by antonio on 1/30/16. - */ public class MultiPolygonTest extends BaseGeoJSON { - @Test - public void fromJson() { - MultiPolygon geo = MultiPolygon.fromJson(BaseGeoJSON.SAMPLE_MULTIPOLYGON); - assertEquals(geo.getType(), "MultiPolygon"); - assertEquals(geo.getCoordinates().get(0).get(0).get(0).getLongitude(), 102.0, 0.0); - assertEquals(geo.getCoordinates().get(0).get(0).get(0).getLatitude(), 2.0, 0.0); - assertFalse(geo.getCoordinates().get(0).get(0).get(0).hasAltitude()); - } + @Test + public void fromJson() { + MultiPolygon geo = MultiPolygon.fromJson(BaseGeoJSON.SAMPLE_MULTIPOLYGON); + assertEquals(geo.getType(), "MultiPolygon"); + assertEquals(geo.getCoordinates().get(0).get(0).get(0).getLongitude(), 102.0, 0.0); + assertEquals(geo.getCoordinates().get(0).get(0).get(0).getLatitude(), 2.0, 0.0); + assertFalse(geo.getCoordinates().get(0).get(0).get(0).hasAltitude()); + } - @Test - public void toJson() { - MultiPolygon geo = MultiPolygon.fromJson(BaseGeoJSON.SAMPLE_MULTIPOLYGON); - compareJson(BaseGeoJSON.SAMPLE_MULTIPOLYGON, geo.toJson()); - } + @Test + public void toJson() { + MultiPolygon geo = MultiPolygon.fromJson(BaseGeoJSON.SAMPLE_MULTIPOLYGON); + compareJson(BaseGeoJSON.SAMPLE_MULTIPOLYGON, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/PointTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/PointTest.java index 4cd566cb0..34e6105cb 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/PointTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/PointTest.java @@ -4,25 +4,22 @@ import static org.junit.Assert.*; -/** - * Created by antonio on 1/30/16. - */ public class PointTest extends BaseGeoJSON { - @Test - public void fromJson() { - com.mapbox.services.commons.geojson.Point geo = com.mapbox.services.commons.geojson.Point.fromJson(BaseGeoJSON.SAMPLE_POINT); - assertEquals(geo.getType(), "Point"); - assertEquals(geo.getCoordinates().getLongitude(), 100.0, 0.0); - assertEquals(geo.getCoordinates().getLatitude(), 0.0, 0.0); - assertFalse(geo.getCoordinates().hasAltitude()); - } + @Test + public void fromJson() { + com.mapbox.services.commons.geojson.Point geo = com.mapbox.services.commons.geojson.Point.fromJson(BaseGeoJSON.SAMPLE_POINT); + assertEquals(geo.getType(), "Point"); + assertEquals(geo.getCoordinates().getLongitude(), 100.0, 0.0); + assertEquals(geo.getCoordinates().getLatitude(), 0.0, 0.0); + assertFalse(geo.getCoordinates().hasAltitude()); + } - @Test - public void toJson() { - com.mapbox.services.commons.geojson.Point geo = com.mapbox.services.commons.geojson.Point.fromJson(BaseGeoJSON.SAMPLE_POINT); - compareJson(BaseGeoJSON.SAMPLE_POINT, geo.toJson()); - } + @Test + public void toJson() { + com.mapbox.services.commons.geojson.Point geo = com.mapbox.services.commons.geojson.Point.fromJson(BaseGeoJSON.SAMPLE_POINT); + compareJson(BaseGeoJSON.SAMPLE_POINT, geo.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/geojson/PolygonTest.java b/libjava/lib/src/test/java/com/mapbox/services/geojson/PolygonTest.java index 39974021a..084931ee0 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/geojson/PolygonTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/geojson/PolygonTest.java @@ -11,62 +11,59 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -/** - * Created by antonio on 1/30/16. - */ public class PolygonTest extends BaseGeoJSON { - @Test - public void fromJson() { - Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON); - assertEquals(geo.getType(), "Polygon"); - assertEquals(geo.getCoordinates().get(0).get(0).getLongitude(), 100.0, DELTA); - assertEquals(geo.getCoordinates().get(0).get(0).getLatitude(), 0.0, DELTA); - assertFalse(geo.getCoordinates().get(0).get(0).hasAltitude()); - } + @Test + public void fromJson() { + Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON); + assertEquals(geo.getType(), "Polygon"); + assertEquals(geo.getCoordinates().get(0).get(0).getLongitude(), 100.0, DELTA); + assertEquals(geo.getCoordinates().get(0).get(0).getLatitude(), 0.0, DELTA); + assertFalse(geo.getCoordinates().get(0).get(0).hasAltitude()); + } - @Test - public void fromJsonHoles() { - Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON_HOLES); - assertEquals(geo.getType(), "Polygon"); - assertEquals(geo.getCoordinates().get(0).get(0).getLongitude(), 100.0, DELTA); - assertEquals(geo.getCoordinates().get(0).get(0).getLatitude(), 0.0, DELTA); - assertFalse(geo.getCoordinates().get(0).get(0).hasAltitude()); - } + @Test + public void fromJsonHoles() { + Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON_HOLES); + assertEquals(geo.getType(), "Polygon"); + assertEquals(geo.getCoordinates().get(0).get(0).getLongitude(), 100.0, DELTA); + assertEquals(geo.getCoordinates().get(0).get(0).getLatitude(), 0.0, DELTA); + assertFalse(geo.getCoordinates().get(0).get(0).hasAltitude()); + } - @Test - public void toJson() { - Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON); - compareJson(BaseGeoJSON.SAMPLE_POLYGON, geo.toJson()); - } + @Test + public void toJson() { + Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON); + compareJson(BaseGeoJSON.SAMPLE_POLYGON, geo.toJson()); + } - @Test - public void toJsonHoles() { - Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON_HOLES); - compareJson(BaseGeoJSON.SAMPLE_POLYGON_HOLES, geo.toJson()); - } + @Test + public void toJsonHoles() { + Polygon geo = Polygon.fromJson(BaseGeoJSON.SAMPLE_POLYGON_HOLES); + compareJson(BaseGeoJSON.SAMPLE_POLYGON_HOLES, geo.toJson()); + } - @Test - public void testFromCoordinates() { - // fromCoordinates (list) - ArrayList pointList = new ArrayList<>(); - pointList.add(Position.fromCoordinates(0, 0)); - pointList.add(Position.fromCoordinates(0, 100)); - pointList.add(Position.fromCoordinates(100, 100)); - pointList.add(Position.fromCoordinates(100, 0)); - pointList.add(Position.fromCoordinates(0, 0)); - ArrayList> coordinates = new ArrayList<>(); - coordinates.add(pointList); - Polygon polyList = Polygon.fromCoordinates(coordinates); + @Test + public void testFromCoordinates() { + // fromCoordinates (list) + ArrayList pointList = new ArrayList<>(); + pointList.add(Position.fromCoordinates(0, 0)); + pointList.add(Position.fromCoordinates(0, 100)); + pointList.add(Position.fromCoordinates(100, 100)); + pointList.add(Position.fromCoordinates(100, 0)); + pointList.add(Position.fromCoordinates(0, 0)); + ArrayList> coordinates = new ArrayList<>(); + coordinates.add(pointList); + Polygon polyList = Polygon.fromCoordinates(coordinates); - // fromCoordinates (array) - Polygon polyArray = Polygon.fromCoordinates(new double[][][]{{ - {0, 0}, {0, 100}, {100, 100}, {100, 0}, {0, 0} - }}); + // fromCoordinates (array) + Polygon polyArray = Polygon.fromCoordinates(new double[][][] {{ + {0, 0}, {0, 100}, {100, 100}, {100, 0}, {0, 0} + }}); - // Test equality - assertEquals(polyList.getCoordinates(), polyArray.getCoordinates()); - compareJson(polyList.toJson(), polyArray.toJson()); - } + // Test equality + assertEquals(polyList.getCoordinates(), polyArray.getCoordinates()); + compareJson(polyList.toJson(), polyArray.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/mapmatching/v4/MapboxMapMatchingTest.java b/libjava/lib/src/test/java/com/mapbox/services/mapmatching/v4/MapboxMapMatchingTest.java index 18bcf2fe3..ff411ef46 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/mapmatching/v4/MapboxMapMatchingTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/mapmatching/v4/MapboxMapMatchingTest.java @@ -35,171 +35,171 @@ */ public class MapboxMapMatchingTest { - public static final String POLYLINE_FIXTURE = "src/test/fixtures/mapmatching_v5_polyline.json"; - public static final String NO_GEOMETRY_FIXTURE = "src/test/fixtures/mapmatching_v5_no_geometry.json"; + public static final String POLYLINE_FIXTURE = "src/test/fixtures/mapmatching_v5_polyline.json"; + public static final String NO_GEOMETRY_FIXTURE = "src/test/fixtures/mapmatching_v5_no_geometry.json"; - private static final String ACCESS_TOKEN = "pk.XXX"; + private static final String ACCESS_TOKEN = "pk.XXX"; - private MockWebServer server; - private HttpUrl mockUrl; + private MockWebServer server; + private HttpUrl mockUrl; - private LineString trace; + private LineString trace; - @Rule - public ExpectedException thrown = ExpectedException.none(); + @Rule + public ExpectedException thrown = ExpectedException.none(); - @Before - public void setUp() throws IOException { - server = new MockWebServer(); + @Before + public void setUp() throws IOException { + server = new MockWebServer(); - server.setDispatcher(new Dispatcher() { + server.setDispatcher(new Dispatcher() { - @Override - public MockResponse dispatch(RecordedRequest request) throws InterruptedException { - // Switch response on geometry parameter (only false supported, so nice and simple) - String resource = POLYLINE_FIXTURE; - if (request.getPath().contains("geometry=false")) { - resource = NO_GEOMETRY_FIXTURE; - } - - try { - String body = new String(Files.readAllBytes(Paths.get(resource)), Charset.forName("utf-8")); - return new MockResponse().setBody(body); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }); - - server.start(); - mockUrl = server.url(""); - - // From https://www.mapbox.com/api-documentation/#map-matching - trace = LineString.fromJson("{ \"type\": \"LineString\", \"coordinates\": [ [13.418946862220764, 52.50055852688439], [13.419011235237122, 52.50113000479732], [13.419756889343262, 52.50171780290061], [13.419885635375975, 52.50237416816131], [13.420631289482117, 52.50294888790448] ] }"); - } - - @After - public void tearDown() throws IOException { - server.shutdown(); - } - - /** - * Test the most basic request (default response format) - */ - @Test - public void testCallSanity() throws ServicesException, IOException { - MapboxMapMatching client = new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile(DirectionsCriteria.PROFILE_WALKING) - .setTrace(trace) - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - assertEquals(response.code(), 200); - - // Check the response body - assertNotNull(response.body()); - assertEquals(1, response.body().getFeatures().size()); - assertNotNull(response.body().getFeatures().get(0).getGeometry()); - } - - /** - * Test a basic request with polyline response - */ - @Test - public void testNoGeometryResponse() throws ServicesException, IOException { - MapboxMapMatching client = new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile(DirectionsCriteria.PROFILE_WALKING) - .setTrace(trace) - .setNoGeometry() - .build(); - client.setBaseUrl(mockUrl.toString()); - Response response = client.executeCall(); - assertEquals(response.code(), 200); - - // Check the response body - assertNotNull(response.body()); - assertEquals(1, response.body().getFeatures().size()); - assertNull(response.body().getFeatures().get(0).getGeometry()); - } - - @Test - public void requiredAccessToken() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Services requires setting a valid access token")); - new MapboxMapMatching.Builder().build(); - } - - @Test - public void validGpsPrecisionLowerBounds() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid GPS precision")); - new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile(DirectionsCriteria.PROFILE_WALKING) - .setGpsPrecison(0) - .build(); - } - - @Test - public void validGpsPrecisionUpperBounds() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid GPS precision")); - new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile(DirectionsCriteria.PROFILE_WALKING) - .setGpsPrecison(11) - .build(); - } - - @Test - public void validProfileNonNull() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid profile")); - new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile(null) - .build(); - } - - @Test - public void validProfileCorrectString() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid profile")); - new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile("my_own_profile") - .build(); - } - - @Test - public void validCoordinates() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Map Matching requires to set some coordinates")); - new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .build(); - } - - @Test - public void validCoordinatesTotal() throws ServicesException { - // Fake too many positions - ArrayList positions = new ArrayList<>(); - for (int i = 0; i < 101; i++) { - positions.add(Position.fromCoordinates(0.0, 0.0)); + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + // Switch response on geometry parameter (only false supported, so nice and simple) + String resource = POLYLINE_FIXTURE; + if (request.getPath().contains("geometry=false")) { + resource = NO_GEOMETRY_FIXTURE; } - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("The Map Matching API is limited to processing traces with up to 100 coordinates")); - new MapboxMapMatching.Builder() - .setAccessToken(ACCESS_TOKEN) - .setProfile(DirectionsCriteria.PROFILE_DRIVING) - .setTrace(LineString.fromCoordinates(positions)) - .build(); + try { + String body = new String(Files.readAllBytes(Paths.get(resource)), Charset.forName("utf-8")); + return new MockResponse().setBody(body); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }); + + server.start(); + mockUrl = server.url(""); + + // From https://www.mapbox.com/api-documentation/#map-matching + trace = LineString.fromJson("{ \"type\": \"LineString\", \"coordinates\": [ [13.418946862220764, 52.50055852688439], [13.419011235237122, 52.50113000479732], [13.419756889343262, 52.50171780290061], [13.419885635375975, 52.50237416816131], [13.420631289482117, 52.50294888790448] ] }"); + } + + @After + public void tearDown() throws IOException { + server.shutdown(); + } + + /** + * Test the most basic request (default response format) + */ + @Test + public void testCallSanity() throws ServicesException, IOException { + MapboxMapMatching client = new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile(DirectionsCriteria.PROFILE_WALKING) + .setTrace(trace) + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + assertEquals(response.code(), 200); + + // Check the response body + assertNotNull(response.body()); + assertEquals(1, response.body().getFeatures().size()); + assertNotNull(response.body().getFeatures().get(0).getGeometry()); + } + + /** + * Test a basic request with polyline response + */ + @Test + public void testNoGeometryResponse() throws ServicesException, IOException { + MapboxMapMatching client = new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile(DirectionsCriteria.PROFILE_WALKING) + .setTrace(trace) + .setNoGeometry() + .build(); + client.setBaseUrl(mockUrl.toString()); + Response response = client.executeCall(); + assertEquals(response.code(), 200); + + // Check the response body + assertNotNull(response.body()); + assertEquals(1, response.body().getFeatures().size()); + assertNull(response.body().getFeatures().get(0).getGeometry()); + } + + @Test + public void requiredAccessToken() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Services requires setting a valid access token")); + new MapboxMapMatching.Builder().build(); + } + + @Test + public void validGpsPrecisionLowerBounds() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid GPS precision")); + new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile(DirectionsCriteria.PROFILE_WALKING) + .setGpsPrecison(0) + .build(); + } + + @Test + public void validGpsPrecisionUpperBounds() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid GPS precision")); + new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile(DirectionsCriteria.PROFILE_WALKING) + .setGpsPrecison(11) + .build(); + } + + @Test + public void validProfileNonNull() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid profile")); + new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile(null) + .build(); + } + + @Test + public void validProfileCorrectString() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Map Matching requires setting a valid profile")); + new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile("my_own_profile") + .build(); + } + + @Test + public void validCoordinates() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Map Matching requires to set some coordinates")); + new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .build(); + } + + @Test + public void validCoordinatesTotal() throws ServicesException { + // Fake too many positions + ArrayList positions = new ArrayList<>(); + for (int i = 0; i < 101; i++) { + positions.add(Position.fromCoordinates(0.0, 0.0)); } + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("The Map Matching API is limited to processing traces with up to 100 coordinates")); + new MapboxMapMatching.Builder() + .setAccessToken(ACCESS_TOKEN) + .setProfile(DirectionsCriteria.PROFILE_DRIVING) + .setTrace(LineString.fromCoordinates(positions)) + .build(); + } + // @Test // public void testPost() throws ServicesException, IOException { // MapboxMapMatching client = new MapboxMapMatching.Builder() diff --git a/libjava/lib/src/test/java/com/mapbox/services/models/PositionTest.java b/libjava/lib/src/test/java/com/mapbox/services/models/PositionTest.java index 3d179acf2..df1781efb 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/models/PositionTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/models/PositionTest.java @@ -7,19 +7,16 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -/** - * Created by antonio on 7/14/16. - */ public class PositionTest { - @Test - public void testEquals() { - assertNotEquals(Position.fromCoordinates(1.2, 3.4), null); - assertNotEquals(Position.fromCoordinates(1.2, 3.4), Position.fromCoordinates(1.2, 0.0)); - assertNotEquals(Position.fromCoordinates(1.2, 3.4), Position.fromCoordinates(0.0, 3.4)); - assertNotEquals(Position.fromCoordinates(1.2, 3.4), Position.fromCoordinates(1.2, 3.4, 0.0)); + @Test + public void testEquals() { + assertNotEquals(Position.fromCoordinates(1.2, 3.4), null); + assertNotEquals(Position.fromCoordinates(1.2, 3.4), Position.fromCoordinates(1.2, 0.0)); + assertNotEquals(Position.fromCoordinates(1.2, 3.4), Position.fromCoordinates(0.0, 3.4)); + assertNotEquals(Position.fromCoordinates(1.2, 3.4), Position.fromCoordinates(1.2, 3.4, 0.0)); - assertEquals(Position.fromCoordinates(4.3, 2.1), Position.fromCoordinates(4.3, 2.1)); - assertEquals(Position.fromCoordinates(6.5, 4.3, 2.1), Position.fromCoordinates(6.5, 4.3, 2.1)); - } + assertEquals(Position.fromCoordinates(4.3, 2.1), Position.fromCoordinates(4.3, 2.1)); + assertEquals(Position.fromCoordinates(6.5, 4.3, 2.1), Position.fromCoordinates(6.5, 4.3, 2.1)); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/navigation/v5/RouteUtilsTest.java b/libjava/lib/src/test/java/com/mapbox/services/navigation/v5/RouteUtilsTest.java index 1b6264dd4..e64ebf5e9 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/navigation/v5/RouteUtilsTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/navigation/v5/RouteUtilsTest.java @@ -28,94 +28,91 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -/** - * Created by antonio on 8/23/16. - */ public class RouteUtilsTest extends BaseTest { - private DirectionsResponse response; - private RouteLeg route; + private DirectionsResponse response; + private RouteLeg route; - @Before - public void setUp() throws IOException { - Gson gson = new Gson(); - byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/directions_v5.json")); - String body = new String(content, StandardCharsets.UTF_8); - response = gson.fromJson(body, DirectionsResponse.class); - route = response.getRoutes().get(0).getLegs().get(0); - } + @Before + public void setUp() throws IOException { + Gson gson = new Gson(); + byte[] content = Files.readAllBytes(Paths.get("src/test/fixtures/directions_v5.json")); + String body = new String(content, StandardCharsets.UTF_8); + response = gson.fromJson(body, DirectionsResponse.class); + route = response.getRoutes().get(0).getLegs().get(0); + } - @Rule - public ExpectedException thrown = ExpectedException.none(); + @Rule + public ExpectedException thrown = ExpectedException.none(); - @Test - public void isInStepTest() throws ServicesException, TurfException { - RouteUtils routeUtils = new RouteUtils(); + @Test + public void isInStepTest() throws ServicesException, TurfException { + RouteUtils routeUtils = new RouteUtils(); - // For each step, the first coordinate is in the step - for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { - LegStep step = route.getSteps().get(stepIndex); - List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); - assertTrue(routeUtils.isInStep(coords.get(0), route, stepIndex)); - } + // For each step, the first coordinate is in the step + for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { + LegStep step = route.getSteps().get(stepIndex); + List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); + assertTrue(routeUtils.isInStep(coords.get(0), route, stepIndex)); } + } - @Test - public void getDistanceToStepTest() throws ServicesException, TurfException { - RouteUtils routeUtils = new RouteUtils(); + @Test + public void getDistanceToStepTest() throws ServicesException, TurfException { + RouteUtils routeUtils = new RouteUtils(); - // For each step, the distance to the first coordinate is zero - for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { - LegStep step = route.getSteps().get(stepIndex); - List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); - assertEquals(0.0, routeUtils.getDistanceToStep(coords.get(0), route, stepIndex), DELTA); - } + // For each step, the distance to the first coordinate is zero + for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { + LegStep step = route.getSteps().get(stepIndex); + List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); + assertEquals(0.0, routeUtils.getDistanceToStep(coords.get(0), route, stepIndex), DELTA); } - - @Test - public void getSnapToRouteTest() throws ServicesException, TurfException { - RouteUtils routeUtils = new RouteUtils(); - - // For each step, the first coordinate snap point is the same point - for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { - LegStep step = route.getSteps().get(stepIndex); - List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); - Position snapPoint = routeUtils.getSnapToRoute(coords.get(0), route, stepIndex); - assertEquals(coords.get(0).getLatitude(), snapPoint.getLatitude(), DELTA); - assertEquals(coords.get(0).getLongitude(), snapPoint.getLongitude(), DELTA); - } + } + + @Test + public void getSnapToRouteTest() throws ServicesException, TurfException { + RouteUtils routeUtils = new RouteUtils(); + + // For each step, the first coordinate snap point is the same point + for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { + LegStep step = route.getSteps().get(stepIndex); + List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); + Position snapPoint = routeUtils.getSnapToRoute(coords.get(0), route, stepIndex); + assertEquals(coords.get(0).getLatitude(), snapPoint.getLatitude(), DELTA); + assertEquals(coords.get(0).getLongitude(), snapPoint.getLongitude(), DELTA); } + } + + @Test + public void isOffRouteTest() throws ServicesException, TurfException { + RouteUtils routeUtils = new RouteUtils(); - @Test - public void isOffRouteTest() throws ServicesException, TurfException { - RouteUtils routeUtils = new RouteUtils(); - - // For each step, the first coordinate is not off-route - for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { - LegStep step = route.getSteps().get(stepIndex); - List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); - assertFalse(routeUtils.isOffRoute(coords.get(0), route)); - } - - // The route goes from SF (N) to San Jose (S). So 0.1 km south of the last point should - // be off-route - LegStep lastStep = route.getSteps().get(route.getSteps().size() - 1); - List lastCoords = PolylineUtils.decode(lastStep.getGeometry(), Constants.OSRM_PRECISION_V5); - Position offRoutePoint = TurfMeasurement.destination(lastCoords.get(0), routeUtils.getOffRouteThresholdKm(), 180, TurfConstants.UNIT_DEFAULT); - assertTrue(routeUtils.isOffRoute(offRoutePoint, route)); + // For each step, the first coordinate is not off-route + for (int stepIndex = 0; stepIndex < route.getSteps().size(); stepIndex++) { + LegStep step = route.getSteps().get(stepIndex); + List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); + assertFalse(routeUtils.isOffRoute(coords.get(0), route)); } - @Test - public void getClosestStepTest() throws ServicesException, TurfException { - RouteUtils routeUtils = new RouteUtils(); - - // For each step, the last coordinate is closest to its step (except the last step which - // is one point only) - for (int stepIndex = 0; stepIndex < route.getSteps().size() - 1; stepIndex++) { - LegStep step = route.getSteps().get(stepIndex); - List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); - assertEquals(stepIndex, routeUtils.getClosestStep(coords.get(coords.size() - 1), route)); - } + // The route goes from SF (N) to San Jose (S). So 0.1 km south of the last point should + // be off-route + LegStep lastStep = route.getSteps().get(route.getSteps().size() - 1); + List lastCoords = PolylineUtils.decode(lastStep.getGeometry(), Constants.OSRM_PRECISION_V5); + Position offRoutePoint = TurfMeasurement.destination(lastCoords.get(0), routeUtils.getOffRouteThresholdKm(), 180, TurfConstants.UNIT_DEFAULT); + assertTrue(routeUtils.isOffRoute(offRoutePoint, route)); + } + + @Test + public void getClosestStepTest() throws ServicesException, TurfException { + RouteUtils routeUtils = new RouteUtils(); + + // For each step, the last coordinate is closest to its step (except the last step which + // is one point only) + for (int stepIndex = 0; stepIndex < route.getSteps().size() - 1; stepIndex++) { + LegStep step = route.getSteps().get(stepIndex); + List coords = PolylineUtils.decode(step.getGeometry(), Constants.OSRM_PRECISION_V5); + assertEquals(stepIndex, routeUtils.getClosestStep(coords.get(coords.size() - 1), route)); } + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/staticimage/v1/MapboxStaticImageTest.java b/libjava/lib/src/test/java/com/mapbox/services/staticimage/v1/MapboxStaticImageTest.java index 1e115c93b..d7924db49 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/staticimage/v1/MapboxStaticImageTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/staticimage/v1/MapboxStaticImageTest.java @@ -7,145 +7,147 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import okhttp3.HttpUrl; + import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class MapboxStaticImageTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testSanity() throws ServicesException { - MapboxStaticImage client = new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLat(1.0).setLon(2.0) - .setZoom(10) - .setWidth(100).setHeight(200) - .build(); - HttpUrl url = client.getUrl(); - assertFalse(url.toString().isEmpty()); - } - - @Test - public void requireAccessToken() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("Using Mapbox Services requires setting a valid access token.")); - new MapboxStaticImage.Builder() - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLat(1.0).setLon(2.0) - .setZoom(10) - .setWidth(100).setHeight(200) - .build(); - } - - @Test - public void requireStyleId() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You need to set a map style.")); - new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setLat(1.0).setLon(2.0) - .setZoom(10) - .setWidth(100).setHeight(200) - .build(); - } - - @Test - public void requireLon() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You need to set the map lon/lat coordinates.")); - new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLat(1.0) - .setZoom(10) - .setWidth(100).setHeight(200) - .build(); - } - - @Test - public void requireLat() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You need to set the map lon/lat coordinates.")); - new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLon(2.0) - .setZoom(10) - .setWidth(100).setHeight(200) - .build(); - } - - @Test - public void requireZoom() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You need to set the map zoom level.")); - new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLat(1.0).setLon(2.0) - .setWidth(100).setHeight(200) - .build(); - } - - @Test - public void requireWidth() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You need to set a valid image width (between 1 and 1280).")); - new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLat(1.0).setLon(2.0) - .setZoom(10) - .setHeight(200) - .build(); - } - - @Test - public void requireHeight() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You need to set a valid image height (between 1 and 1280).")); - new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLat(1.0).setLon(2.0) - .setZoom(10) - .setWidth(100) - .build(); - } - - @Test - public void requireHeightInRange() throws ServicesException { - thrown.expect(ServicesException.class); - thrown.expectMessage(startsWith("You need to set a valid image height (between 1 and 1280).")); - new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLat(1.0).setLon(2.0) - .setZoom(10) - .setWidth(100) - .setHeight(5000) - .build(); - } - - @Test - public void testPrecision() throws ServicesException { - MapboxStaticImage client = new MapboxStaticImage.Builder() - .setAccessToken("pk.") - .setStyleId(Constants.MAPBOX_STYLE_STREETS) - .setLocation(Position.fromCoordinates(1.23456789, -98.76)) - .setZoom(10).setBearing(345.67890123456789).setPitch(0.000000005) - .setWidth(100).setHeight(200) - .setPrecision(5) - .build(); - HttpUrl url = client.getUrl(); - assertEquals( - url.toString(), - "https://api.mapbox.com/styles/v1/mapbox/streets-v9/static/1.23456,-98.76000,10.00000,345.67890,0.00000/100x200?access_token=pk."); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testSanity() throws ServicesException { + MapboxStaticImage client = new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLat(1.0).setLon(2.0) + .setZoom(10) + .setWidth(100).setHeight(200) + .build(); + HttpUrl url = client.getUrl(); + assertFalse(url.toString().isEmpty()); + } + + @Test + public void requireAccessToken() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("Using Mapbox Services requires setting a valid access token.")); + new MapboxStaticImage.Builder() + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLat(1.0).setLon(2.0) + .setZoom(10) + .setWidth(100).setHeight(200) + .build(); + } + + @Test + public void requireStyleId() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You need to set a map style.")); + new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setLat(1.0).setLon(2.0) + .setZoom(10) + .setWidth(100).setHeight(200) + .build(); + } + + @Test + public void requireLon() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You need to set the map lon/lat coordinates.")); + new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLat(1.0) + .setZoom(10) + .setWidth(100).setHeight(200) + .build(); + } + + @Test + public void requireLat() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You need to set the map lon/lat coordinates.")); + new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLon(2.0) + .setZoom(10) + .setWidth(100).setHeight(200) + .build(); + } + + @Test + public void requireZoom() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You need to set the map zoom level.")); + new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLat(1.0).setLon(2.0) + .setWidth(100).setHeight(200) + .build(); + } + + @Test + public void requireWidth() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You need to set a valid image width (between 1 and 1280).")); + new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLat(1.0).setLon(2.0) + .setZoom(10) + .setHeight(200) + .build(); + } + + @Test + public void requireHeight() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You need to set a valid image height (between 1 and 1280).")); + new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLat(1.0).setLon(2.0) + .setZoom(10) + .setWidth(100) + .build(); + } + + @Test + public void requireHeightInRange() throws ServicesException { + thrown.expect(ServicesException.class); + thrown.expectMessage(startsWith("You need to set a valid image height (between 1 and 1280).")); + new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLat(1.0).setLon(2.0) + .setZoom(10) + .setWidth(100) + .setHeight(5000) + .build(); + } + + @Test + public void testPrecision() throws ServicesException { + MapboxStaticImage client = new MapboxStaticImage.Builder() + .setAccessToken("pk.") + .setStyleId(Constants.MAPBOX_STYLE_STREETS) + .setLocation(Position.fromCoordinates(1.23456789, -98.76)) + .setZoom(10).setBearing(345.67890123456789).setPitch(0.000000005) + .setWidth(100).setHeight(200) + .setPrecision(5) + .build(); + HttpUrl url = client.getUrl(); + assertEquals( + url.toString(), + "https://api.mapbox.com/styles/v1/mapbox/streets-v9/static/1.23456,-98.76000,10.00000,345.67890,0.00000/100x200?access_token=pk."); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/tidy/TidyTest.java b/libjava/lib/src/test/java/com/mapbox/services/tidy/TidyTest.java index 8f2e2e80a..ffda87b16 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/tidy/TidyTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/tidy/TidyTest.java @@ -16,72 +16,69 @@ import static org.junit.Assert.assertEquals; -/** - * Created by antonio on 7/26/16. - */ public class TidyTest extends BaseTest { - @Test - public void testDates() throws IOException, ParseException { - FeatureCollection walk1 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-1.json")); - JsonArray timeStamp = walk1.getFeatures().get(0).getProperties().getAsJsonArray(Tidy.KEY_COORD_TIMES); - assertEquals(timeStamp.size(), 423); - - String sampleString = timeStamp.get(0).getAsString(); - assertEquals(sampleString, "2015-06-05T01:07:54Z"); - - Tidy tidy = new Tidy(); - Calendar calendar = Calendar.getInstance(); - Date date = tidy.getDateFormat().parse(sampleString); - calendar.setTime(date); - assertEquals(calendar.get(Calendar.YEAR), 2015); - assertEquals(calendar.get(Calendar.MONTH), Calendar.JUNE); - assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 5); - assertEquals(calendar.get(Calendar.HOUR), 1); - assertEquals(calendar.get(Calendar.MINUTE), 7); - assertEquals(calendar.get(Calendar.SECOND), 54); - } - - @Test - public void testWithoutTimestamps() throws IOException, TurfException, ServicesException { - // Process a feature collection without timestamps - FeatureCollection walk2 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-2.json")); - - Tidy tidy = new Tidy(); - FeatureCollection result = tidy.execute(walk2); - compareJson(loadJsonFixture("tidy", "walk-2-tidy.json"), result.toJson()); - } - - @Test - public void testWithTimestamps() throws IOException, TurfException, ServicesException { - // Process a feature collection with timestamps - FeatureCollection walk1 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-1.json")); - - Tidy tidy = new Tidy(); - FeatureCollection result = tidy.execute(walk1); - compareJson(loadJsonFixture("tidy", "walk-1-tidy.json"), result.toJson()); - } - - @Test - public void testWithOptions() throws IOException, TurfException, ServicesException { - // Process a feature collection with custom minimumDistance minimumTime and maximumPoints - FeatureCollection walk1 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-1.json")); - - Tidy tidy = new Tidy(); - tidy.setMinimumDistance(20); - tidy.setMinimumTime(7000); - tidy.setMaximumPoints(10); - FeatureCollection result = tidy.execute(walk1); - compareJson(loadJsonFixture("tidy", "walk-1-resampled.json"), result.toJson()); - } - - @Test - public void testWithMultiple() throws IOException, TurfException, ServicesException { - // Process a feature collection with multiple features - FeatureCollection crossCountry = FeatureCollection.fromJson(loadJsonFixture("tidy", "cross-country.json")); - - Tidy tidy = new Tidy(); - FeatureCollection result = tidy.execute(crossCountry); - compareJson(loadJsonFixture("tidy", "cross-country-tidy.json"), result.toJson()); - } + @Test + public void testDates() throws IOException, ParseException { + FeatureCollection walk1 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-1.json")); + JsonArray timeStamp = walk1.getFeatures().get(0).getProperties().getAsJsonArray(Tidy.KEY_COORD_TIMES); + assertEquals(timeStamp.size(), 423); + + String sampleString = timeStamp.get(0).getAsString(); + assertEquals(sampleString, "2015-06-05T01:07:54Z"); + + Tidy tidy = new Tidy(); + Calendar calendar = Calendar.getInstance(); + Date date = tidy.getDateFormat().parse(sampleString); + calendar.setTime(date); + assertEquals(calendar.get(Calendar.YEAR), 2015); + assertEquals(calendar.get(Calendar.MONTH), Calendar.JUNE); + assertEquals(calendar.get(Calendar.DAY_OF_MONTH), 5); + assertEquals(calendar.get(Calendar.HOUR), 1); + assertEquals(calendar.get(Calendar.MINUTE), 7); + assertEquals(calendar.get(Calendar.SECOND), 54); + } + + @Test + public void testWithoutTimestamps() throws IOException, TurfException, ServicesException { + // Process a feature collection without timestamps + FeatureCollection walk2 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-2.json")); + + Tidy tidy = new Tidy(); + FeatureCollection result = tidy.execute(walk2); + compareJson(loadJsonFixture("tidy", "walk-2-tidy.json"), result.toJson()); + } + + @Test + public void testWithTimestamps() throws IOException, TurfException, ServicesException { + // Process a feature collection with timestamps + FeatureCollection walk1 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-1.json")); + + Tidy tidy = new Tidy(); + FeatureCollection result = tidy.execute(walk1); + compareJson(loadJsonFixture("tidy", "walk-1-tidy.json"), result.toJson()); + } + + @Test + public void testWithOptions() throws IOException, TurfException, ServicesException { + // Process a feature collection with custom minimumDistance minimumTime and maximumPoints + FeatureCollection walk1 = FeatureCollection.fromJson(loadJsonFixture("tidy", "walk-1.json")); + + Tidy tidy = new Tidy(); + tidy.setMinimumDistance(20); + tidy.setMinimumTime(7000); + tidy.setMaximumPoints(10); + FeatureCollection result = tidy.execute(walk1); + compareJson(loadJsonFixture("tidy", "walk-1-resampled.json"), result.toJson()); + } + + @Test + public void testWithMultiple() throws IOException, TurfException, ServicesException { + // Process a feature collection with multiple features + FeatureCollection crossCountry = FeatureCollection.fromJson(loadJsonFixture("tidy", "cross-country.json")); + + Tidy tidy = new Tidy(); + FeatureCollection result = tidy.execute(crossCountry); + compareJson(loadJsonFixture("tidy", "cross-country-tidy.json"), result.toJson()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/turf/BaseTurf.java b/libjava/lib/src/test/java/com/mapbox/services/turf/BaseTurf.java index 85aafa936..174278e55 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/turf/BaseTurf.java +++ b/libjava/lib/src/test/java/com/mapbox/services/turf/BaseTurf.java @@ -2,9 +2,6 @@ import com.mapbox.services.BaseTest; -/** - * Created by antonio on 7/8/16. - */ public class BaseTurf extends BaseTest { } diff --git a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfGridsTest.java b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfGridsTest.java index ffbe249b7..6b9fe8d4c 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfGridsTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfGridsTest.java @@ -16,57 +16,54 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -/** - * Created by antonio on 7/15/16. - */ public class TurfGridsTest { - @Test - public void testWithin() throws TurfException { - // Test with a single point - ArrayList pointList = new ArrayList<>(); - pointList.add(Position.fromCoordinates(0, 0)); - pointList.add(Position.fromCoordinates(0, 100)); - pointList.add(Position.fromCoordinates(100, 100)); - pointList.add(Position.fromCoordinates(100, 0)); - pointList.add(Position.fromCoordinates(0, 0)); - ArrayList> coordinates = new ArrayList<>(); - coordinates.add(pointList); - Polygon poly = Polygon.fromCoordinates(coordinates); + @Test + public void testWithin() throws TurfException { + // Test with a single point + ArrayList pointList = new ArrayList<>(); + pointList.add(Position.fromCoordinates(0, 0)); + pointList.add(Position.fromCoordinates(0, 100)); + pointList.add(Position.fromCoordinates(100, 100)); + pointList.add(Position.fromCoordinates(100, 0)); + pointList.add(Position.fromCoordinates(0, 0)); + ArrayList> coordinates = new ArrayList<>(); + coordinates.add(pointList); + Polygon poly = Polygon.fromCoordinates(coordinates); - Point pt = Point.fromCoordinates(Position.fromCoordinates(50, 50)); + Point pt = Point.fromCoordinates(Position.fromCoordinates(50, 50)); - ArrayList features1 = new ArrayList<>(); - features1.add(Feature.fromGeometry(poly)); - FeatureCollection polyFC = FeatureCollection.fromFeatures(features1); + ArrayList features1 = new ArrayList<>(); + features1.add(Feature.fromGeometry(poly)); + FeatureCollection polyFC = FeatureCollection.fromFeatures(features1); - ArrayList features2 = new ArrayList<>(); - features2.add(Feature.fromGeometry(pt)); - FeatureCollection ptFC = FeatureCollection.fromFeatures(features2); + ArrayList features2 = new ArrayList<>(); + features2.add(Feature.fromGeometry(pt)); + FeatureCollection ptFC = FeatureCollection.fromFeatures(features2); - FeatureCollection counted = TurfGrids.within(ptFC, polyFC); - assertNotNull(counted); - assertEquals(counted.getFeatures().size(), 1); // 1 point in 1 polygon + FeatureCollection counted = TurfGrids.within(ptFC, polyFC); + assertNotNull(counted); + assertEquals(counted.getFeatures().size(), 1); // 1 point in 1 polygon - // test with multiple points and multiple polygons - Polygon poly1 = Polygon.fromCoordinates(new double[][][]{{{0,0},{10,0},{10,10},{0,10},{0,0}}}); - Polygon poly2 = Polygon.fromCoordinates(new double[][][]{{{10,0},{20,10},{20,20},{20,0},{10,0}}}); - polyFC = FeatureCollection.fromFeatures(new Feature[]{ - Feature.fromGeometry(poly1), - Feature.fromGeometry(poly2)}); + // test with multiple points and multiple polygons + Polygon poly1 = Polygon.fromCoordinates(new double[][][] {{{0, 0}, {10, 0}, {10, 10}, {0, 10}, {0, 0}}}); + Polygon poly2 = Polygon.fromCoordinates(new double[][][] {{{10, 0}, {20, 10}, {20, 20}, {20, 0}, {10, 0}}}); + polyFC = FeatureCollection.fromFeatures(new Feature[] { + Feature.fromGeometry(poly1), + Feature.fromGeometry(poly2)}); - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(1, 1)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(1, 3)); - Point pt3 = Point.fromCoordinates(Position.fromCoordinates(14, 2)); - Point pt4 = Point.fromCoordinates(Position.fromCoordinates(13, 1)); - Point pt5 = Point.fromCoordinates(Position.fromCoordinates(19, 7)); - Point pt6 = Point.fromCoordinates(Position.fromCoordinates(100, 7)); - ptFC = FeatureCollection.fromFeatures(new Feature[]{ - Feature.fromGeometry(pt1), Feature.fromGeometry(pt2), Feature.fromGeometry(pt3), - Feature.fromGeometry(pt4), Feature.fromGeometry(pt5), Feature.fromGeometry(pt6)}); + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(1, 1)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(1, 3)); + Point pt3 = Point.fromCoordinates(Position.fromCoordinates(14, 2)); + Point pt4 = Point.fromCoordinates(Position.fromCoordinates(13, 1)); + Point pt5 = Point.fromCoordinates(Position.fromCoordinates(19, 7)); + Point pt6 = Point.fromCoordinates(Position.fromCoordinates(100, 7)); + ptFC = FeatureCollection.fromFeatures(new Feature[] { + Feature.fromGeometry(pt1), Feature.fromGeometry(pt2), Feature.fromGeometry(pt3), + Feature.fromGeometry(pt4), Feature.fromGeometry(pt5), Feature.fromGeometry(pt6)}); - counted = TurfGrids.within(ptFC, polyFC); - assertNotNull(counted); - assertEquals(counted.getFeatures().size(), 5); // multiple points in multiple polygons - } + counted = TurfGrids.within(ptFC, polyFC); + assertNotNull(counted); + assertEquals(counted.getFeatures().size(), 5); // multiple points in multiple polygons + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfInvariantTest.java b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfInvariantTest.java index 54ea88d8d..182a7c86b 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfInvariantTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfInvariantTest.java @@ -16,106 +16,106 @@ public class TurfInvariantTest extends BaseTurf { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testInvariantGeojsonType1() throws TurfException { - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Type and name required")); - TurfInvariant.geojsonType(null, null, null); - } - - @Test - public void testInvariantGeojsonType2() throws TurfException { - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Type and name required")); - TurfInvariant.geojsonType(null, null, "myfn"); - } - - @Test - public void testInvariantGeojsonType3() throws TurfException { - String json = "{ type: 'Point', coordinates: [0, 0] }"; - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Invalid input to myfn: must be a Polygon, given Point")); - TurfInvariant.geojsonType(Point.fromJson(json), "Polygon", "myfn"); - } - - @Test - public void testInvariantGeojsonType4() throws TurfException { - String json = "{ type: 'Point', coordinates: [0, 0] }"; - TurfInvariant.geojsonType(Point.fromJson(json), "Point", "myfn"); - } - - @Test - public void testInvariantFeatureOf1() throws TurfException { - String json = "{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0] }, properties: {}}"; - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith(".featureOf() requires a name")); - TurfInvariant.featureOf(Feature.fromJson(json), "Polygon", null); - } - - @Test - public void testInvariantFeatureOf2() throws TurfException { - String json = "{}"; - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Invalid input to foo, Feature with geometry required")); - TurfInvariant.featureOf(Feature.fromJson(json), "Polygon", "foo"); - } - - @Test - public void testInvariantFeatureOf3() throws TurfException { - String json = "{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0] }}"; - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Invalid input to myfn: must be a Polygon, given Point")); - TurfInvariant.featureOf(Feature.fromJson(json), "Polygon", "myfn"); - } - - @Test - public void testInvariantFeatureOf4() throws TurfException { - String json = "{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0]}, properties: {}}"; - TurfInvariant.featureOf(Feature.fromJson(json), "Point", "myfn"); - } - - @Test - public void testInvariantCollectionOf1() throws TurfException { - String json = "{type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0]}, properties: {}}]}"; - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Invalid input to myfn: must be a Polygon, given Point")); - TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Polygon", "myfn"); - } - - @Test - public void testInvariantCollectionOf2() throws TurfException { - String json = "{}"; - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("collectionOf() requires a name")); - TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Polygon", null); - } - - @Test - public void testInvariantCollectionOf3() throws TurfException { - String json = "{}"; - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Invalid input to foo, FeatureCollection required")); - TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Polygon", "foo"); - } - - @Test - public void testInvariantCollectionOf4() throws TurfException { - String json = "{type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0]}, properties: {}}]}"; - TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Point", "myfn"); - } - - - @Test - public void testInvariantGetCoord() throws TurfException { - String jsonPoint = "{type: 'Point', coordinates: [1, 2]}"; - String jsonFeature = "{type: 'Feature', geometry: {type: 'Point', coordinates: [1, 2]}}"; - - assertEquals(TurfInvariant.getCoord(Point.fromJson(jsonPoint)), Position.fromCoordinates(1, 2)); - assertEquals(TurfInvariant.getCoord(Feature.fromJson(jsonFeature)), Position.fromCoordinates(1, 2)); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testInvariantGeojsonType1() throws TurfException { + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Type and name required")); + TurfInvariant.geojsonType(null, null, null); + } + + @Test + public void testInvariantGeojsonType2() throws TurfException { + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Type and name required")); + TurfInvariant.geojsonType(null, null, "myfn"); + } + + @Test + public void testInvariantGeojsonType3() throws TurfException { + String json = "{ type: 'Point', coordinates: [0, 0] }"; + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Invalid input to myfn: must be a Polygon, given Point")); + TurfInvariant.geojsonType(Point.fromJson(json), "Polygon", "myfn"); + } + + @Test + public void testInvariantGeojsonType4() throws TurfException { + String json = "{ type: 'Point', coordinates: [0, 0] }"; + TurfInvariant.geojsonType(Point.fromJson(json), "Point", "myfn"); + } + + @Test + public void testInvariantFeatureOf1() throws TurfException { + String json = "{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0] }, properties: {}}"; + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith(".featureOf() requires a name")); + TurfInvariant.featureOf(Feature.fromJson(json), "Polygon", null); + } + + @Test + public void testInvariantFeatureOf2() throws TurfException { + String json = "{}"; + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Invalid input to foo, Feature with geometry required")); + TurfInvariant.featureOf(Feature.fromJson(json), "Polygon", "foo"); + } + + @Test + public void testInvariantFeatureOf3() throws TurfException { + String json = "{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0] }}"; + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Invalid input to myfn: must be a Polygon, given Point")); + TurfInvariant.featureOf(Feature.fromJson(json), "Polygon", "myfn"); + } + + @Test + public void testInvariantFeatureOf4() throws TurfException { + String json = "{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0]}, properties: {}}"; + TurfInvariant.featureOf(Feature.fromJson(json), "Point", "myfn"); + } + + @Test + public void testInvariantCollectionOf1() throws TurfException { + String json = "{type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0]}, properties: {}}]}"; + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Invalid input to myfn: must be a Polygon, given Point")); + TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Polygon", "myfn"); + } + + @Test + public void testInvariantCollectionOf2() throws TurfException { + String json = "{}"; + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("collectionOf() requires a name")); + TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Polygon", null); + } + + @Test + public void testInvariantCollectionOf3() throws TurfException { + String json = "{}"; + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Invalid input to foo, FeatureCollection required")); + TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Polygon", "foo"); + } + + @Test + public void testInvariantCollectionOf4() throws TurfException { + String json = "{type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [0, 0]}, properties: {}}]}"; + TurfInvariant.collectionOf(FeatureCollection.fromJson(json), "Point", "myfn"); + } + + + @Test + public void testInvariantGetCoord() throws TurfException { + String jsonPoint = "{type: 'Point', coordinates: [1, 2]}"; + String jsonFeature = "{type: 'Feature', geometry: {type: 'Point', coordinates: [1, 2]}}"; + + assertEquals(TurfInvariant.getCoord(Point.fromJson(jsonPoint)), Position.fromCoordinates(1, 2)); + assertEquals(TurfInvariant.getCoord(Feature.fromJson(jsonFeature)), Position.fromCoordinates(1, 2)); + } } \ No newline at end of file diff --git a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfJoinsTest.java b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfJoinsTest.java index a2ede8ed9..28cd4bdfa 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfJoinsTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfJoinsTest.java @@ -19,86 +19,86 @@ public class TurfJoinsTest extends BaseTurf { - @Test - public void testFeatureCollection() throws TurfException { - // Test for a simple polygon - ArrayList pointList = new ArrayList<>(); - pointList.add(Position.fromCoordinates(0, 0)); - pointList.add(Position.fromCoordinates(0, 100)); - pointList.add(Position.fromCoordinates(100, 100)); - pointList.add(Position.fromCoordinates(100, 0)); - pointList.add(Position.fromCoordinates(0, 0)); - List> coordinates = new ArrayList<>(); - coordinates.add(pointList); - Polygon poly = Polygon.fromCoordinates(coordinates); - - Point ptIn = Point.fromCoordinates(Position.fromCoordinates(50, 50)); - Point ptOut = Point.fromCoordinates(Position.fromCoordinates(140, 150)); - - assertTrue(TurfJoins.inside(ptIn, poly)); - assertFalse(TurfJoins.inside(ptOut, poly)); - - // Test for a concave polygon - pointList = new ArrayList<>(); - pointList.add(Position.fromCoordinates(0, 0)); - pointList.add(Position.fromCoordinates(50, 50)); - pointList.add(Position.fromCoordinates(0, 100)); - pointList.add(Position.fromCoordinates(100, 100)); - pointList.add(Position.fromCoordinates(100, 0)); - pointList.add(Position.fromCoordinates(0, 0)); - coordinates = new ArrayList<>(); - coordinates.add(pointList); - Polygon concavePoly = Polygon.fromCoordinates(coordinates); - - ptIn = Point.fromCoordinates(Position.fromCoordinates(75, 75)); - ptOut = Point.fromCoordinates(Position.fromCoordinates(25, 50)); - - assertTrue(TurfJoins.inside(ptIn, concavePoly)); - assertFalse(TurfJoins.inside(ptOut, concavePoly)); - } - - @Test - public void testPolyWithHole() throws TurfException, IOException { - Point ptInHole = Point.fromCoordinates(Position.fromCoordinates(-86.69208526611328, 36.20373274711739)); - Point ptInPoly = Point.fromCoordinates(Position.fromCoordinates(-86.72229766845702, 36.20258997094334)); - Point ptOutsidePoly = Point.fromCoordinates(Position.fromCoordinates(-86.75079345703125, 36.18527313913089)); - Feature polyHole = Feature.fromJson(loadJsonFixture("turf-inside", "poly-with-hole.geojson")); - - assertFalse(TurfJoins.inside(ptInHole, (Polygon)polyHole.getGeometry())); - assertTrue(TurfJoins.inside(ptInPoly, (Polygon)polyHole.getGeometry())); - assertFalse(TurfJoins.inside(ptOutsidePoly, (Polygon)polyHole.getGeometry())); - } - - @Test - public void testMultipolygonWithHole() throws TurfException, IOException { - Point ptInHole = Point.fromCoordinates(Position.fromCoordinates(-86.69208526611328, 36.20373274711739)); - Point ptInPoly = Point.fromCoordinates(Position.fromCoordinates(-86.72229766845702, 36.20258997094334)); - Point ptInPoly2 = Point.fromCoordinates(Position.fromCoordinates(-86.75079345703125, 36.18527313913089)); - Point ptOutsidePoly = Point.fromCoordinates(Position.fromCoordinates(-86.75302505493164, 36.23015046460186)); - - Feature multiPolyHole = Feature.fromJson(loadJsonFixture("turf-inside", "multipoly-with-hole.geojson")); - assertFalse(TurfJoins.inside(ptInHole, (MultiPolygon)multiPolyHole.getGeometry())); - assertTrue(TurfJoins.inside(ptInPoly, (MultiPolygon)multiPolyHole.getGeometry())); - assertTrue(TurfJoins.inside(ptInPoly2, (MultiPolygon)multiPolyHole.getGeometry())); - assertFalse(TurfJoins.inside(ptOutsidePoly, (MultiPolygon)multiPolyHole.getGeometry())); - } + @Test + public void testFeatureCollection() throws TurfException { + // Test for a simple polygon + ArrayList pointList = new ArrayList<>(); + pointList.add(Position.fromCoordinates(0, 0)); + pointList.add(Position.fromCoordinates(0, 100)); + pointList.add(Position.fromCoordinates(100, 100)); + pointList.add(Position.fromCoordinates(100, 0)); + pointList.add(Position.fromCoordinates(0, 0)); + List> coordinates = new ArrayList<>(); + coordinates.add(pointList); + Polygon poly = Polygon.fromCoordinates(coordinates); + + Point ptIn = Point.fromCoordinates(Position.fromCoordinates(50, 50)); + Point ptOut = Point.fromCoordinates(Position.fromCoordinates(140, 150)); + + assertTrue(TurfJoins.inside(ptIn, poly)); + assertFalse(TurfJoins.inside(ptOut, poly)); + + // Test for a concave polygon + pointList = new ArrayList<>(); + pointList.add(Position.fromCoordinates(0, 0)); + pointList.add(Position.fromCoordinates(50, 50)); + pointList.add(Position.fromCoordinates(0, 100)); + pointList.add(Position.fromCoordinates(100, 100)); + pointList.add(Position.fromCoordinates(100, 0)); + pointList.add(Position.fromCoordinates(0, 0)); + coordinates = new ArrayList<>(); + coordinates.add(pointList); + Polygon concavePoly = Polygon.fromCoordinates(coordinates); + + ptIn = Point.fromCoordinates(Position.fromCoordinates(75, 75)); + ptOut = Point.fromCoordinates(Position.fromCoordinates(25, 50)); + + assertTrue(TurfJoins.inside(ptIn, concavePoly)); + assertFalse(TurfJoins.inside(ptOut, concavePoly)); + } + + @Test + public void testPolyWithHole() throws TurfException, IOException { + Point ptInHole = Point.fromCoordinates(Position.fromCoordinates(-86.69208526611328, 36.20373274711739)); + Point ptInPoly = Point.fromCoordinates(Position.fromCoordinates(-86.72229766845702, 36.20258997094334)); + Point ptOutsidePoly = Point.fromCoordinates(Position.fromCoordinates(-86.75079345703125, 36.18527313913089)); + Feature polyHole = Feature.fromJson(loadJsonFixture("turf-inside", "poly-with-hole.geojson")); + + assertFalse(TurfJoins.inside(ptInHole, (Polygon) polyHole.getGeometry())); + assertTrue(TurfJoins.inside(ptInPoly, (Polygon) polyHole.getGeometry())); + assertFalse(TurfJoins.inside(ptOutsidePoly, (Polygon) polyHole.getGeometry())); + } + + @Test + public void testMultipolygonWithHole() throws TurfException, IOException { + Point ptInHole = Point.fromCoordinates(Position.fromCoordinates(-86.69208526611328, 36.20373274711739)); + Point ptInPoly = Point.fromCoordinates(Position.fromCoordinates(-86.72229766845702, 36.20258997094334)); + Point ptInPoly2 = Point.fromCoordinates(Position.fromCoordinates(-86.75079345703125, 36.18527313913089)); + Point ptOutsidePoly = Point.fromCoordinates(Position.fromCoordinates(-86.75302505493164, 36.23015046460186)); + + Feature multiPolyHole = Feature.fromJson(loadJsonFixture("turf-inside", "multipoly-with-hole.geojson")); + assertFalse(TurfJoins.inside(ptInHole, (MultiPolygon) multiPolyHole.getGeometry())); + assertTrue(TurfJoins.inside(ptInPoly, (MultiPolygon) multiPolyHole.getGeometry())); + assertTrue(TurfJoins.inside(ptInPoly2, (MultiPolygon) multiPolyHole.getGeometry())); + assertFalse(TurfJoins.inside(ptOutsidePoly, (MultiPolygon) multiPolyHole.getGeometry())); + } /* * Custom test */ - @Test - public void testInputPositions() throws IOException, TurfException { - Position ptInPoly = Position.fromCoordinates(-86.72229766845702, 36.20258997094334); - Position ptOutsidePoly = Position.fromCoordinates(-86.75079345703125, 36.18527313913089); - Feature polyHole = Feature.fromJson(loadJsonFixture("turf-inside", "poly-with-hole.geojson")); + @Test + public void testInputPositions() throws IOException, TurfException { + Position ptInPoly = Position.fromCoordinates(-86.72229766845702, 36.20258997094334); + Position ptOutsidePoly = Position.fromCoordinates(-86.75079345703125, 36.18527313913089); + Feature polyHole = Feature.fromJson(loadJsonFixture("turf-inside", "poly-with-hole.geojson")); - Polygon polygon = (Polygon) polyHole.getGeometry(); - List> polygonPosition = polygon.getCoordinates(); + Polygon polygon = (Polygon) polyHole.getGeometry(); + List> polygonPosition = polygon.getCoordinates(); - assertTrue(TurfJoins.inside(ptInPoly, polygonPosition.get(0))); - assertFalse(TurfJoins.inside(ptOutsidePoly, polygonPosition.get(0))); + assertTrue(TurfJoins.inside(ptInPoly, polygonPosition.get(0))); + assertFalse(TurfJoins.inside(ptOutsidePoly, polygonPosition.get(0))); - } + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMeasurementTest.java b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMeasurementTest.java index b7d1eea1e..5d0e16b47 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMeasurementTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMeasurementTest.java @@ -23,201 +23,201 @@ public class TurfMeasurementTest extends BaseTurf { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testBearing() { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-75.4, 39.4)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(-75.534, 39.123)); - assertNotEquals(TurfMeasurement.bearing(pt1, pt2), 0, DELTA); - } - - @Test - public void testDestination() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-75.0, 39.0)); - double dist = 100; - double bear = 180; - assertNotNull(TurfMeasurement.destination(pt1, dist, bear, TurfConstants.UNIT_KILOMETERS)); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testBearing() { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-75.4, 39.4)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(-75.534, 39.123)); + assertNotEquals(TurfMeasurement.bearing(pt1, pt2), 0, DELTA); + } + + @Test + public void testDestination() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-75.0, 39.0)); + double dist = 100; + double bear = 180; + assertNotNull(TurfMeasurement.destination(pt1, dist, bear, TurfConstants.UNIT_KILOMETERS)); + } /* * Turf distance tests */ - @Test - public void testDistance() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-75.343, 39.984)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(-75.534, 39.123)); - - // Common cases - assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_MILES), 60.37218405837491, DELTA); - assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_NAUTICAL_MILES), 52.461979624130436, DELTA); - assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_KILOMETERS), 97.15957803131901, DELTA); - assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_RADIANS), 0.015245501024842149, DELTA); - assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_DEGREES), 0.8735028650863799, DELTA); - - // This also works - assertEquals(TurfMeasurement.distance(pt1, pt2, "kilometres"), 97.15957803131901, DELTA); - - // Default is kilometers - assertEquals(TurfMeasurement.distance(pt1, pt2), 97.15957803131901, DELTA); - - // Bad unit - thrown.expect(TurfException.class); - thrown.expectMessage(startsWith("Invalid unit.")); - TurfMeasurement.distance(pt1, pt2, "blah"); - } - - @Test - public void testLineDistanceLineString() throws IOException, TurfException { - Feature route1 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route1.geojson")); - Feature route2 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route2.geojson")); - assertEquals(Math.round(TurfMeasurement.lineDistance(route1, "miles")), 202); - assertTrue((TurfMeasurement.lineDistance(route2, "kilometers") - 742) < 1 - && (TurfMeasurement.lineDistance(route2, "kilometers") - 742) > (-1)); - } - - @Test - public void testLineDistanceWithGeometries() throws IOException, TurfException { - Feature route1 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route1.geojson")); - Feature route2 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route2.geojson")); - assertEquals(Math.round(TurfMeasurement.lineDistance(route1.getGeometry(), "miles")), 202); - assertTrue((TurfMeasurement.lineDistance(route2.getGeometry(), "kilometers") - 742) < 1 - && (TurfMeasurement.lineDistance(route2.getGeometry(), "kilometers") - 742) > (-1)); - } - - @Test - public void testLineDistancePolygon() throws IOException, TurfException { - Feature feat = Feature.fromJson(loadJsonFixture("turf-line-distance", "polygon.geojson")); - assertEquals(Math.round(1000 * TurfMeasurement.lineDistance(feat, "kilometers")), 5599); - } - - @Test - public void testLineDistanceMultiLineString() throws IOException, TurfException { - Feature feat = Feature.fromJson(loadJsonFixture("turf-line-distance", "multilinestring.geojson")); - assertEquals(Math.round(1000 * TurfMeasurement.lineDistance(feat, "kilometers")), 4705); - } - - @Test - public void testLineDistanceFeatureCollection() throws IOException, TurfException { - FeatureCollection feat = FeatureCollection.fromJson(loadJsonFixture("turf-line-distance", "featurecollection.geojson")); - assertEquals(Math.round(1000 * TurfMeasurement.lineDistance(feat, "kilometers")), 10304); - } + @Test + public void testDistance() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-75.343, 39.984)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(-75.534, 39.123)); + + // Common cases + assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_MILES), 60.37218405837491, DELTA); + assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_NAUTICAL_MILES), 52.461979624130436, DELTA); + assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_KILOMETERS), 97.15957803131901, DELTA); + assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_RADIANS), 0.015245501024842149, DELTA); + assertEquals(TurfMeasurement.distance(pt1, pt2, TurfConstants.UNIT_DEGREES), 0.8735028650863799, DELTA); + + // This also works + assertEquals(TurfMeasurement.distance(pt1, pt2, "kilometres"), 97.15957803131901, DELTA); + + // Default is kilometers + assertEquals(TurfMeasurement.distance(pt1, pt2), 97.15957803131901, DELTA); + + // Bad unit + thrown.expect(TurfException.class); + thrown.expectMessage(startsWith("Invalid unit.")); + TurfMeasurement.distance(pt1, pt2, "blah"); + } + + @Test + public void testLineDistanceLineString() throws IOException, TurfException { + Feature route1 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route1.geojson")); + Feature route2 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route2.geojson")); + assertEquals(Math.round(TurfMeasurement.lineDistance(route1, "miles")), 202); + assertTrue((TurfMeasurement.lineDistance(route2, "kilometers") - 742) < 1 + && (TurfMeasurement.lineDistance(route2, "kilometers") - 742) > (-1)); + } + + @Test + public void testLineDistanceWithGeometries() throws IOException, TurfException { + Feature route1 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route1.geojson")); + Feature route2 = Feature.fromJson(loadJsonFixture("turf-line-distance", "route2.geojson")); + assertEquals(Math.round(TurfMeasurement.lineDistance(route1.getGeometry(), "miles")), 202); + assertTrue((TurfMeasurement.lineDistance(route2.getGeometry(), "kilometers") - 742) < 1 + && (TurfMeasurement.lineDistance(route2.getGeometry(), "kilometers") - 742) > (-1)); + } + + @Test + public void testLineDistancePolygon() throws IOException, TurfException { + Feature feat = Feature.fromJson(loadJsonFixture("turf-line-distance", "polygon.geojson")); + assertEquals(Math.round(1000 * TurfMeasurement.lineDistance(feat, "kilometers")), 5599); + } + + @Test + public void testLineDistanceMultiLineString() throws IOException, TurfException { + Feature feat = Feature.fromJson(loadJsonFixture("turf-line-distance", "multilinestring.geojson")); + assertEquals(Math.round(1000 * TurfMeasurement.lineDistance(feat, "kilometers")), 4705); + } + + @Test + public void testLineDistanceFeatureCollection() throws IOException, TurfException { + FeatureCollection feat = FeatureCollection.fromJson(loadJsonFixture("turf-line-distance", "featurecollection.geojson")); + assertEquals(Math.round(1000 * TurfMeasurement.lineDistance(feat, "kilometers")), 10304); + } /* * Turf midpoint tests */ - @Test - public void testMidpointHorizontalEquator() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(0, 0)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(10, 0)); - Point mid = TurfMeasurement.midpoint(pt1, pt2); - - assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), - TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); - } - - @Test - public void testMidpointVericalFromEquator() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(0, 0)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(0, 10)); - Point mid = TurfMeasurement.midpoint(pt1, pt2); - - assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), - TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); - } - - @Test - public void testMidpointVericalToEquator() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(0, 10)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(0, 0)); - Point mid = TurfMeasurement.midpoint(pt1, pt2); - - assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), - TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); - } - - @Test - public void testMidpointDiagonalBackOverEquator() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-1, 10)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(1, -1)); - Point mid = TurfMeasurement.midpoint(pt1, pt2); - - assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), - TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); - } - - @Test - public void testMidpointDiagonalForwardOverEquator() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-5, -1)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(5, 10)); - Point mid = TurfMeasurement.midpoint(pt1, pt2); - - assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), - TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); - } - - @Test - public void testMidpointLongDistance() throws TurfException { - Point pt1 = Point.fromCoordinates(Position.fromCoordinates(22.5, 21.94304553343818)); - Point pt2 = Point.fromCoordinates(Position.fromCoordinates(92.10937499999999, 46.800059446787316)); - Point mid = TurfMeasurement.midpoint(pt1, pt2); - - assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), - TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); - } - - // Custom test to make sure conversion of Position to point works correctly - @Test - public void testMidpointPositionToPoint() throws TurfException { - Position pt1 = Position.fromCoordinates(0, 0); - Position pt2 = Position.fromCoordinates(10, 0); - Position mid = TurfMeasurement.midpoint(pt1, pt2); - - assertEquals(TurfMeasurement.distance(Point.fromCoordinates(pt1), - Point.fromCoordinates(mid), TurfConstants.UNIT_MILES), - TurfMeasurement.distance(Point.fromCoordinates(pt2), - Point.fromCoordinates(mid), TurfConstants.UNIT_MILES), DELTA); - } - - @Test - public void testTurfAlong() throws IOException, TurfException { - Feature feature = Feature.fromJson(loadJsonFixture("turf-along", "dc-line.geojson")); - LineString line = (LineString) feature.getGeometry(); - - Point pt1 = TurfMeasurement.along(line, 1, "miles"); - Point pt2 = TurfMeasurement.along(line, 1.2, "miles"); - Point pt3 = TurfMeasurement.along(line, 1.4, "miles"); - Point pt4 = TurfMeasurement.along(line, 1.6, "miles"); - Point pt5 = TurfMeasurement.along(line, 1.8, "miles"); - Point pt6 = TurfMeasurement.along(line, 2, "miles"); - Point pt7 = TurfMeasurement.along(line, 100, "miles"); - Point pt8 = TurfMeasurement.along(line, 0, "miles"); - FeatureCollection fc = FeatureCollection.fromFeatures(new Feature[] { - Feature.fromGeometry(pt1), - Feature.fromGeometry(pt2), - Feature.fromGeometry(pt3), - Feature.fromGeometry(pt4), - Feature.fromGeometry(pt5), - Feature.fromGeometry(pt6), - Feature.fromGeometry(pt7), - Feature.fromGeometry(pt8) - }); - - for (Feature f: fc.getFeatures()) { - assertNotNull(f); - assertEquals(f.getType(), "Feature"); - assertEquals(f.getGeometry().getType(), "Point"); - } - - assertEquals(fc.getFeatures().size(), 8); - assertEquals( - ((Point) fc.getFeatures().get(7).getGeometry()).getCoordinates().getLongitude(), - pt8.getCoordinates().getLongitude(), DELTA); - assertEquals( - ((Point) fc.getFeatures().get(7).getGeometry()).getCoordinates().getLatitude(), - pt8.getCoordinates().getLatitude(), DELTA); - } + @Test + public void testMidpointHorizontalEquator() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(0, 0)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(10, 0)); + Point mid = TurfMeasurement.midpoint(pt1, pt2); + + assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), + TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); + } + + @Test + public void testMidpointVericalFromEquator() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(0, 0)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(0, 10)); + Point mid = TurfMeasurement.midpoint(pt1, pt2); + + assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), + TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); + } + + @Test + public void testMidpointVericalToEquator() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(0, 10)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(0, 0)); + Point mid = TurfMeasurement.midpoint(pt1, pt2); + + assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), + TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); + } + + @Test + public void testMidpointDiagonalBackOverEquator() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-1, 10)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(1, -1)); + Point mid = TurfMeasurement.midpoint(pt1, pt2); + + assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), + TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); + } + + @Test + public void testMidpointDiagonalForwardOverEquator() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(-5, -1)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(5, 10)); + Point mid = TurfMeasurement.midpoint(pt1, pt2); + + assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), + TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); + } + + @Test + public void testMidpointLongDistance() throws TurfException { + Point pt1 = Point.fromCoordinates(Position.fromCoordinates(22.5, 21.94304553343818)); + Point pt2 = Point.fromCoordinates(Position.fromCoordinates(92.10937499999999, 46.800059446787316)); + Point mid = TurfMeasurement.midpoint(pt1, pt2); + + assertEquals(TurfMeasurement.distance(pt1, mid, TurfConstants.UNIT_MILES), + TurfMeasurement.distance(pt2, mid, TurfConstants.UNIT_MILES), DELTA); + } + + // Custom test to make sure conversion of Position to point works correctly + @Test + public void testMidpointPositionToPoint() throws TurfException { + Position pt1 = Position.fromCoordinates(0, 0); + Position pt2 = Position.fromCoordinates(10, 0); + Position mid = TurfMeasurement.midpoint(pt1, pt2); + + assertEquals(TurfMeasurement.distance(Point.fromCoordinates(pt1), + Point.fromCoordinates(mid), TurfConstants.UNIT_MILES), + TurfMeasurement.distance(Point.fromCoordinates(pt2), + Point.fromCoordinates(mid), TurfConstants.UNIT_MILES), DELTA); + } + + @Test + public void testTurfAlong() throws IOException, TurfException { + Feature feature = Feature.fromJson(loadJsonFixture("turf-along", "dc-line.geojson")); + LineString line = (LineString) feature.getGeometry(); + + Point pt1 = TurfMeasurement.along(line, 1, "miles"); + Point pt2 = TurfMeasurement.along(line, 1.2, "miles"); + Point pt3 = TurfMeasurement.along(line, 1.4, "miles"); + Point pt4 = TurfMeasurement.along(line, 1.6, "miles"); + Point pt5 = TurfMeasurement.along(line, 1.8, "miles"); + Point pt6 = TurfMeasurement.along(line, 2, "miles"); + Point pt7 = TurfMeasurement.along(line, 100, "miles"); + Point pt8 = TurfMeasurement.along(line, 0, "miles"); + FeatureCollection fc = FeatureCollection.fromFeatures(new Feature[] { + Feature.fromGeometry(pt1), + Feature.fromGeometry(pt2), + Feature.fromGeometry(pt3), + Feature.fromGeometry(pt4), + Feature.fromGeometry(pt5), + Feature.fromGeometry(pt6), + Feature.fromGeometry(pt7), + Feature.fromGeometry(pt8) + }); + + for (Feature f : fc.getFeatures()) { + assertNotNull(f); + assertEquals(f.getType(), "Feature"); + assertEquals(f.getGeometry().getType(), "Point"); + } + + assertEquals(fc.getFeatures().size(), 8); + assertEquals( + ((Point) fc.getFeatures().get(7).getGeometry()).getCoordinates().getLongitude(), + pt8.getCoordinates().getLongitude(), DELTA); + assertEquals( + ((Point) fc.getFeatures().get(7).getGeometry()).getCoordinates().getLatitude(), + pt8.getCoordinates().getLatitude(), DELTA); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMiscTest.java b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMiscTest.java index 646b3c39a..c94ff387e 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMiscTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/turf/TurfMiscTest.java @@ -16,85 +16,82 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; -/** - * Created by antonio on 7/8/16. - */ public class TurfMiscTest extends BaseTurf { - @Test - public void testTurfLineSliceLine1() throws IOException, TurfException { - Point start = Point.fromCoordinates(Position.fromCoordinates(-97.79617309570312, 22.254624939561698)); - Point stop = Point.fromCoordinates(Position.fromCoordinates(-97.72750854492188, 22.057641623615734)); + @Test + public void testTurfLineSliceLine1() throws IOException, TurfException { + Point start = Point.fromCoordinates(Position.fromCoordinates(-97.79617309570312, 22.254624939561698)); + Point stop = Point.fromCoordinates(Position.fromCoordinates(-97.72750854492188, 22.057641623615734)); - Feature line1 = Feature.fromJson(loadJsonFixture("turf-line-slice", "line1.geojson")); + Feature line1 = Feature.fromJson(loadJsonFixture("turf-line-slice", "line1.geojson")); - LineString sliced = TurfMisc.lineSlice(start, stop, line1); - assertNotNull(sliced); - } + LineString sliced = TurfMisc.lineSlice(start, stop, line1); + assertNotNull(sliced); + } - @Test - public void testTurfLineSliceRawGeometry() throws IOException, TurfException { - Point start = Point.fromCoordinates(Position.fromCoordinates(-97.79617309570312,22.254624939561698)); - Point stop = Point.fromCoordinates(Position.fromCoordinates(-97.72750854492188,22.057641623615734)); + @Test + public void testTurfLineSliceRawGeometry() throws IOException, TurfException { + Point start = Point.fromCoordinates(Position.fromCoordinates(-97.79617309570312, 22.254624939561698)); + Point stop = Point.fromCoordinates(Position.fromCoordinates(-97.72750854492188, 22.057641623615734)); - Feature line1 = Feature.fromJson(loadJsonFixture("turf-line-slice", "line1.geojson")); + Feature line1 = Feature.fromJson(loadJsonFixture("turf-line-slice", "line1.geojson")); - LineString sliced = TurfMisc.lineSlice(start, stop, (LineString)line1.getGeometry()); - assertNotNull(sliced); - } + LineString sliced = TurfMisc.lineSlice(start, stop, (LineString) line1.getGeometry()); + assertNotNull(sliced); + } - @Test - public void testTurfLineSliceLine2() throws TurfException { - Point start = Point.fromCoordinates(Position.fromCoordinates(0,0.1)); - Point stop = Point.fromCoordinates(Position.fromCoordinates(.9,.8)); + @Test + public void testTurfLineSliceLine2() throws TurfException { + Point start = Point.fromCoordinates(Position.fromCoordinates(0, 0.1)); + Point stop = Point.fromCoordinates(Position.fromCoordinates(.9, .8)); - ArrayList coordinates = new ArrayList<>(); - coordinates.add(Position.fromCoordinates(0, 0)); - coordinates.add(Position.fromCoordinates(1, 1)); - LineString line2 = LineString.fromCoordinates(coordinates); + ArrayList coordinates = new ArrayList<>(); + coordinates.add(Position.fromCoordinates(0, 0)); + coordinates.add(Position.fromCoordinates(1, 1)); + LineString line2 = LineString.fromCoordinates(coordinates); - LineString sliced = TurfMisc.lineSlice(start, stop, line2); - assertNotNull(sliced); - } + LineString sliced = TurfMisc.lineSlice(start, stop, line2); + assertNotNull(sliced); + } - @Test - public void testTurfLineSliceRoute1() throws IOException, TurfException { - Point start = Point.fromCoordinates(Position.fromCoordinates(-79.0850830078125,37.60117623656667)); - Point stop = Point.fromCoordinates(Position.fromCoordinates(-77.7667236328125,38.65119833229951)); + @Test + public void testTurfLineSliceRoute1() throws IOException, TurfException { + Point start = Point.fromCoordinates(Position.fromCoordinates(-79.0850830078125, 37.60117623656667)); + Point stop = Point.fromCoordinates(Position.fromCoordinates(-77.7667236328125, 38.65119833229951)); - Feature route1 = Feature.fromJson(loadJsonFixture("turf-line-slice", "route1.geojson")); + Feature route1 = Feature.fromJson(loadJsonFixture("turf-line-slice", "route1.geojson")); - LineString sliced = TurfMisc.lineSlice(start, stop, route1); - assertNotNull(sliced); - } + LineString sliced = TurfMisc.lineSlice(start, stop, route1); + assertNotNull(sliced); + } - @Test - public void testTurfLineSliceRoute2() throws IOException, TurfException { - Point start = Point.fromCoordinates(Position.fromCoordinates(-112.60660171508789,45.96021963947196)); - Point stop = Point.fromCoordinates(Position.fromCoordinates(-111.97265625,48.84302835299516)); + @Test + public void testTurfLineSliceRoute2() throws IOException, TurfException { + Point start = Point.fromCoordinates(Position.fromCoordinates(-112.60660171508789, 45.96021963947196)); + Point stop = Point.fromCoordinates(Position.fromCoordinates(-111.97265625, 48.84302835299516)); - Feature route2 = Feature.fromJson(loadJsonFixture("turf-line-slice", "route2.geojson")); + Feature route2 = Feature.fromJson(loadJsonFixture("turf-line-slice", "route2.geojson")); - LineString sliced = TurfMisc.lineSlice(start, stop, route2); - assertNotNull(sliced); - } + LineString sliced = TurfMisc.lineSlice(start, stop, route2); + assertNotNull(sliced); + } - @Test - public void testTurfLineSliceVertical() throws IOException, TurfException { - Point start = Point.fromCoordinates(Position.fromCoordinates(-121.25447809696198, 38.70582415504791)); - Point stop = Point.fromCoordinates(Position.fromCoordinates(-121.25447809696198, 38.70634324369764)); + @Test + public void testTurfLineSliceVertical() throws IOException, TurfException { + Point start = Point.fromCoordinates(Position.fromCoordinates(-121.25447809696198, 38.70582415504791)); + Point stop = Point.fromCoordinates(Position.fromCoordinates(-121.25447809696198, 38.70634324369764)); - Feature vertical = Feature.fromJson(loadJsonFixture("turf-line-slice", "vertical.geojson")); + Feature vertical = Feature.fromJson(loadJsonFixture("turf-line-slice", "vertical.geojson")); - LineString sliced = TurfMisc.lineSlice(start, stop, vertical); - assertNotNull(sliced); + LineString sliced = TurfMisc.lineSlice(start, stop, vertical); + assertNotNull(sliced); - // No duplicated coords - assertEquals(sliced.getCoordinates().size(), 2); + // No duplicated coords + assertEquals(sliced.getCoordinates().size(), 2); - // Vertical slice does not collapse to 1st coord - assertNotEquals( - sliced.getCoordinates().get(0).getCoordinates(), - sliced.getCoordinates().get(1).getCoordinates()); - } + // Vertical slice does not collapse to 1st coord + assertNotEquals( + sliced.getCoordinates().get(0).getCoordinates(), + sliced.getCoordinates().get(1).getCoordinates()); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/utils/MapboxUtilsTest.java b/libjava/lib/src/test/java/com/mapbox/services/utils/MapboxUtilsTest.java index d705f3dc3..7531b3521 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/utils/MapboxUtilsTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/utils/MapboxUtilsTest.java @@ -6,26 +6,23 @@ import static org.junit.Assert.*; -/** - * Created by antonio on 4/8/16. - */ public class MapboxUtilsTest { - @Test - public void testEmpty() { - assertFalse(MapboxUtils.isAccessTokenValid(null)); - assertFalse(MapboxUtils.isAccessTokenValid("")); - } - - @Test - public void testRightPrefix() { - assertTrue(MapboxUtils.isAccessTokenValid("pk.XXX")); - assertTrue(MapboxUtils.isAccessTokenValid("sk.XXX")); - } - - @Test - public void testWrongPrefix() { - assertFalse(MapboxUtils.isAccessTokenValid("XXX")); - } + @Test + public void testEmpty() { + assertFalse(MapboxUtils.isAccessTokenValid(null)); + assertFalse(MapboxUtils.isAccessTokenValid("")); + } + + @Test + public void testRightPrefix() { + assertTrue(MapboxUtils.isAccessTokenValid("pk.XXX")); + assertTrue(MapboxUtils.isAccessTokenValid("sk.XXX")); + } + + @Test + public void testWrongPrefix() { + assertFalse(MapboxUtils.isAccessTokenValid("XXX")); + } } diff --git a/libjava/lib/src/test/java/com/mapbox/services/utils/PolylineUtilsTest.java b/libjava/lib/src/test/java/com/mapbox/services/utils/PolylineUtilsTest.java index ca7575dc1..1f47e4889 100644 --- a/libjava/lib/src/test/java/com/mapbox/services/utils/PolylineUtilsTest.java +++ b/libjava/lib/src/test/java/com/mapbox/services/utils/PolylineUtilsTest.java @@ -12,137 +12,134 @@ import static org.junit.Assert.*; -/** - * Created by antonio on 1/30/16. - */ public class PolylineUtilsTest { - private final static double DELTA = 1e-15; - - private Position[] points = { - Position.fromCoordinates(224.55, 250.15), Position.fromCoordinates(226.91, 244.19), Position.fromCoordinates(233.31, 241.45), Position.fromCoordinates(234.98, 236.06), - Position.fromCoordinates(244.21, 232.76), Position.fromCoordinates(262.59, 215.31), Position.fromCoordinates(267.76, 213.81), Position.fromCoordinates(273.57, 201.84), - Position.fromCoordinates(273.12, 192.16), Position.fromCoordinates(277.62, 189.03), Position.fromCoordinates(280.36, 181.41), Position.fromCoordinates(286.51, 177.74), - Position.fromCoordinates(292.41, 159.37), Position.fromCoordinates(296.91, 155.64), Position.fromCoordinates(314.95, 151.37), Position.fromCoordinates(319.75, 145.16), - Position.fromCoordinates(330.33, 137.57), Position.fromCoordinates(341.48, 139.96), Position.fromCoordinates(369.98, 137.89), Position.fromCoordinates(387.39, 142.51), - Position.fromCoordinates(391.28, 139.39), Position.fromCoordinates(409.52, 141.14), Position.fromCoordinates(414.82, 139.75), Position.fromCoordinates(427.72, 127.30), - Position.fromCoordinates(439.60, 119.74), Position.fromCoordinates(474.93, 107.87), Position.fromCoordinates(486.51, 106.75), Position.fromCoordinates(489.20, 109.45), - Position.fromCoordinates(493.79, 108.63), Position.fromCoordinates(504.74, 119.66), Position.fromCoordinates(512.96, 122.35), Position.fromCoordinates(518.63, 120.89), - Position.fromCoordinates(524.09, 126.88), Position.fromCoordinates(529.57, 127.86), Position.fromCoordinates(534.21, 140.93), Position.fromCoordinates(539.27, 147.24), - Position.fromCoordinates(567.69, 148.91), Position.fromCoordinates(575.25, 157.26), Position.fromCoordinates(580.62, 158.15), Position.fromCoordinates(601.53, 156.85), - Position.fromCoordinates(617.74, 159.86), Position.fromCoordinates(622.00, 167.04), Position.fromCoordinates(629.55, 194.60), Position.fromCoordinates(638.90, 195.61), - Position.fromCoordinates(641.26, 200.81), Position.fromCoordinates(651.77, 204.56), Position.fromCoordinates(671.55, 222.55), Position.fromCoordinates(683.68, 217.45), - Position.fromCoordinates(695.25, 219.15), Position.fromCoordinates(700.64, 217.98), Position.fromCoordinates(703.12, 214.36), Position.fromCoordinates(712.26, 215.87), - Position.fromCoordinates(721.49, 212.81), Position.fromCoordinates(727.81, 213.36), Position.fromCoordinates(729.98, 208.73), Position.fromCoordinates(735.32, 208.20), - Position.fromCoordinates(739.94, 204.77), Position.fromCoordinates(769.98, 208.42), Position.fromCoordinates(779.60, 216.87), Position.fromCoordinates(784.20, 218.16), - Position.fromCoordinates(800.24, 214.62), Position.fromCoordinates(810.53, 219.73), Position.fromCoordinates(817.19, 226.82), Position.fromCoordinates(820.77, 236.17), - Position.fromCoordinates(827.23, 236.16), Position.fromCoordinates(829.89, 239.89), Position.fromCoordinates(851.00, 248.94), Position.fromCoordinates(859.88, 255.49), - Position.fromCoordinates(865.21, 268.53), Position.fromCoordinates(857.95, 280.30), Position.fromCoordinates(865.48, 291.45), Position.fromCoordinates(866.81, 298.66), - Position.fromCoordinates(864.68, 302.71), Position.fromCoordinates(867.79, 306.17), Position.fromCoordinates(859.87, 311.37), Position.fromCoordinates(860.08, 314.35), - Position.fromCoordinates(858.29, 314.94), Position.fromCoordinates(858.10, 327.60), Position.fromCoordinates(854.54, 335.40), Position.fromCoordinates(860.92, 343.00), - Position.fromCoordinates(856.43, 350.15), Position.fromCoordinates(851.42, 352.96), Position.fromCoordinates(849.84, 359.59), Position.fromCoordinates(854.56, 365.53), - Position.fromCoordinates(849.74, 370.38), Position.fromCoordinates(844.09, 371.89), Position.fromCoordinates(844.75, 380.44), Position.fromCoordinates(841.52, 383.67), - Position.fromCoordinates(839.57, 390.40), Position.fromCoordinates(845.59, 399.05), Position.fromCoordinates(848.40, 407.55), Position.fromCoordinates(843.71, 411.30), - Position.fromCoordinates(844.09, 419.88), Position.fromCoordinates(839.51, 432.76), Position.fromCoordinates(841.33, 441.04), Position.fromCoordinates(847.62, 449.22), - Position.fromCoordinates(847.16, 458.44), Position.fromCoordinates(851.38, 462.79), Position.fromCoordinates(853.97, 471.15), Position.fromCoordinates(866.36, 480.77) - }; - - private Position[] simplified = { - Position.fromCoordinates(224.55, 250.15), Position.fromCoordinates(267.76, 213.81), Position.fromCoordinates(296.91, 155.64), Position.fromCoordinates(330.33, 137.57), - Position.fromCoordinates(409.52, 141.14), Position.fromCoordinates(439.60, 119.74), Position.fromCoordinates(486.51, 106.75), Position.fromCoordinates(529.57, 127.86), - Position.fromCoordinates(539.27, 147.24), Position.fromCoordinates(617.74, 159.86), Position.fromCoordinates(629.55, 194.60), Position.fromCoordinates(671.55, 222.55), - Position.fromCoordinates(727.81, 213.36), Position.fromCoordinates(739.94, 204.77), Position.fromCoordinates(769.98, 208.42), Position.fromCoordinates(779.60, 216.87), - Position.fromCoordinates(800.24, 214.62), Position.fromCoordinates(820.77, 236.17), Position.fromCoordinates(859.88, 255.49), Position.fromCoordinates(865.21, 268.53), - Position.fromCoordinates(857.95, 280.30), Position.fromCoordinates(867.79, 306.17), Position.fromCoordinates(859.87, 311.37), Position.fromCoordinates(854.54, 335.40), - Position.fromCoordinates(860.92, 343.00), Position.fromCoordinates(849.84, 359.59), Position.fromCoordinates(854.56, 365.53), Position.fromCoordinates(844.09, 371.89), - Position.fromCoordinates(839.57, 390.40), Position.fromCoordinates(848.40, 407.55), Position.fromCoordinates(839.51, 432.76), Position.fromCoordinates(853.97, 471.15), - Position.fromCoordinates(866.36, 480.77) - }; + private final static double DELTA = 1e-15; + + private Position[] points = { + Position.fromCoordinates(224.55, 250.15), Position.fromCoordinates(226.91, 244.19), Position.fromCoordinates(233.31, 241.45), Position.fromCoordinates(234.98, 236.06), + Position.fromCoordinates(244.21, 232.76), Position.fromCoordinates(262.59, 215.31), Position.fromCoordinates(267.76, 213.81), Position.fromCoordinates(273.57, 201.84), + Position.fromCoordinates(273.12, 192.16), Position.fromCoordinates(277.62, 189.03), Position.fromCoordinates(280.36, 181.41), Position.fromCoordinates(286.51, 177.74), + Position.fromCoordinates(292.41, 159.37), Position.fromCoordinates(296.91, 155.64), Position.fromCoordinates(314.95, 151.37), Position.fromCoordinates(319.75, 145.16), + Position.fromCoordinates(330.33, 137.57), Position.fromCoordinates(341.48, 139.96), Position.fromCoordinates(369.98, 137.89), Position.fromCoordinates(387.39, 142.51), + Position.fromCoordinates(391.28, 139.39), Position.fromCoordinates(409.52, 141.14), Position.fromCoordinates(414.82, 139.75), Position.fromCoordinates(427.72, 127.30), + Position.fromCoordinates(439.60, 119.74), Position.fromCoordinates(474.93, 107.87), Position.fromCoordinates(486.51, 106.75), Position.fromCoordinates(489.20, 109.45), + Position.fromCoordinates(493.79, 108.63), Position.fromCoordinates(504.74, 119.66), Position.fromCoordinates(512.96, 122.35), Position.fromCoordinates(518.63, 120.89), + Position.fromCoordinates(524.09, 126.88), Position.fromCoordinates(529.57, 127.86), Position.fromCoordinates(534.21, 140.93), Position.fromCoordinates(539.27, 147.24), + Position.fromCoordinates(567.69, 148.91), Position.fromCoordinates(575.25, 157.26), Position.fromCoordinates(580.62, 158.15), Position.fromCoordinates(601.53, 156.85), + Position.fromCoordinates(617.74, 159.86), Position.fromCoordinates(622.00, 167.04), Position.fromCoordinates(629.55, 194.60), Position.fromCoordinates(638.90, 195.61), + Position.fromCoordinates(641.26, 200.81), Position.fromCoordinates(651.77, 204.56), Position.fromCoordinates(671.55, 222.55), Position.fromCoordinates(683.68, 217.45), + Position.fromCoordinates(695.25, 219.15), Position.fromCoordinates(700.64, 217.98), Position.fromCoordinates(703.12, 214.36), Position.fromCoordinates(712.26, 215.87), + Position.fromCoordinates(721.49, 212.81), Position.fromCoordinates(727.81, 213.36), Position.fromCoordinates(729.98, 208.73), Position.fromCoordinates(735.32, 208.20), + Position.fromCoordinates(739.94, 204.77), Position.fromCoordinates(769.98, 208.42), Position.fromCoordinates(779.60, 216.87), Position.fromCoordinates(784.20, 218.16), + Position.fromCoordinates(800.24, 214.62), Position.fromCoordinates(810.53, 219.73), Position.fromCoordinates(817.19, 226.82), Position.fromCoordinates(820.77, 236.17), + Position.fromCoordinates(827.23, 236.16), Position.fromCoordinates(829.89, 239.89), Position.fromCoordinates(851.00, 248.94), Position.fromCoordinates(859.88, 255.49), + Position.fromCoordinates(865.21, 268.53), Position.fromCoordinates(857.95, 280.30), Position.fromCoordinates(865.48, 291.45), Position.fromCoordinates(866.81, 298.66), + Position.fromCoordinates(864.68, 302.71), Position.fromCoordinates(867.79, 306.17), Position.fromCoordinates(859.87, 311.37), Position.fromCoordinates(860.08, 314.35), + Position.fromCoordinates(858.29, 314.94), Position.fromCoordinates(858.10, 327.60), Position.fromCoordinates(854.54, 335.40), Position.fromCoordinates(860.92, 343.00), + Position.fromCoordinates(856.43, 350.15), Position.fromCoordinates(851.42, 352.96), Position.fromCoordinates(849.84, 359.59), Position.fromCoordinates(854.56, 365.53), + Position.fromCoordinates(849.74, 370.38), Position.fromCoordinates(844.09, 371.89), Position.fromCoordinates(844.75, 380.44), Position.fromCoordinates(841.52, 383.67), + Position.fromCoordinates(839.57, 390.40), Position.fromCoordinates(845.59, 399.05), Position.fromCoordinates(848.40, 407.55), Position.fromCoordinates(843.71, 411.30), + Position.fromCoordinates(844.09, 419.88), Position.fromCoordinates(839.51, 432.76), Position.fromCoordinates(841.33, 441.04), Position.fromCoordinates(847.62, 449.22), + Position.fromCoordinates(847.16, 458.44), Position.fromCoordinates(851.38, 462.79), Position.fromCoordinates(853.97, 471.15), Position.fromCoordinates(866.36, 480.77) + }; + + private Position[] simplified = { + Position.fromCoordinates(224.55, 250.15), Position.fromCoordinates(267.76, 213.81), Position.fromCoordinates(296.91, 155.64), Position.fromCoordinates(330.33, 137.57), + Position.fromCoordinates(409.52, 141.14), Position.fromCoordinates(439.60, 119.74), Position.fromCoordinates(486.51, 106.75), Position.fromCoordinates(529.57, 127.86), + Position.fromCoordinates(539.27, 147.24), Position.fromCoordinates(617.74, 159.86), Position.fromCoordinates(629.55, 194.60), Position.fromCoordinates(671.55, 222.55), + Position.fromCoordinates(727.81, 213.36), Position.fromCoordinates(739.94, 204.77), Position.fromCoordinates(769.98, 208.42), Position.fromCoordinates(779.60, 216.87), + Position.fromCoordinates(800.24, 214.62), Position.fromCoordinates(820.77, 236.17), Position.fromCoordinates(859.88, 255.49), Position.fromCoordinates(865.21, 268.53), + Position.fromCoordinates(857.95, 280.30), Position.fromCoordinates(867.79, 306.17), Position.fromCoordinates(859.87, 311.37), Position.fromCoordinates(854.54, 335.40), + Position.fromCoordinates(860.92, 343.00), Position.fromCoordinates(849.84, 359.59), Position.fromCoordinates(854.56, 365.53), Position.fromCoordinates(844.09, 371.89), + Position.fromCoordinates(839.57, 390.40), Position.fromCoordinates(848.40, 407.55), Position.fromCoordinates(839.51, 432.76), Position.fromCoordinates(853.97, 471.15), + Position.fromCoordinates(866.36, 480.77) + }; /* * Sample values from * https://developers.google.com/maps/documentation/utilities/polylinealgorithm */ - @Test - public void testDecode() { - // _p~iF~ps|U_ulLnnqC_mqNvxq`@ - List path = PolylineUtils.decode( - "_p~iF~ps|U_ulLnnqC_mqNvxq`@", Constants.GOOGLE_PRECISION); - - // (38.5, -120.2), (40.7, -120.95), (43.252, -126.453) - assertEquals(path.get(0).getLongitude(), -120.2, DELTA); - assertEquals(path.get(0).getLatitude(), 38.5, DELTA); - assertEquals(path.get(1).getLongitude(), -120.95, DELTA); - assertEquals(path.get(1).getLatitude(), 40.7, DELTA); - assertEquals(path.get(2).getLongitude(), -126.453, DELTA); - assertEquals(path.get(2).getLatitude(), 43.252, DELTA); - } - - @Test - public void testEncode() { - // (38.5, -120.2), (40.7, -120.95), (43.252, -126.453) - List path = new ArrayList<>(); - path.add(Position.fromCoordinates(-120.2, 38.5)); - path.add(Position.fromCoordinates(-120.95, 40.7)); - path.add(Position.fromCoordinates(-126.453, 43.252)); - - // _p~iF~ps|U_ulLnnqC_mqNvxq`@ - assertEquals(PolylineUtils.encode( - path, Constants.GOOGLE_PRECISION), "_p~iF~ps|U_ulLnnqC_mqNvxq`@"); - } + @Test + public void testDecode() { + // _p~iF~ps|U_ulLnnqC_mqNvxq`@ + List path = PolylineUtils.decode( + "_p~iF~ps|U_ulLnnqC_mqNvxq`@", Constants.GOOGLE_PRECISION); + + // (38.5, -120.2), (40.7, -120.95), (43.252, -126.453) + assertEquals(path.get(0).getLongitude(), -120.2, DELTA); + assertEquals(path.get(0).getLatitude(), 38.5, DELTA); + assertEquals(path.get(1).getLongitude(), -120.95, DELTA); + assertEquals(path.get(1).getLatitude(), 40.7, DELTA); + assertEquals(path.get(2).getLongitude(), -126.453, DELTA); + assertEquals(path.get(2).getLatitude(), 43.252, DELTA); + } + + @Test + public void testEncode() { + // (38.5, -120.2), (40.7, -120.95), (43.252, -126.453) + List path = new ArrayList<>(); + path.add(Position.fromCoordinates(-120.2, 38.5)); + path.add(Position.fromCoordinates(-120.95, 40.7)); + path.add(Position.fromCoordinates(-126.453, 43.252)); + + // _p~iF~ps|U_ulLnnqC_mqNvxq`@ + assertEquals(PolylineUtils.encode( + path, Constants.GOOGLE_PRECISION), "_p~iF~ps|U_ulLnnqC_mqNvxq`@"); + } /* * Sample route: * https://api.mapbox.com/v4/directions/mapbox.walking/-77.043410,38.909620;-77.036500,38.897700.json?access_token=&alternatives=false&steps=false&geometry=polyline */ - private final static String POLYLINE = "ujzeiApjj}qCfj@}Wnv@ka@tYaPrVmMb]kN`GiCxEgDdr@}[dCsAjXoMhNkGjM_Hts@k^dG_CrAi@|GoDzl@mWdH}GzA{Bl@iFAge@vF?zB?pB@rt@B`E?fF@fEGxB[nC}@xNaHp`@iREsG~EiA`JIxAUvAkBNeDo@qBpFuH|BkD|A{CnAaDdAaEn@uDXiDPkFAiG|H@x@sABkMdVEhFE|GCCko@|GChDv@"; - - private final static String LINESTRING = "{\"type\":\"LineString\",\"coordinates\":[[-77.043385,38.909627],[-77.042986,38.908935],[-77.042436,38.908047],[-77.042163,38.90762],[-77.041932,38.907242],[-77.041686,38.90676],[-77.041617,38.906631],[-77.041533,38.906522],[-77.04107,38.905703],[-77.041028,38.905636],[-77.040796,38.90523],[-77.040662,38.904985],[-77.040518,38.904755],[-77.040016,38.903912],[-77.039952,38.903781],[-77.039931,38.903739],[-77.039843,38.903596],[-77.039452,38.902862],[-77.039309,38.902715],[-77.039247,38.902669],[-77.03913,38.902646],[-77.038518,38.902647],[-77.038518,38.902523],[-77.038518,38.902461],[-77.038519,38.902404],[-77.038521,38.901546],[-77.038521,38.901449],[-77.038522,38.901333],[-77.038518,38.901233],[-77.038504,38.901172],[-77.038473,38.9011],[-77.038328,38.900847],[-77.038019,38.90031],[-77.037881,38.900313],[-77.037844,38.900201],[-77.037839,38.900024],[-77.037828,38.899979],[-77.037774,38.899935],[-77.037691,38.899927],[-77.037634,38.899951],[-77.037479,38.89983],[-77.037393,38.899767],[-77.037315,38.89972],[-77.037234,38.89968],[-77.037137,38.899645],[-77.037046,38.899621],[-77.036961,38.899608],[-77.036843,38.899599],[-77.03671,38.8996],[-77.036711,38.899441],[-77.036669,38.899412],[-77.036439,38.89941],[-77.036436,38.899039],[-77.036433,38.898922],[-77.036431,38.898779],[-77.035657,38.898781],[-77.035655,38.898638],[-77.035683,38.898553]]}"; - - @Test - public void testOsrmEncode() { - LineString path = LineString.fromJson(LINESTRING); - assertEquals(path.toPolyline(Constants.OSRM_PRECISION_V4), POLYLINE); - } - - @Test - public void testOsrmDecode() { - LineString path = LineString.fromPolyline(POLYLINE, Constants.OSRM_PRECISION_V4); - - // Check a first, middle, last elements - int middle = path.getCoordinates().size() / 2; - int last = path.getCoordinates().size() - 1; - assertEquals(path.getCoordinates().get(0).getLongitude(), -77.043385, DELTA); - assertEquals(path.getCoordinates().get(0).getLatitude(), 38.909627, DELTA); - assertEquals(path.getCoordinates().get(middle).getLongitude(), -77.038504, DELTA); - assertEquals(path.getCoordinates().get(middle).getLatitude(), 38.901172, DELTA); - assertEquals(path.getCoordinates().get(last).getLongitude(), -77.035683, DELTA); - assertEquals(path.getCoordinates().get(last).getLatitude(), 38.898553, DELTA); + private final static String POLYLINE = "ujzeiApjj}qCfj@}Wnv@ka@tYaPrVmMb]kN`GiCxEgDdr@}[dCsAjXoMhNkGjM_Hts@k^dG_CrAi@|GoDzl@mWdH}GzA{Bl@iFAge@vF?zB?pB@rt@B`E?fF@fEGxB[nC}@xNaHp`@iREsG~EiA`JIxAUvAkBNeDo@qBpFuH|BkD|A{CnAaDdAaEn@uDXiDPkFAiG|H@x@sABkMdVEhFE|GCCko@|GChDv@"; + + private final static String LINESTRING = "{\"type\":\"LineString\",\"coordinates\":[[-77.043385,38.909627],[-77.042986,38.908935],[-77.042436,38.908047],[-77.042163,38.90762],[-77.041932,38.907242],[-77.041686,38.90676],[-77.041617,38.906631],[-77.041533,38.906522],[-77.04107,38.905703],[-77.041028,38.905636],[-77.040796,38.90523],[-77.040662,38.904985],[-77.040518,38.904755],[-77.040016,38.903912],[-77.039952,38.903781],[-77.039931,38.903739],[-77.039843,38.903596],[-77.039452,38.902862],[-77.039309,38.902715],[-77.039247,38.902669],[-77.03913,38.902646],[-77.038518,38.902647],[-77.038518,38.902523],[-77.038518,38.902461],[-77.038519,38.902404],[-77.038521,38.901546],[-77.038521,38.901449],[-77.038522,38.901333],[-77.038518,38.901233],[-77.038504,38.901172],[-77.038473,38.9011],[-77.038328,38.900847],[-77.038019,38.90031],[-77.037881,38.900313],[-77.037844,38.900201],[-77.037839,38.900024],[-77.037828,38.899979],[-77.037774,38.899935],[-77.037691,38.899927],[-77.037634,38.899951],[-77.037479,38.89983],[-77.037393,38.899767],[-77.037315,38.89972],[-77.037234,38.89968],[-77.037137,38.899645],[-77.037046,38.899621],[-77.036961,38.899608],[-77.036843,38.899599],[-77.03671,38.8996],[-77.036711,38.899441],[-77.036669,38.899412],[-77.036439,38.89941],[-77.036436,38.899039],[-77.036433,38.898922],[-77.036431,38.898779],[-77.035657,38.898781],[-77.035655,38.898638],[-77.035683,38.898553]]}"; + + @Test + public void testOsrmEncode() { + LineString path = LineString.fromJson(LINESTRING); + assertEquals(path.toPolyline(Constants.OSRM_PRECISION_V4), POLYLINE); + } + + @Test + public void testOsrmDecode() { + LineString path = LineString.fromPolyline(POLYLINE, Constants.OSRM_PRECISION_V4); + + // Check a first, middle, last elements + int middle = path.getCoordinates().size() / 2; + int last = path.getCoordinates().size() - 1; + assertEquals(path.getCoordinates().get(0).getLongitude(), -77.043385, DELTA); + assertEquals(path.getCoordinates().get(0).getLatitude(), 38.909627, DELTA); + assertEquals(path.getCoordinates().get(middle).getLongitude(), -77.038504, DELTA); + assertEquals(path.getCoordinates().get(middle).getLatitude(), 38.901172, DELTA); + assertEquals(path.getCoordinates().get(last).getLongitude(), -77.035683, DELTA); + assertEquals(path.getCoordinates().get(last).getLatitude(), 38.898553, DELTA); + } + + @Test + public void testSimplify() { + // Simplifies points correctly with the given tolerance + Position[] result = PolylineUtils.simplify(points, 5); + assertEquals(simplified.length, result.length); + for (int i = 0; i < simplified.length; i++) { + assertEquals(simplified[i].getLongitude(), result[i].getLongitude(), DELTA); + assertEquals(simplified[i].getLatitude(), result[i].getLatitude(), DELTA); } - @Test - public void testSimplify() { - // Simplifies points correctly with the given tolerance - Position[] result = PolylineUtils.simplify(points, 5); - assertEquals(simplified.length, result.length); - for (int i = 0; i < simplified.length; i++) { - assertEquals(simplified[i].getLongitude(), result[i].getLongitude(), DELTA); - assertEquals(simplified[i].getLatitude(), result[i].getLatitude(), DELTA); - } - - // Just return the points if it has only one point - Position[] onePoint = {Position.fromCoordinates(1, 2)}; - result = PolylineUtils.simplify(onePoint); - assertEquals(result.length, 1); - assertEquals(result[0].getLongitude(), 1, DELTA); - assertEquals(result[0].getLatitude(), 2, DELTA); - - // Just return the points if it has no points - Position[] emptyList = {}; - result = PolylineUtils.simplify(emptyList); - assertEquals(result.length, 0); - } + // Just return the points if it has only one point + Position[] onePoint = {Position.fromCoordinates(1, 2)}; + result = PolylineUtils.simplify(onePoint); + assertEquals(result.length, 1); + assertEquals(result[0].getLongitude(), 1, DELTA); + assertEquals(result[0].getLatitude(), 2, DELTA); + + // Just return the points if it has no points + Position[] emptyList = {}; + result = PolylineUtils.simplify(emptyList); + assertEquals(result.length, 0); + } }