index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/constants/package-info.java
/** * Contains the constants used throughout the GeoJson classes. */ package com.nbmap.geojson.constants;
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/exception/GeoJsonException.java
package com.nbmap.geojson.exception; /** * A form of {@code Throwable} that indicates an issue occurred during a GeoJSON operation. * * @since 3.0.0 */ public class GeoJsonException extends RuntimeException { /** * A form of {@code Throwable} that indicates an issue occurred during a GeoJSON operation. * * @param message the detail message (which is saved for later retrieval by the * {@link #getMessage()} method) * @since 3.0.0 */ public GeoJsonException(String message) { super(message); } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/exception/package-info.java
/** * Contains a Runtime Exception specific to GeoJSON issues. * * @since 3.0.0 */ package com.nbmap.geojson.exception;
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/gson/BoundingBoxTypeAdapter.java
package com.nbmap.geojson.gson; import androidx.annotation.Keep; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.nbmap.geojson.BoundingBox; import com.nbmap.geojson.Point; import com.nbmap.geojson.exception.GeoJsonException; import com.nbmap.geojson.shifter.CoordinateShifterManager; import com.nbmap.geojson.utils.GeoJsonUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Adapter to read and write coordinates for BoundingBox class. * * @since 4.6.0 */ @Keep public class BoundingBoxTypeAdapter extends TypeAdapter<BoundingBox> { @Override public void write(JsonWriter out, BoundingBox value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginArray(); // Southwest Point point = value.southwest(); List<Double> unshiftedCoordinates = CoordinateShifterManager.getCoordinateShifter().unshiftPoint(point); out.value(GeoJsonUtils.trim(unshiftedCoordinates.get(0))); out.value(GeoJsonUtils.trim(unshiftedCoordinates.get(1))); if (point.hasAltitude()) { out.value(unshiftedCoordinates.get(2)); } // Northeast point = value.northeast(); unshiftedCoordinates = CoordinateShifterManager.getCoordinateShifter().unshiftPoint(point); out.value(GeoJsonUtils.trim(unshiftedCoordinates.get(0))); out.value(GeoJsonUtils.trim(unshiftedCoordinates.get(1))); if (point.hasAltitude()) { out.value(unshiftedCoordinates.get(2)); } out.endArray(); } @Override public BoundingBox read(JsonReader in) throws IOException { List<Double> rawCoordinates = new ArrayList<Double>(); in.beginArray(); while (in.hasNext()) { rawCoordinates.add(in.nextDouble()); } in.endArray(); if (rawCoordinates.size() == 6) { return BoundingBox.fromLngLats( rawCoordinates.get(0), rawCoordinates.get(1), rawCoordinates.get(2), rawCoordinates.get(3), rawCoordinates.get(4), rawCoordinates.get(5)); } if (rawCoordinates.size() == 4) { return BoundingBox.fromLngLats( rawCoordinates.get(0), rawCoordinates.get(1), rawCoordinates.get(2), rawCoordinates.get(3)); } else { throw new GeoJsonException("The value of the bbox member MUST be an array of length 2*n where" + " n is the number of dimensions represented in the contained geometries," + "with all axes of the most southwesterly point followed " + " by all axes of the more northeasterly point. The " + "axes order of a bbox follows the axes order of geometries."); } } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/gson/GeoJsonAdapterFactory.java
package com.nbmap.geojson.gson; import androidx.annotation.Keep; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.nbmap.geojson.BoundingBox; import com.nbmap.geojson.Feature; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.GeometryCollection; import com.nbmap.geojson.LineString; import com.nbmap.geojson.MultiLineString; import com.nbmap.geojson.MultiPoint; import com.nbmap.geojson.MultiPolygon; import com.nbmap.geojson.Point; import com.nbmap.geojson.Polygon; /** * A GeoJson type adapter factory for convenience for * serialization/deserialization. * * @since 3.0.0 */ @Keep public abstract class GeoJsonAdapterFactory implements TypeAdapterFactory { /** * Create a new instance of this GeoJson type adapter factory, this is passed into the Gson * Builder. * * @return a new GSON TypeAdapterFactory * @since 3.0.0 */ public static TypeAdapterFactory create() { return new GeoJsonAdapterFactoryIml(); } /** * GeoJsonAdapterFactory implementation. * * @since 3.0.0 */ public static final class GeoJsonAdapterFactoryIml extends GeoJsonAdapterFactory { @Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<?> rawType = type.getRawType(); if (BoundingBox.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) BoundingBox.typeAdapter(gson); } else if (Feature.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) Feature.typeAdapter(gson); } else if (FeatureCollection.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) FeatureCollection.typeAdapter(gson); } else if (GeometryCollection.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) GeometryCollection.typeAdapter(gson); } else if (LineString.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) LineString.typeAdapter(gson); } else if (MultiLineString.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) MultiLineString.typeAdapter(gson); } else if (MultiPoint.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) MultiPoint.typeAdapter(gson); } else if (MultiPolygon.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) MultiPolygon.typeAdapter(gson); } else if (Polygon.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) Polygon.typeAdapter(gson); } else if (Point.class.isAssignableFrom(rawType)) { return (TypeAdapter<T>) Point.typeAdapter(gson); } return null; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/gson/GeometryGeoJson.java
package com.nbmap.geojson.gson; import androidx.annotation.Keep; import androidx.annotation.NonNull; import com.google.gson.GsonBuilder; import com.nbmap.geojson.Geometry; import com.nbmap.geojson.GeometryAdapterFactory; /** * This is a utility class that helps create a Geometry instance from a JSON string. * @since 4.0.0 */ @Keep public class GeometryGeoJson { /** * Create a new instance of Geometry class by passing in a formatted valid JSON String. * * @param json a formatted valid JSON string defining a GeoJson Geometry * @return a new instance of Geometry class defined by the values passed inside * this static factory method * @since 4.0.0 */ public static Geometry fromJson(@NonNull String json) { GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create()); gson.registerTypeAdapterFactory(GeometryAdapterFactory.create()); return gson.create().fromJson(json, Geometry.class); } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/gson/package-info.java
/** * Contains the Nbmap Java GeoJson GSON helper classes which assist in parsing. */ package com.nbmap.geojson.gson;
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/internal
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/internal/typeadapters/RuntimeTypeAdapterFactory.java
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nbmap.geojson.internal.typeadapters; import androidx.annotation.Keep; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * Adapts values whose runtime type may differ from their declaration type. This * is necessary when a field's type is not the same type that GSON should create * when deserializing that field. For example, consider these types: * <pre> {@code * abstract class Shape { * int x; * int y; * } * class Circle extends Shape { * int radius; * } * class Rectangle extends Shape { * int width; * int height; * } * class Diamond extends Shape { * int width; * int height; * } * class Drawing { * Shape bottomShape; * Shape topShape; * } * }</pre> * <p>Without additional type information, the serialized JSON is ambiguous. Is * the bottom shape in this drawing a rectangle or a diamond? <pre> {@code * { * "bottomShape": { * "width": 10, * "height": 5, * "x": 0, * "y": 0 * }, * "topShape": { * "radius": 2, * "x": 4, * "y": 1 * } * }}</pre> * This class addresses this problem by adding type information to the * serialized JSON and honoring that type information when the JSON is * deserialized: <pre> {@code * { * "bottomShape": { * "type": "Diamond", * "width": 10, * "height": 5, * "x": 0, * "y": 0 * }, * "topShape": { * "type": "Circle", * "radius": 2, * "x": 4, * "y": 1 * } * }}</pre> * Both the type field name ({@code "type"}) and the type labels ({@code * "Rectangle"}) are configurable. * * <h3>Registering Types</h3> * Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field * name to the {@link #of} factory method. If you don't supply an explicit type * field name, {@code "type"} will be used. <pre> {@code * RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory * = RuntimeTypeAdapterFactory.of(Shape.class, "type"); * }</pre> * Next register all of your subtypes. Every subtype must be explicitly * registered. This protects your application from injection attacks. If you * don't supply an explicit type label, the type's simple name will be used. * <pre> {@code * shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle"); * shapeAdapterFactory.registerSubtype(Circle.class, "Circle"); * shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond"); * }</pre> * Finally, register the type adapter factory in your application's GSON builder: * <pre> {@code * Gson gson = new GsonBuilder() * .registerTypeAdapterFactory(shapeAdapterFactory) * .create(); * }</pre> * Like {@code GsonBuilder}, this API supports chaining: <pre> {@code * RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = * RuntimeTypeAdapterFactory.of(Shape.class) * .registerSubtype(Rectangle.class) * .registerSubtype(Circle.class) * .registerSubtype(Diamond.class); * }</pre> * * @param <T> base type for this factory * @since 4.6.0 */ @Keep public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory { private final Class<?> baseType; private final String typeFieldName; private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>(); private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>(); private final boolean maintainType; private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName, boolean maintainType) { if (typeFieldName == null || baseType == null) { throw new NullPointerException(); } this.baseType = baseType; this.typeFieldName = typeFieldName; this.maintainType = maintainType; } /** * Creates a new runtime type adapter using for {@code baseType} using {@code * typeFieldName} as the type field name. Type field names are case sensitive. * {@code maintainType} flag decide if the type will be stored in pojo or not. * * @param <T> base type * @param baseType class of base type * @param typeFieldName field name used to distinguish subtypes * @param maintainType true if the type will be stored in pojo, false - otherwise */ public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName, boolean maintainType) { return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, maintainType); } /** * Creates a new runtime type adapter using for {@code baseType} using {@code * typeFieldName} as the type field name. Type field names are case sensitive. * * @param <T> base type * @param baseType class of base type * @param typeFieldName field name used to distinguish subtypes */ public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) { return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, false); } /** * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as * the type field name. * * @param <T> base type * @param baseType class of base type */ public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) { return new RuntimeTypeAdapterFactory<T>(baseType, "type", false); } /** * Registers {@code type} identified by {@code label}. Labels are case * sensitive. * * @param type class of subtype of base type * @param label string value for field that distinguishes subtypes * @throws IllegalArgumentException if either {@code type} or {@code label} * have already been registered on this type adapter. */ public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) { if (type == null || label == null) { throw new NullPointerException(); } if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) { throw new IllegalArgumentException("types and labels must be unique"); } labelToSubtype.put(label, type); subtypeToLabel.put(type, label); return this; } /** * Registers {@code type} identified by its {@link Class#getSimpleName simple * name}. Labels are case sensitive. * * @param type type name * @throws IllegalArgumentException if either {@code type} or its simple name * have already been registered on this type adapter. */ public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) { return registerSubtype(type, type.getSimpleName()); } @Override public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; } final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement; if (maintainType) { labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); } else { labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); } if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException("cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (maintainType) { Streams.write(jsonObject, out); return; } JsonObject clone = new JsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } String label = subtypeToLabel.get(srcType); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/internal
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/internal/typeadapters/package-info.java
/** * Contains Google gson type adapters. */ package com.google.gson.typeadapters;
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/shifter/CoordinateShifter.java
package com.nbmap.geojson.shifter; import com.nbmap.geojson.Point; import java.util.List; /** * ShifterManager allows the movement of all Point objects according to a custom algorithm. * Once set, it will be applied to all Point objects created through this method. * * @since 4.2.0 */ public interface CoordinateShifter { /** * Shifted coordinate values according to its algorithm. * * @param lon unshifted longitude * @param lat unshifted latitude * @return shifted longitude, shifted latitude in the form of a List of Double values * @since 4.2.0 */ List<Double> shiftLonLat(double lon, double lat); /** * Shifted coordinate values according to its algorithm. * * @param lon unshifted longitude * @param lat unshifted latitude * @param altitude unshifted altitude * @return shifted longitude, shifted latitude, shifted altitude in the form of a * List of Double values * @since 4.2.0 */ List<Double> shiftLonLatAlt(double lon, double lat, double altitude); /** * Unshifted coordinate values according to its algorithm. * * @param shiftedPoint shifted point * @return unshifted longitude, shifted latitude, * and altitude (if present) in the form of List of Double * @since 4.2.0 */ List<Double> unshiftPoint(Point shiftedPoint); /** * Unshifted coordinate values according to its algorithm. * * @param shiftedCoordinates shifted point * @return unshifted longitude, shifted latitude, * and altitude (if present) in the form of List of Double * @since 4.2.0 */ List<Double> unshiftPoint(List<Double> shiftedCoordinates); }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/shifter/CoordinateShifterManager.java
package com.nbmap.geojson.shifter; import com.nbmap.geojson.Point; import java.util.Arrays; import java.util.List; /** * CoordinateShifterManager keeps track of currently set CoordinateShifter. * * @since 4.2.0 */ public final class CoordinateShifterManager { private static final CoordinateShifter DEFAULT = new CoordinateShifter() { @Override public List<Double> shiftLonLat(double lon, double lat) { return Arrays.asList(lon, lat); } @Override public List<Double> shiftLonLatAlt(double lon, double lat, double alt) { return Double.isNaN(alt) ? Arrays.asList(lon, lat) : Arrays.asList(lon, lat, alt); } @Override public List<Double> unshiftPoint(Point point) { return point.coordinates(); } @Override public List<Double> unshiftPoint(List<Double> coordinates) { return coordinates; } }; private static volatile CoordinateShifter coordinateShifter = DEFAULT; /** * Currently set CoordinateShifterManager. * * @return Currently set CoordinateShifterManager * @since 4.2.0 */ public static CoordinateShifter getCoordinateShifter() { return coordinateShifter; } /** * Sets CoordinateShifterManager. * * @param coordinateShifter CoordinateShifterManager to be set * @since 4.2.0 */ public static void setCoordinateShifter(CoordinateShifter coordinateShifter) { CoordinateShifterManager.coordinateShifter = coordinateShifter == null ? DEFAULT : coordinateShifter; } /** * Check whether the current shifter is the default one. * @return true if using default shifter. */ public static boolean isUsingDefaultShifter() { return coordinateShifter == DEFAULT; } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/shifter/package-info.java
/** * Contains Utility for universally applying a shifting algorithm to all Geometry types. */ package com.nbmap.geojson.shifter;
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/utils/GeoJsonUtils.java
package com.nbmap.geojson.utils; /** * GeoJson utils class contains method that can be used throughout geojson package. * * @since 4.3.0 */ public class GeoJsonUtils { private static double ROUND_PRECISION = 10000000.0; private static long MAX_DOUBLE_TO_ROUND = (long) (Long.MAX_VALUE / ROUND_PRECISION); /** * Trims a double value to have only 7 digits after period. * * @param value to be trimed * @return trimmed value */ public static double trim(double value) { if (value > MAX_DOUBLE_TO_ROUND || value < -MAX_DOUBLE_TO_ROUND) { return value; } return Math.round(value * ROUND_PRECISION) / ROUND_PRECISION; } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/utils/PolylineUtils.java
package com.nbmap.geojson.utils; import androidx.annotation.NonNull; import com.nbmap.geojson.Point; import java.util.ArrayList; import java.util.List; /** * Polyline utils class contains method that can decode/encode a polyline, simplify a line, and * more. * * @since 1.0.0 */ public final class PolylineUtils { private PolylineUtils() { // Prevent initialization of this class } // 1 by default (in the same metric as the point coordinates) private static final double SIMPLIFY_DEFAULT_TOLERANCE = 1; // False by default (excludes distance-based preprocessing step which leads to highest quality // simplification but runs slower) private static final boolean SIMPLIFY_DEFAULT_HIGHEST_QUALITY = false; /** * Decodes an encoded path string into a sequence of {@link Point}. * * @param encodedPath a String representing an encoded path string * @param precision OSRMv4 uses 6, OSRMv5 and Google uses 5 * @return list of {@link Point} making up the line * @see <a href="https://github.com/nbmap/polyline/blob/master/src/polyline.js">Part of algorithm came from this source</a> * @see <a href="https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/PolyUtil.java">Part of algorithm came from this source.</a> * @since 1.0.0 */ @NonNull public static List<Point> decode(@NonNull final String encodedPath, int precision) { int len = encodedPath.length(); // OSRM uses precision=6, the default Polyline spec divides by 1E5, capping at precision=5 double factor = Math.pow(10, precision); // For speed we preallocate to an upper bound on the final length, then // truncate the array before returning. final List<Point> path = new ArrayList<>(); int index = 0; int lat = 0; int lng = 0; while (index < len) { int result = 1; int shift = 0; int temp; do { temp = encodedPath.charAt(index++) - 63 - 1; result += temp << shift; shift += 5; } while (temp >= 0x1f); lat += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); result = 1; shift = 0; do { temp = encodedPath.charAt(index++) - 63 - 1; result += temp << shift; shift += 5; } while (temp >= 0x1f); lng += (result & 1) != 0 ? ~(result >> 1) : (result >> 1); path.add(Point.fromLngLat(lng / factor, lat / factor)); } return path; } /** * Encodes a sequence of Points into an encoded path string. * * @param path list of {@link Point}s making up the line * @param precision OSRMv4 uses 6, OSRMv5 and Google uses 5 * @return a String representing a path string * @since 1.0.0 */ @NonNull public static String encode(@NonNull final List<Point> path, int precision) { long lastLat = 0; long lastLng = 0; final StringBuilder result = new StringBuilder(); // OSRM uses precision=6, the default Polyline spec divides by 1E5, capping at precision=5 double factor = Math.pow(10, precision); for (final Point point : path) { long lat = Math.round(point.latitude() * factor); long lng = Math.round(point.longitude() * factor); long varLat = lat - lastLat; long varLng = lng - lastLng; encode(varLat, result); encode(varLng, result); lastLat = lat; lastLng = lng; } return result.toString(); } private static void encode(long variable, StringBuilder result) { variable = variable < 0 ? ~(variable << 1) : variable << 1; while (variable >= 0x20) { result.append(Character.toChars((int) ((0x20 | (variable & 0x1f)) + 63))); variable >>= 5; } result.append(Character.toChars((int) (variable + 63))); } /* * Polyline simplification method. It's a direct port of simplify.js to Java. * See: https://github.com/mourner/simplify-js/blob/master/simplify.js */ /** * Reduces the number of points in a polyline while retaining its shape, giving a performance * boost when processing it and also reducing visual noise. * * @param points an array of points * @return an array of simplified points * @see <a href="http://mourner.github.io/simplify-js/">JavaScript implementation</a> * @since 1.2.0 */ @NonNull public static List<Point> simplify(@NonNull List<Point> points) { return simplify(points, SIMPLIFY_DEFAULT_TOLERANCE, SIMPLIFY_DEFAULT_HIGHEST_QUALITY); } /** * Reduces the number of points in a polyline while retaining its shape, giving a performance * boost when processing it and also reducing visual noise. * * @param points an array of points * @param tolerance affects the amount of simplification (in the same metric as the point * coordinates) * @return an array of simplified points * @see <a href="http://mourner.github.io/simplify-js/">JavaScript implementation</a> * @since 1.2.0 */ @NonNull public static List<Point> simplify(@NonNull List<Point> points, double tolerance) { return simplify(points, tolerance, SIMPLIFY_DEFAULT_HIGHEST_QUALITY); } /** * Reduces the number of points in a polyline while retaining its shape, giving a performance * boost when processing it and also reducing visual noise. * * @param points an array of points * @param highestQuality excludes distance-based preprocessing step which leads to highest quality * simplification * @return an array of simplified points * @see <a href="http://mourner.github.io/simplify-js/">JavaScript implementation</a> * @since 1.2.0 */ @NonNull public static List<Point> simplify(@NonNull List<Point> points, boolean highestQuality) { return simplify(points, SIMPLIFY_DEFAULT_TOLERANCE, highestQuality); } /** * Reduces the number of points in a polyline while retaining its shape, giving a performance * boost when processing it and also reducing visual noise. * * @param points an array of points * @param tolerance affects the amount of simplification (in the same metric as the point * coordinates) * @param highestQuality excludes distance-based preprocessing step which leads to highest quality * simplification * @return an array of simplified points * @see <a href="http://mourner.github.io/simplify-js/">JavaScript implementation</a> * @since 1.2.0 */ @NonNull public static List<Point> simplify(@NonNull List<Point> points, double tolerance, boolean highestQuality) { if (points.size() <= 2) { return points; } double sqTolerance = tolerance * tolerance; points = highestQuality ? points : simplifyRadialDist(points, sqTolerance); points = simplifyDouglasPeucker(points, sqTolerance); return points; } /** * Square distance between 2 points. * * @param p1 first {@link Point} * @param p2 second Point * @return square of the distance between two input points */ private static double getSqDist(Point p1, Point p2) { double dx = p1.longitude() - p2.longitude(); double dy = p1.latitude() - p2.latitude(); return dx * dx + dy * dy; } /** * Square distance from a point to a segment. * * @param point {@link Point} whose distance from segment needs to be determined * @param p1,p2 points defining the segment * @return square of the distance between first input point and segment defined by * other two input points */ private static double getSqSegDist(Point point, Point p1, Point p2) { double horizontal = p1.longitude(); double vertical = p1.latitude(); double diffHorizontal = p2.longitude() - horizontal; double diffVertical = p2.latitude() - vertical; if (diffHorizontal != 0 || diffVertical != 0) { double total = ((point.longitude() - horizontal) * diffHorizontal + (point.latitude() - vertical) * diffVertical) / (diffHorizontal * diffHorizontal + diffVertical * diffVertical); if (total > 1) { horizontal = p2.longitude(); vertical = p2.latitude(); } else if (total > 0) { horizontal += diffHorizontal * total; vertical += diffVertical * total; } } diffHorizontal = point.longitude() - horizontal; diffVertical = point.latitude() - vertical; return diffHorizontal * diffHorizontal + diffVertical * diffVertical; } /** * Basic distance-based simplification. * * @param points a list of points to be simplified * @param sqTolerance square of amount of simplification * @return a list of simplified points */ private static List<Point> simplifyRadialDist(List<Point> points, double sqTolerance) { Point prevPoint = points.get(0); ArrayList<Point> newPoints = new ArrayList<>(); newPoints.add(prevPoint); Point point = null; for (int i = 1, len = points.size(); i < len; i++) { point = points.get(i); if (getSqDist(point, prevPoint) > sqTolerance) { newPoints.add(point); prevPoint = point; } } if (!prevPoint.equals(point)) { newPoints.add(point); } return newPoints; } private static List<Point> simplifyDpStep( List<Point> points, int first, int last, double sqTolerance, List<Point> simplified) { double maxSqDist = sqTolerance; int index = 0; ArrayList<Point> stepList = new ArrayList<>(); for (int i = first + 1; i < last; i++) { double sqDist = getSqSegDist(points.get(i), points.get(first), points.get(last)); if (sqDist > maxSqDist) { index = i; maxSqDist = sqDist; } } if (maxSqDist > sqTolerance) { if (index - first > 1) { stepList.addAll(simplifyDpStep(points, first, index, sqTolerance, simplified)); } stepList.add(points.get(index)); if (last - index > 1) { stepList.addAll(simplifyDpStep(points, index, last, sqTolerance, simplified)); } } return stepList; } /** * Simplification using Ramer-Douglas-Peucker algorithm. * * @param points a list of points to be simplified * @param sqTolerance square of amount of simplification * @return a list of simplified points */ private static List<Point> simplifyDouglasPeucker(List<Point> points, double sqTolerance) { int last = points.size() - 1; ArrayList<Point> simplified = new ArrayList<>(); simplified.add(points.get(0)); simplified.addAll(simplifyDpStep(points, 0, last, sqTolerance, simplified)); simplified.add(points.get(last)); return simplified; } }
0
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson
java-sources/ai/nextbillion/nbmap-sdk-geojson/0.1.2/com/nbmap/geojson/utils/package-info.java
/** * Contains Utilities useful for GeoJson translations and formations. */ package com.nbmap.geojson.utils;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directions
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directions/v5/DirectionsResponseFactory.java
package com.nbmap.api.directions.v5; import com.nbmap.api.directions.v5.models.DirectionsResponse; import com.nbmap.api.directions.v5.models.DirectionsRoute; import com.nbmap.api.directions.v5.models.RouteOptions; import com.nbmap.api.directions.v5.utils.ParseUtils; import java.util.ArrayList; import java.util.List; import retrofit2.Response; /** * @since 4.4.0 */ class DirectionsResponseFactory { private final NbmapDirections nbmapDirections; DirectionsResponseFactory(NbmapDirections nbmapDirections) { this.nbmapDirections = nbmapDirections; } Response<DirectionsResponse> generate(Response<DirectionsResponse> response) { if (isNotSuccessful(response)) { return response; } else { return Response.success( response .body() .toBuilder() .routes(generateRouteOptions(response)) .build(), new okhttp3.Response.Builder() .code(200) .message("OK") .protocol(response.raw().protocol()) .headers(response.headers()) .request(response.raw().request()) .build()); } } private boolean isNotSuccessful(Response<DirectionsResponse> response) { return !response.isSuccessful() || response.body() == null || response.body().routes().isEmpty(); } private List<DirectionsRoute> generateRouteOptions(Response<DirectionsResponse> response) { List<DirectionsRoute> routes = response.body().routes(); List<DirectionsRoute> modifiedRoutes = new ArrayList<>(); for (DirectionsRoute route : routes) { modifiedRoutes.add(route.toBuilder().routeOptions( RouteOptions.builder() .profile(nbmapDirections.profile()) .coordinates(nbmapDirections.coordinates()) .waypointIndicesList(ParseUtils.parseToIntegers(nbmapDirections.waypointIndices())) .waypointNamesList(ParseUtils.parseToStrings(nbmapDirections.waypointNames())) .waypointTargetsList(ParseUtils.parseToPoints(nbmapDirections.waypointTargets())) .continueStraight(nbmapDirections.continueStraight()) .annotationsList(ParseUtils.parseToStrings(nbmapDirections.annotation())) .approachesList(ParseUtils.parseToStrings(nbmapDirections.approaches())) .bearingsList(ParseUtils.parseToListOfListOfDoubles(nbmapDirections.bearing())) .alternatives(nbmapDirections.alternatives()) .language(nbmapDirections.language()) .radiusesList(ParseUtils.parseToDoubles(nbmapDirections.radius())) .user(nbmapDirections.user()) .voiceInstructions(nbmapDirections.voiceInstructions()) .bannerInstructions(nbmapDirections.bannerInstructions()) .roundaboutExits(nbmapDirections.roundaboutExits()) .geometries(nbmapDirections.geometries()) .overview(nbmapDirections.overview()) .steps(nbmapDirections.steps()) .exclude(nbmapDirections.exclude()) .voiceUnits(nbmapDirections.voiceUnits()) .accessToken(nbmapDirections.accessToken()) .requestUuid(response.body().uuid()) .baseUrl(nbmapDirections.baseUrl()) .walkingOptions(nbmapDirections.walkingOptions()) .snappingClosures(nbmapDirections.snappingClosures()) .build() ).build()); } return modifiedRoutes; } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directions
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directions/v5/DirectionsService.java
package com.nbmap.api.directions.v5; import com.nbmap.api.directions.v5.models.DirectionsResponse; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the directions service (v5). * * @since 1.0.0 */ public interface DirectionsService { /** * Constructs the html get call using the information passed in through the * {@link NbmapDirections.Builder}. * * @param userAgent the user agent * @param user the user * @param profile the profile directions should use * @param coordinates the coordinates the route should follow * @param accessToken Nbmap access token * @param alternatives define whether you want to receive 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 bearings used to filter the road segment the waypoint will be placed on by * direction and dictates the angle of approach * @param continueStraight define whether the route should continue straight even if the * route will be slower * @param annotations an annotations object that contains additional details about each * line segment along the route geometry. Each entry in an * annotations field corresponds to a coordinate along the route * geometry * @param language language of returned turn-by-turn text instructions * @param roundaboutExits Add extra step when roundabouts occur with additional information * for the user * @param voiceInstructions request that the response contain voice instruction information, * useful for navigation * @param bannerInstructions request that the response contain banner instruction information, * useful for navigation * @param voiceUnits voice units * @param exclude exclude tolls, motorways or more along your route * @param approaches which side of the road to approach a waypoint * @param waypointIndices which input coordinates should be treated as waypoints/separate legs * Note: coordinate indices not added here act as silent waypoints * @param waypointNames custom names for waypoints used for the arrival instruction * @param waypointTargets list of coordinate pairs for drop-off locations * @param enableRefresh whether the routes should be refreshable * @param walkingSpeed walking speed * @param walkwayBias a factor that modifies the cost when encountering roads or paths * that do not allow vehicles and are set aside for pedestrian use * @param alleyBias a factor that modifies the cost when alleys are encountered * @param snappingClosures a list of booleans affecting snapping of waypoint locations to road * segments * @return the {@link DirectionsResponse} in a Call wrapper * @since 1.0.0 */ @GET("directions/v5/{user}/{profile}/{coordinates}") Call<DirectionsResponse> getCall( @Header("User-Agent") String userAgent, @Path("user") String user, @Path("profile") String profile, @Path("coordinates") String coordinates, @Query("key") String accessToken, @Query("alternatives") Boolean alternatives, @Query("geometries") String geometries, @Query("overview") String overview, @Query("radiuses") String radiuses, @Query("steps") Boolean steps, @Query("bearings") String bearings, @Query("continue_straight") Boolean continueStraight, @Query("annotations") String annotations, @Query("language") String language, @Query("roundabout_exits") Boolean roundaboutExits, @Query("voice_instructions") Boolean voiceInstructions, @Query("banner_instructions") Boolean bannerInstructions, @Query("voice_units") String voiceUnits, @Query("exclude") String exclude, @Query("approaches") String approaches, @Query("waypoints") String waypointIndices, @Query("waypoint_names") String waypointNames, @Query("waypoint_targets") String waypointTargets, @Query("enable_refresh") Boolean enableRefresh, @Query("walking_speed") Double walkingSpeed, @Query("walkway_bias") Double walkwayBias, @Query("alley_bias") Double alleyBias, @Query("snapping_include_closures") String snappingClosures ); /** * Constructs the post html call using the information passed in through the * {@link NbmapDirections.Builder}. * * @param userAgent the user agent * @param user the user * @param profile the profile directions should use * @param coordinates the coordinates the route should follow * @param accessToken Nbmap access token * @param alternatives define whether you want to receive 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 bearings used to filter the road segment the waypoint will be placed on by * direction and dictates the angle of approach * @param continueStraight define whether the route should continue straight even if the * route will be slower * @param annotations an annotations object that contains additional details about each * line segment along the route geometry. Each entry in an * annotations field corresponds to a coordinate along the route * geometry * @param language language of returned turn-by-turn text instructions * @param roundaboutExits Add extra step when roundabouts occur with additional information * for the user * @param voiceInstructions request that the response contain voice instruction information, * useful for navigation * @param bannerInstructions request that the response contain banner instruction information, * useful for navigation * @param voiceUnits voice units * @param exclude exclude tolls, motorways or more along your route * @param approaches which side of the road to approach a waypoint * @param waypointIndices which input coordinates should be treated as waypoints/separate legs * Note: coordinate indices not added here act as silent waypoints * @param waypointNames custom names for waypoints used for the arrival instruction * @param waypointTargets list of coordinate pairs for drop-off locations * @param enableRefresh whether the routes should be refreshable * @param walkingSpeed walking speed * @param walkwayBias a factor that modifies the cost when encountering roads or paths * that do not allow vehicles and are set aside for pedestrian use * @param alleyBias a factor that modifies the cost when alleys are encountered * @param snappingClosures a list of booleans affecting snapping of waypoint locations to road * segments * @return the {@link DirectionsResponse} in a Call wrapper * @since 4.6.0 */ @FormUrlEncoded @POST("directions/v5/{user}/{profile}") Call<DirectionsResponse> postCall( @Header("User-Agent") String userAgent, @Path("user") String user, @Path("profile") String profile, @Field("coordinates") String coordinates, @Query("key") String accessToken, @Field("alternatives") Boolean alternatives, @Field("geometries") String geometries, @Field("overview") String overview, @Field("radiuses") String radiuses, @Field("steps") Boolean steps, @Field("bearings") String bearings, @Field("continue_straight") Boolean continueStraight, @Field("annotations") String annotations, @Field("language") String language, @Field("roundabout_exits") Boolean roundaboutExits, @Field("voice_instructions") Boolean voiceInstructions, @Field("banner_instructions") Boolean bannerInstructions, @Field("voice_units") String voiceUnits, @Field("exclude") String exclude, @Field("approaches") String approaches, @Field("waypoints") String waypointIndices, @Field("waypoint_names") String waypointNames, @Field("waypoint_targets") String waypointTargets, @Field("enable_refresh") Boolean enableRefresh, @Field("walking_speed") Double walkingSpeed, @Field("walkway_bias") Double walkwayBias, @Field("alley_bias") Double alleyBias, @Field("snapping_include_closures") String snappingClosures ); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directions
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directions/v5/NbmapDirections.java
package com.nbmap.api.directions.v5; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.api.directions.v5.DirectionsCriteria.AnnotationCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.ExcludeCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.GeometriesCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.OverviewCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.ProfileCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.VoiceUnitCriteria; import com.nbmap.api.directions.v5.models.DirectionsResponse; import com.nbmap.api.directions.v5.models.RouteLeg; import com.nbmap.api.directions.v5.utils.FormatUtils; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.ApiCallHelper; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.geojson.Point; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import okhttp3.EventListener; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * The Directions API allows the calculation of routes between coordinates. The fastest route can be * returned with geometries, turn-by-turn instructions, and much more. The Nbmap Directions API * supports routing for driving cars (including live traffic), riding bicycles and walking. * Requested routes can include as much as 25 coordinates anywhere on earth (except the traffic * profile). * <p> * Requesting a route at a bare minimal must include, a Nbmap access token, destination, and an * origin. * </p> * * @see <a href="https://www.nbmap.com/android-docs/java-sdk/overview/directions/">Android * Directions documentation</a> * @see <a href="https://www.nbmap.com/api-documentation/navigation/#directions">Directions API * documentation</a> * @since 1.0.0 */ @AutoValue public abstract class NbmapDirections extends NbmapService<DirectionsResponse, DirectionsService> { protected NbmapDirections() { super(DirectionsService.class); } @Override protected Call<DirectionsResponse> initializeCall() { if (usePostMethod() == null) { return callForUrlLength(); } if (usePostMethod()) { return post(); } return get(); } private Call<DirectionsResponse> callForUrlLength() { Call<DirectionsResponse> get = get(); if (get.request().url().toString().length() < MAX_URL_SIZE) { return get; } return post(); } private Call<DirectionsResponse> get() { return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), user(), profile(), FormatUtils.formatCoordinates(coordinates()), accessToken(), alternatives(), geometries(), overview(), radius(), steps(), bearing(), continueStraight(), annotation(), language(), roundaboutExits(), voiceInstructions(), bannerInstructions(), voiceUnits(), exclude(), approaches(), waypointIndices(), waypointNames(), waypointTargets(), enableRefresh(), walkingSpeed(), walkwayBias(), alleyBias(), snappingClosures() ); } private Call<DirectionsResponse> post() { return getService().postCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), user(), profile(), FormatUtils.formatCoordinates(coordinates()), accessToken(), alternatives(), geometries(), overview(), radius(), steps(), bearing(), continueStraight(), annotation(), language(), roundaboutExits(), voiceInstructions(), bannerInstructions(), voiceUnits(), exclude(), approaches(), waypointIndices(), waypointNames(), waypointTargets(), enableRefresh(), walkingSpeed(), walkwayBias(), alleyBias(), snappingClosures() ); } @Override protected GsonBuilder getGsonBuilder() { return super.getGsonBuilder() .registerTypeAdapterFactory(DirectionsAdapterFactory.create()); } /** * Wrapper method for Retrofits {@link Call#execute()} call returning a response specific to the * Directions API. * * @return the Directions v5 response once the call completes successfully * @throws IOException Signals that an I/O exception of some sort has occurred * @since 1.0.0 */ @Override public Response<DirectionsResponse> executeCall() throws IOException { Response<DirectionsResponse> response = super.executeCall(); DirectionsResponseFactory factory = new DirectionsResponseFactory(this); return factory.generate(response); } /** * Wrapper method for Retrofits {@link Call#enqueue(Callback)} call returning a response specific * to the Directions API. Use this method to make a directions request on the Main Thread. * * @param callback a {@link Callback} which is used once the {@link DirectionsResponse} is * created. * @since 1.0.0 */ @Override public void enqueueCall(final Callback<DirectionsResponse> callback) { getCall().enqueue(new Callback<DirectionsResponse>() { @Override public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) { DirectionsResponseFactory factory = new DirectionsResponseFactory(NbmapDirections.this); Response<DirectionsResponse> generatedResponse = factory.generate(response); callback.onResponse(call, generatedResponse); } @Override public void onFailure(Call<DirectionsResponse> call, Throwable throwable) { callback.onFailure(call, throwable); } }); } @Override protected synchronized OkHttpClient getOkHttpClient() { if (okHttpClient == null) { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); if (isEnableDebug()) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BASIC); httpClient.addInterceptor(logging); } Interceptor interceptor = interceptor(); if (interceptor != null) { httpClient.addInterceptor(interceptor); } Interceptor networkInterceptor = networkInterceptor(); if (networkInterceptor != null) { httpClient.addNetworkInterceptor(networkInterceptor); } EventListener eventListener = eventListener(); if (eventListener != null) { httpClient.eventListener(eventListener); } okHttpClient = httpClient.build(); } return okHttpClient; } @NonNull abstract String user(); @NonNull abstract String profile(); @NonNull abstract List<Point> coordinates(); @NonNull @Override protected abstract String baseUrl(); @NonNull abstract String accessToken(); @Nullable abstract Boolean alternatives(); @Nullable abstract String geometries(); @Nullable abstract String overview(); @Nullable abstract String radius(); @Nullable abstract String bearing(); @Nullable abstract Boolean steps(); @Nullable abstract Boolean continueStraight(); @Nullable abstract String annotation(); @Nullable abstract String language(); @Nullable abstract Boolean roundaboutExits(); @Nullable abstract String clientAppName(); @Nullable abstract Boolean voiceInstructions(); @Nullable abstract Boolean bannerInstructions(); @Nullable abstract String voiceUnits(); @Nullable abstract String exclude(); @Nullable abstract String approaches(); @Nullable abstract String waypointIndices(); @Nullable abstract String waypointNames(); @Nullable abstract String waypointTargets(); @Nullable abstract Boolean enableRefresh(); @Nullable abstract Interceptor interceptor(); @Nullable abstract Interceptor networkInterceptor(); @Nullable abstract EventListener eventListener(); @Nullable abstract Boolean usePostMethod(); @Nullable abstract WalkingOptions walkingOptions(); @Nullable Double walkingSpeed() { if (!hasWalkingOptions()) { return null; } return walkingOptions().walkingSpeed(); } @Nullable Double walkwayBias() { if (!hasWalkingOptions()) { return null; } return walkingOptions().walkwayBias(); } @Nullable Double alleyBias() { if (!hasWalkingOptions()) { return null; } return walkingOptions().alleyBias(); } @Nullable abstract String snappingClosures(); private boolean hasWalkingOptions() { return walkingOptions() != null; } /** * Build a new {@link NbmapDirections} object with the initial values set for * {@link #baseUrl()}, {@link #profile()}, {@link #user()}, and {@link #geometries()}. * * @return a {@link Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_NbmapDirections.Builder() .baseUrl(Constants.BASE_API_URL) .profile(DirectionsCriteria.PROFILE_DRIVING) .user(DirectionsCriteria.PROFILE_DEFAULT_USER) .geometries(DirectionsCriteria.GEOMETRY_POLYLINE6); } /** * Returns the builder which created this instance of {@link NbmapDirections} and allows for * modification and building a new directions request with new information. * * @return {@link NbmapDirections.Builder} with the same variables set as this directions object * @since 3.0.0 */ public abstract Builder toBuilder(); /** * This builder is used to create a new request to the Nbmap Directions API. At a bare minimum, * your request must include an access token, an origin, and a destination. All other fields can * be left alone inorder to use the default behaviour of the API. * <p> * By default, the directions profile is set to driving (without traffic) but can be changed to * reflect your users use-case. * </p><p> * Note to contributors: All optional booleans in this builder use the object {@code Boolean} * rather than the primitive to allow for unset (null) values. * </p> * * @since 1.0.0 */ @AutoValue.Builder public abstract static class Builder { // TODO: change List<Double> to a custom model or to a Pair private List<List<Double>> bearings = new ArrayList<>(); private List<Point> coordinates = new ArrayList<>(); private List<String> annotations = new ArrayList<>(); private List<Double> radiuses = new ArrayList<>(); private Point destination; private Point origin; private List<String> approaches = new ArrayList<>(); private List<Integer> waypointIndices = new ArrayList<>(); private List<String> waypointNames = new ArrayList<>(); private List<Point> waypointTargets = new ArrayList<>(); private List<Boolean> snappingClosures = new ArrayList<>(); /** * The username for the account that the directions engine runs on. In most cases, this should * always remain the default value of {@link DirectionsCriteria#PROFILE_DEFAULT_USER}. * * @param user a non-null string which will replace the default user used in the directions * request * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder user(@NonNull String user); /** * This selects which mode of transportation the user will be using while navigating from the * origin to the final destination. The options include driving, driving considering traffic, * walking, and cycling. Using each of these profiles will result in different routing biases. * * @param profile required to be one of the String values found in the {@link ProfileCriteria} * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder profile(@NonNull @ProfileCriteria String profile); /** * This sets the starting point on the map where the route will begin. It is one of the * required parameters which must be set for a successful directions response. * * @param origin a GeoJson {@link Point} object representing the starting location for the route * @return this builder for chaining options together * @since 1.0.0 */ public Builder origin(@NonNull Point origin) { this.origin = origin; return this; } /** * This sets the ending point on the map where the route will end. It is one of the required * parameters which must be set for a successful directions response. * * @param destination a GeoJson {@link Point} object representing the starting location for the * route * @return this builder for chaining options together * @since 1.0.0 */ public Builder destination(@NonNull Point destination) { this.destination = destination; return this; } /** * This can be used to set up to 23 additional in-between points which will act as pit-stops * along the users route. Note that if you are using the * {@link DirectionsCriteria#PROFILE_DRIVING_TRAFFIC} that the max number of waypoints allowed * in the request is currently limited to 1. * * @param waypoint a {@link Point} which represents the pit-stop or waypoint where you'd like * one of the {@link RouteLeg} to navigate the user to * @return this builder for chaining options together * @since 3.0.0 */ public Builder addWaypoint(@NonNull Point waypoint) { coordinates.add(waypoint); return this; } /** * This can be used to set up to 23 additional in-between points which will act as pit-stops * along the users route. Note that if you are using the * {@link DirectionsCriteria#PROFILE_DRIVING_TRAFFIC} that the max number of waypoints allowed * in the request is currently limited to 1. * * @param waypoints a list which represents the pit-stops or waypoints where * you'd like one of the {@link RouteLeg} to navigate the user to * @return this builder for chaining options together */ public Builder waypoints(@NonNull List<Point> waypoints) { coordinates = waypoints; return this; } /** * Optionally set whether to try to return alternative routes. An alternative is classified as a * route that is significantly different then the fastest route, but also still reasonably fast. * Not in all circumstances such a route exists. At the moment at most one alternative can be * returned. * * @param alternatives true if you'd like to receive an alternative route, otherwise false or * null to use the APIs default value * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder alternatives(@Nullable Boolean alternatives); /** * alter the default geometry being returned for the directions route. A null value will reset * this field to the APIs default value vs this SDKs default value of * {@link DirectionsCriteria#GEOMETRY_POLYLINE6}. * <p> * Note that while the API supports GeoJson as an option for geometry, this SDK intentionally * removes this as an option since an encoded string for the geometry significantly reduces * bandwidth on mobile devices and speeds up response time. * </p> * * @param geometries null if you'd like the default geometry, else one of the options found in * {@link GeometriesCriteria}. * @return this builder for chaining options together * @since 2.0.0 */ public abstract Builder geometries(@GeometriesCriteria String geometries); /** * Type of returned overview geometry. Can be {@link DirectionsCriteria#OVERVIEW_FULL} (the most * detailed geometry available), {@link DirectionsCriteria#OVERVIEW_SIMPLIFIED} (a simplified * version of the full geometry), or {@link DirectionsCriteria#OVERVIEW_FALSE} (no overview * geometry). The default is simplified. Passing in null will use the APIs default setting for * the overview field. * * @param overview null or one of the options found in * {@link OverviewCriteria} * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder overview(@Nullable @OverviewCriteria String overview); /** * Setting this will determine whether to return steps and turn-by-turn instructions. Can be * set to either true or false to enable or disable respectively. null can also optionally be * passed in to set the default behavior to match what the API does by default. * * @param steps true if you'd like step information * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder steps(@Nullable Boolean steps); /** * Sets allowed direction of travel when departing intermediate waypoints. If true the route * will continue in the same direction of travel. If false the route may continue in the * opposite direction of travel. API defaults to true for * {@link DirectionsCriteria#PROFILE_DRIVING} and false for * {@link DirectionsCriteria#PROFILE_WALKING} and {@link DirectionsCriteria#PROFILE_CYCLING}. * * @param continueStraight boolean true if you want to always continue straight, else false. * Null can also be passed in here to use the APIs default option * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder continueStraight(@Nullable Boolean continueStraight); /** * Set the instruction language for the directions request, the default is english. Only a * select number of languages are currently supported, reference the table provided in the see * link below. * * @param language a Locale value representing the language you'd like the instructions to be * written in when returned * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#instructions-languages">Supported * Languages</a> * @since 2.2.0 */ public Builder language(@Nullable Locale language) { if (language != null) { language(language.getLanguage()); } return this; } abstract Builder language(@Nullable String language); /** * Optionally, set this to true if you want to enable instructions while exiting roundabouts * and rotaries. * * @param roundaboutExits true if you'd like extra roundabout instructions * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder roundaboutExits(@Nullable Boolean roundaboutExits); /** * Whether or not to return additional metadata along the route. Possible values are: * {@link DirectionsCriteria#ANNOTATION_DISTANCE}, * {@link DirectionsCriteria#ANNOTATION_DURATION} and * {@link DirectionsCriteria#ANNOTATION_CONGESTION}. Several annotation can be used by * separating them with {@code ,}. * * @param annotations string referencing one of the annotation direction criteria's. The strings * restricted to one or multiple values inside the {@link AnnotationCriteria} * or null which will result in no annotations being used * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#route-leg-object">RouteLeg object * documentation</a> * @since 2.1.0 * @deprecated use {@link #annotations(List)} */ @Deprecated public Builder annotations(@AnnotationCriteria @NonNull String... annotations) { return annotations(Arrays.asList(annotations)); } /** * Whether or not to return additional metadata along the route. Possible values are: * {@link DirectionsCriteria#ANNOTATION_DISTANCE}, * {@link DirectionsCriteria#ANNOTATION_DURATION} and * {@link DirectionsCriteria#ANNOTATION_CONGESTION} * * @param annotations a list of annotations * @return this builder for chaining options together */ public Builder annotations(@NonNull List<String> annotations) { this.annotations = annotations; return this; } /** * Whether or not to return additional metadata along the route. Possible values are: * {@link DirectionsCriteria#ANNOTATION_DISTANCE}, * {@link DirectionsCriteria#ANNOTATION_DURATION} and * {@link DirectionsCriteria#ANNOTATION_CONGESTION} * * @param annotation string referencing one of the annotation direction criteria's. * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#route-leg-object">RouteLeg object * documentation</a> * @since 2.1.0 */ public Builder addAnnotation(@AnnotationCriteria @NonNull String annotation) { this.annotations.add(annotation); return this; } abstract Builder annotation(@Nullable String annotation); /** * Optionally, Use to filter the road segment the waypoint will be placed on by direction and * dictates the angle of approach. This option should always be used in conjunction with the * {@link #radiuses} parameter. * <p> * The parameter takes two values per waypoint: the first is an angle clockwise from true north * between 0 and 360. The second is the range of degrees the angle can deviate by. We recommend * a value of 45 degrees or 90 degrees for the range, as bearing measurements tend to be * inaccurate. This is useful for making sure we reroute vehicles on new routes that continue * traveling in their current direction. A request that does this would provide bearing and * radius values for the first waypoint and leave the remaining values empty. If provided, the * list of bearings must be the same length as the list of waypoints, but you can skip a * coordinate and show its position by passing in null value for both the angle and tolerance * values. * </p><p> * Each bearing value gets associated with the same order which coordinates are arranged in this * builder. For example, the first bearing added in this builder will be associated with the * origin {@code Point}, the nth bearing being associated with the nth waypoint added (if added) * and the last bearing being added will be associated with the destination. * </p> * * @param angle double value used for setting the corresponding coordinate's angle of travel * when determining the route * @param tolerance the deviation the bearing angle can vary while determining the route, * recommended to be either 45 or 90 degree tolerance * @return this builder for chaining options together * @since 2.0.0 */ public Builder addBearing(@Nullable @FloatRange(from = 0, to = 360) Double angle, @Nullable @FloatRange(from = 0, to = 360) Double tolerance) { bearings.add(Arrays.asList(angle, tolerance)); return this; } /** * Optionally, Use to filter the road segment the waypoint will be placed on by direction and * dictates the angle of approach. This option should always be used in conjunction with the * {@link #radiuses} parameter. * * @param bearings a list of list of doubles. Every list has two values: * the first is an angle clockwise from true north between 0 and 360. The * second is the range of degrees the angle can deviate by. We recommend * a value of 45 degrees or 90 degrees for the range, as bearing measurements * tend to be inaccurate. * @return this builder for chaining options together */ public Builder bearings(@NonNull List<List<Double>> bearings) { this.bearings = bearings; return this; } abstract Builder bearing(@Nullable String bearings); /** * Optionally, set the maximum distance in meters that each coordinate is allowed to move when * snapped to a nearby road segment. There must be as many radiuses as there are coordinates in * the request. Values can be any number greater than 0 or they can be unlimited simply by * passing {@link Double#POSITIVE_INFINITY}. * <p> * If no routable road is found within the radius, a {@code NoSegment} error is returned. * </p> * * @param radiuses double array containing the radiuses defined in unit meters. * @return this builder for chaining options together * @since 1.0.0 * @deprecated use {@link #radiuses(List)} */ @Deprecated public Builder radiuses(@NonNull @FloatRange(from = 0) Double... radiuses) { return radiuses(Arrays.asList(radiuses)); } /** * Optionally, set the maximum distance in meters that each coordinate is allowed to move when * snapped to a nearby road segment. There must be as many radiuses as there are coordinates in * the request. Values can be any number greater than 0 or they can be unlimited simply by * passing {@link Double#POSITIVE_INFINITY}. * <p> * If no routable road is found within the radius, a {@code NoSegment} error is returned. * </p> * * @param radiuses a list with radiuses defined in unit meters. * @return this builder for chaining options together */ public Builder radiuses(@NonNull List<Double> radiuses) { this.radiuses = radiuses; return this; } /** * Optionally, set the maximum distance in meters that each coordinate is allowed to move when * snapped to a nearby road segment. There must be as many radiuses as there are coordinates in * the request. Values can be any number greater than 0 or they can be unlimited simply by * passing {@link Double#POSITIVE_INFINITY}. * <p> * If no routable road is found within the radius, a {@code NoSegment} error is returned. * </p> * * @param radius double param defined in unit meters. * @return this builder for chaining options together * @since 1.0.0 */ public Builder addRadius(@NonNull @FloatRange(from = 0) Double radius) { this.radiuses.add(radius); return this; } abstract Builder radius(@Nullable String radiuses); /** * Exclude certain road types from routing. Valid values depend on the profile in use. The * default is to not exclude anything from the profile selected. * * @param exclude one of the constants defined in {@link ExcludeCriteria} * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder exclude(@ExcludeCriteria String exclude); /** * Request voice instructions objects to be returned in your response. This offers instructions * specific for navigation and provides well spoken text instructions along with the distance * from the maneuver the instructions should be said. * <p> * It's important to note that the {@link #steps(Boolean)} should be true or else these results * wont be returned. * </p> * * @param voiceInstructions true if you'd like voice instruction objects be attached to your * response * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder voiceInstructions(@Nullable Boolean voiceInstructions); /** * Request banner instructions object to be returned in your response. This is useful * specifically for navigation and provides an abundance of information one might want to * display to their user inside an Android view for example. * * @param bannerInstructions true if you'd like the receive banner objects within your response * object * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder bannerInstructions(@Nullable Boolean bannerInstructions); /** * Specify what unit you'd like voice and banner instructions to use. * * @param voiceUnits either Imperial (default) or Metric * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder voiceUnits(@Nullable @VoiceUnitCriteria String voiceUnits); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Optimization API * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder baseUrl(String baseUrl); /** * Adds an optional interceptor to set in the OkHttp client. * * @param interceptor to set for OkHttp * @return this builder for chaining options together */ public abstract Builder interceptor(Interceptor interceptor); /** * Adds an optional network interceptor to set in the OkHttp client. * * @param interceptor to set for OkHttp * @return this builder for chaining options together */ public abstract Builder networkInterceptor(Interceptor interceptor); /** * Adds an optional event listener to set in the OkHttp client. * * @param eventListener to set for OkHttp * @return this builder for chaining options together */ public abstract Builder eventListener(EventListener eventListener); abstract Builder coordinates(@NonNull List<Point> coordinates); /** * Indicates from which side of the road to approach a waypoint. * Accepts unrestricted (default), curb or null. * If set to unrestricted , the route can approach waypoints * from either side of the road. If set to curb , the route will be returned * so that on arrival, the waypoint will be found on the side that corresponds with the * driving_side of the region in which the returned route is located. * If provided, the list of approaches must be the same length as the list of waypoints. * * @param approaches null if you'd like the default approaches, * else one of the options found in * {@link com.nbmap.api.directions.v5.DirectionsCriteria.ApproachesCriteria}. * @return this builder for chaining options together * @since 3.2.0 * @deprecated use {@link #approaches(List)} */ @Deprecated public Builder addApproaches(@NonNull String... approaches) { return approaches(Arrays.asList(approaches)); } /** * Indicates from which side of the road to approach a waypoint. * Accepts unrestricted (default), curb or null. * If set to unrestricted , the route can approach waypoints * from either side of the road. If set to curb , the route will be returned * so that on arrival, the waypoint will be found on the side that corresponds with the * driving_side of the region in which the returned route is located. * If provided, the list of approaches must be the same length as the list of waypoints. * * @param approaches empty if you'd like the default approaches, * else one of the options found in * {@link com.nbmap.api.directions.v5.DirectionsCriteria.ApproachesCriteria}. * @return this builder for chaining options together */ public Builder approaches(@NonNull List<String> approaches) { this.approaches = approaches; return this; } abstract Builder approaches(@Nullable String approaches); /** * Indicates from which side of the road to approach a waypoint. * Accepts unrestricted (default), curb or null. * If set to unrestricted , the route can approach waypoints * from either side of the road. If set to curb , the route will be returned * so that on arrival, the waypoint will be found on the side that corresponds with the * driving_side of the region in which the returned route is located. * If provided, the list of approaches must be the same length as the list of waypoints. * * @param approach null if you'd like the default approaches, else one of the options found in * {@link com.nbmap.api.directions.v5.DirectionsCriteria.ApproachesCriteria}. * @return this builder for chaining options together * @since 3.2.0 */ public Builder addApproach(@Nullable String approach) { this.approaches.add(approach); return this; } /** * Optionally, set which input coordinates should be treated as waypoints / separate legs. * Note: coordinate indices not added here act as silent waypoints * <p> * Most useful in combination with steps=true and requests based on traces * with high sample rates. Can be an index corresponding to any of the input coordinates, * but must contain the first ( 0 ) and last coordinates' indices. * {@link #steps()} * </p> * * @param waypointIndices integer array of coordinate indices to be used as waypoints * @return this builder for chaining options together * @since 4.4.0 * @deprecated use {@link #waypointIndices(List)} */ @Deprecated public Builder addWaypointIndices(@NonNull @IntRange(from = 0) Integer... waypointIndices) { return waypointIndices(Arrays.asList(waypointIndices)); } /** * Optionally, set which input coordinates should be treated as waypoints / separate legs. * Note: coordinate indices not added here act as silent waypoints * <p> * Most useful in combination with steps=true and requests based on traces * with high sample rates. Can be an index corresponding to any of the input coordinates, * but must contain the first ( 0 ) and last coordinates' indices. * {@link #steps()} * </p> * * @param waypointIndices a list of coordinate indices to be used as waypoints * @return this builder for chaining options together */ public Builder waypointIndices(@NonNull List<Integer> waypointIndices) { this.waypointIndices = waypointIndices; return this; } abstract Builder waypointIndices(@Nullable String waypointIndices); /** * Optionally, set which input coordinates should be treated as waypoints / separate legs. * Note: coordinate indices not added here act as silent waypoints * <p> * Most useful in combination with steps=true and requests based on traces * with high sample rates. Can be an index corresponding to any of the input coordinates, * but must contain the first ( 0 ) and last coordinates' indices. * {@link #steps()} * </p> * * @param waypointIndex integer index to be used as waypoint * @return this builder for chaining options together * @since 4.4.0 */ public Builder addWaypointIndex(@NonNull @IntRange(from = 0) Integer waypointIndex) { this.waypointIndices.add(waypointIndex); return this; } /** * Custom names for waypoints used for the arrival instruction. * Values can be any string and total number of all characters cannot exceed 500. * If provided, the list of waypointNames must be the same length as the list of * coordinates, but you can skip a coordinate and show its position with the null value. * * @param waypointNames Custom names for waypoints used for the arrival instruction. * @return this builder for chaining options together * @since 3.3.0 * @deprecated use {@link #waypointNames(List)} */ @Deprecated public Builder addWaypointNames(@NonNull String... waypointNames) { return waypointNames(Arrays.asList(waypointNames)); } /** * Custom names for waypoints used for the arrival instruction. * Values can be any string and total number of all characters cannot exceed 500. * If provided, the list of waypointNames must be the same length as the list of * coordinates, but you can skip a coordinate and show its position with the null value. * * @param waypointNames a list of custom names for waypoints used for the arrival instruction. * @return this builder for chaining options together */ public Builder waypointNames(@NonNull List<String> waypointNames) { this.waypointNames = waypointNames; return this; } abstract Builder waypointNames(@Nullable String waypointNames); /** * Custom names for waypoints used for the arrival instruction. * Values can be any string and total number of all characters cannot exceed 500. * If provided, the list of waypointNames must be the same length as the list of * coordinates, but you can skip a coordinate and show its position with the null value. * * @param waypointName Custom name for waypoint used for the arrival instruction. * @return this builder for chaining options together * @since 3.3.0 */ public Builder addWaypointName(@Nullable String waypointName) { this.waypointNames.add(waypointName); return this; } /** * Points to specify drop-off locations that are distinct from the locations specified in * coordinates. * The number of waypoint targets must be the same as the number of coordinates, * but you can skip a coordinate with a null value. * Must be used with steps=true. * * @param waypointTargets list of coordinate points for drop-off locations * @return this builder for chaining options together * @since 4.3.0 * @deprecated use {@link #waypointTargets(List)} */ @Deprecated public Builder addWaypointTargets(@NonNull Point... waypointTargets) { return waypointTargets(Arrays.asList(waypointTargets)); } /** * A list of points used to specify drop-off locations that are distinct from the locations * specified in coordinates. * The number of waypoint targets must be the same as the number of coordinates, * but you can skip a coordinate with a null value. * Must be used with steps=true. * * @param waypointTargets list of coordinate points for drop-off locations * @return this builder for chaining options together */ public Builder waypointTargets(@NonNull List<Point> waypointTargets) { this.waypointTargets = waypointTargets; return this; } abstract Builder waypointTargets(@Nullable String waypointTargets); /** * A point to specify drop-off locations that are distinct from the locations specified in * coordinates. * The number of waypoint targets must be the same as the number of coordinates, * but you can skip a coordinate with a null value. * Must be used with steps=true. * * @param waypointTarget a point for drop-off locations * @return this builder for chaining options together * @since 4.3.0 */ public Builder addWaypointTarget(@Nullable Point waypointTarget) { this.waypointTargets.add(waypointTarget); return this; } /** * A list of booleans affecting snapping of waypoint locations to road segments. * If true, road segments closed due to live-traffic closures will be considered for snapping. * If false, they will not be considered for snapping. * If provided, the number of snappingClosures must be the same as the number of * coordinates. * You can skip a coordinate and show its position in the list with null value. * Must be used with {@link DirectionsCriteria#PROFILE_DRIVING_TRAFFIC} * * @param snappingClosures a list of booleans * @return this builder for chaining options together */ public Builder snappingClosures(@NonNull List<Boolean> snappingClosures) { this.snappingClosures = snappingClosures; return this; } abstract Builder snappingClosures(@Nullable String snappingClosures); /** * A boolean affecting snapping of waypoint location to the road segment. * If true, road segment closed due to live-traffic closure will be considered for snapping. * If false, it will not be considered for snapping. * If provided, the number of snappingClosures must be the same as the number of * coordinates. * You can skip a coordinate with null value. * Must be used with {@link DirectionsCriteria#PROFILE_DRIVING_TRAFFIC} * * @param snappingClosure a boolean affecting snapping of waypoint location to the road segment. * @return this builder for chaining options together * @since 5.9.0 */ public Builder addSnappingClosure(@Nullable Boolean snappingClosure) { this.snappingClosures.add(snappingClosure); return this; } /** * Whether the routes should be refreshable via the directions refresh API. * * @param enableRefresh whether the routes should be refreshable * @return this builder * @since 4.4.0 */ public abstract Builder enableRefresh(Boolean enableRefresh); /** * Use POST method to request data. * The default is to use GET. * @return this builder for chaining options together * @since 4.6.0 */ public Builder post() { usePostMethod(true); return this; } /** * Use GET method to request data. * @return this builder for chaining options together * @since 4.6.0 */ public Builder get() { usePostMethod(false); return this; } /** * To be used to specify settings for use with the walking profile. * * @param walkingOptions options to use for walking profile * @return this builder for chaining options together * @since 4.8.0 */ public abstract Builder walkingOptions(@NonNull WalkingOptions walkingOptions); abstract WalkingOptions walkingOptions(); abstract Builder usePostMethod(@NonNull Boolean usePost); abstract Boolean usePostMethod(); abstract NbmapDirections autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and first checks that all * values are valid, formats the values as strings for easier consumption by the API, and lastly * creates a new {@link NbmapDirections} object with the values provided. * * @return a new instance of Nbmap Directions * @since 2.1.0 */ public NbmapDirections build() { if (origin != null) { coordinates.add(0, origin); } if (destination != null) { coordinates.add(destination); } if (coordinates.size() < 2) { throw new ServicesException("An origin and destination are required before making the" + " directions API request."); } if (!waypointIndices.isEmpty()) { if (waypointIndices.size() < 2) { throw new ServicesException( "Waypoints must be a list of at least two indexes separated by ';'"); } if (waypointIndices.get(0) != 0 || waypointIndices.get(waypointIndices.size() - 1) != coordinates.size() - 1) { throw new ServicesException( "Waypoints must contain indices of the first and last coordinates" ); } for (int i = 1; i < waypointIndices.size() - 1; i++) { if (waypointIndices.get(i) < 0 || waypointIndices.get(i) >= coordinates.size()) { throw new ServicesException( "Waypoints index too large (no corresponding coordinate)"); } } } if (!waypointNames.isEmpty()) { final String waypointNamesStr = FormatUtils.formatWaypointNames(waypointNames); waypointNames(waypointNamesStr); } if (!waypointTargets.isEmpty()) { if (waypointTargets.size() != coordinates.size()) { throw new ServicesException("Number of waypoint targets must match " + " the number of waypoints provided."); } waypointTargets(FormatUtils.formatPointsList(waypointTargets)); } if (!approaches.isEmpty()) { if (approaches.size() != coordinates.size()) { throw new ServicesException("Number of approach elements must match " + "number of coordinates provided."); } String formattedApproaches = FormatUtils.formatApproaches(approaches); if (formattedApproaches == null) { throw new ServicesException("All approaches values must be one of curb, unrestricted"); } approaches(formattedApproaches); } if (!snappingClosures.isEmpty()) { if (snappingClosures.size() != coordinates.size()) { throw new ServicesException("Number of snapping closures elements must match " + "number of coordinates provided."); } snappingClosures(FormatUtils.join(";", snappingClosures)); } coordinates(coordinates); bearing(FormatUtils.formatBearings(bearings)); annotation(FormatUtils.join(",", annotations)); radius(FormatUtils.formatRadiuses(radiuses)); waypointIndices(FormatUtils.join(";", waypointIndices, true)); NbmapDirections directions = autoBuild(); if (!NbmapUtils.isAccessTokenValid(directions.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access" + " token."); } return directions; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directionsrefresh
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directionsrefresh/v1/DirectionsRefreshService.java
package com.nbmap.api.directionsrefresh.v1; import com.nbmap.api.directionsrefresh.v1.models.DirectionsRefreshResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the directions refresh service. This corresponds to v1 of the * directions API, specifically driving directions. * * @since 4.4.0 */ public interface DirectionsRefreshService { /** * Constructs the html call using the information passed in through the * {@link NbmapDirectionsRefresh.Builder}. * * @param userAgent the user agent * @param requestId a uuid specifying the request containing the route being refreshed * @param routeIndex the index of the specified route * @param legIndex the index of the leg to start the refresh response (inclusive) * @param accessToken Nbmap access token * @return the {@link DirectionsRefreshResponse} in a Call wrapper * @since 4.4.0 */ @GET("directions-refresh/v1/nbmap/driving-traffic/{request_id}/{route_index}/{leg_index}") Call<DirectionsRefreshResponse> getCall( @Header("User-Agent") String userAgent, @Path("request_id") String requestId, @Path("route_index") int routeIndex, @Path("leg_index") int legIndex, @Query("key") String accessToken ); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directionsrefresh
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directionsrefresh/v1/NbmapDirectionsRefresh.java
package com.nbmap.api.directionsrefresh.v1; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.api.directions.v5.DirectionsAdapterFactory; import com.nbmap.api.directions.v5.models.RouteOptions; import com.nbmap.api.directionsrefresh.v1.models.DirectionsRefreshResponse; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.utils.ApiCallHelper; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; /** * The directions refresh API allows a route to be refreshed via it's annotations. The * refreshEnabled parameter would have had to have been specified as true in the original * directions request for a refresh to be possible. * * @since 4.4.0 */ @AutoValue public abstract class NbmapDirectionsRefresh extends NbmapService<DirectionsRefreshResponse, DirectionsRefreshService> { private static final int ZERO = 0; protected NbmapDirectionsRefresh() { super(DirectionsRefreshService.class); } @Override protected Call<DirectionsRefreshResponse> initializeCall() { return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), requestId(), routeIndex(), legIndex(), accessToken() ); } @Override protected synchronized OkHttpClient getOkHttpClient() { if (okHttpClient == null) { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); if (isEnableDebug()) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BASIC); httpClient.addInterceptor(logging); } Interceptor interceptor = interceptor(); if (interceptor != null) { httpClient.addInterceptor(interceptor); } okHttpClient = httpClient.build(); } return okHttpClient; } abstract String requestId(); abstract int routeIndex(); abstract int legIndex(); abstract String accessToken(); @Nullable abstract String clientAppName(); @NonNull @Override protected abstract String baseUrl(); @Nullable abstract Interceptor interceptor(); @Override protected GsonBuilder getGsonBuilder() { return super.getGsonBuilder() .registerTypeAdapterFactory(DirectionsRefreshAdapterFactory.create()) .registerTypeAdapterFactory(DirectionsAdapterFactory.create()); } /** * Convert the current {@link NbmapDirectionsRefresh} to its builder holding the currently * assigned values. This allows you to modify a single property and then rebuild the object * resulting in an updated and modified {@link NbmapDirectionsRefresh}. * * @return a {@link NbmapDirectionsRefresh.Builder} with the same values * @since 4.4.0 */ public abstract Builder toBuilder(); /** * Build a new {@link NbmapDirectionsRefresh} builder with default initial values. * * @return a {@link Builder} for creating a default {@link NbmapDirectionsRefresh} * @since 4.4.0 */ public static Builder builder() { return new AutoValue_NbmapDirectionsRefresh.Builder() .baseUrl(Constants.BASE_API_URL) .routeIndex(ZERO) .legIndex(ZERO); } /** * This builder is used to build a new request to the Nbmap Directions Refresh API. A request * requires an access token and a request id. * * @since 4.4.0 */ @AutoValue.Builder public abstract static class Builder { /** * Specified here is the uuid of the initial directions request. The original request must * have specified enableRefresh. * * @param requestId id of the original directions request. This is found in the * {@link RouteOptions} object. * @return this builder * @since 4.4.0 */ public abstract Builder requestId(String requestId); /** * Index of original route in response. * * @param routeIndex index of route in response * @return this builder * @since 4.4.0 */ public abstract Builder routeIndex(@NonNull int routeIndex); /** * Index of leg of which to start. The response will include the annotations of the specified * leg through the end of the list of legs. * * @param legIndex index of leg * @return this builder * @since 4.4.0 */ public abstract Builder legIndex(@NonNull int legIndex); /** * Required to call when this is being built. If no access token provided, * {@link com.nbmap.core.exceptions.ServicesException} will be thrown. * * @param accessToken Nbmap access token * @return this builder * @since 4.4.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 4.4.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as endpoint * @return this builder * @since 4.4.0 */ public abstract Builder baseUrl(String baseUrl); /** * Adds an optional interceptor to set in the OkHttp client. * * @param interceptor to set for OkHttp * @return this builder for chaining options together * @since 4.9.0 */ public abstract Builder interceptor(Interceptor interceptor); /** * Returns an instance of {@link NbmapDirectionsRefresh} for interacting with the endpoint * with the specified values. * * @return instance of {@link NbmapDirectionsRefresh} with specified attributes * @since 4.4.0 */ public abstract NbmapDirectionsRefresh build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directionsrefresh
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/directionsrefresh/v1/package-info.java
/** * Contains classes for accessing the Nbmap Directions Refresh API. * * @since 4.4.0 */ package com.nbmap.api.directionsrefresh.v1;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/GeocodingCriteria.java
package com.nbmap.api.geocoding.v5; import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Constants that should be used when requesting geocoding. * * @since 1.0.0 */ public final class GeocodingCriteria { /** * Default geocoding mode. * * @since 1.0.0 */ public static final String MODE_PLACES = "nbmap.places"; /** * Geocoding mode for batch and permanent geocoding. For more information about this mode, contact <a href="https://www.nbmap.com/contact/sales/">Nbmap sales</a>. * * @since 1.0.0 */ public static final String MODE_PLACES_PERMANENT = "nbmap.places-permanent"; /** * 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 postcode. * * @since 1.0.0 */ public static final String TYPE_POSTCODE = "postcode"; /** * Filter results by district. * * @since 2.2.0 */ public static final String TYPE_DISTRICT = "district"; /** * Filter results by place. * * @since 1.0.0 */ public static final String TYPE_PLACE = "place"; /** * Filter results by locality. * * @since 2.2.0 */ public static final String TYPE_LOCALITY = "locality"; /** * 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 POI. * * @since 1.0.0 */ public static final String TYPE_POI = "poi"; /** * Filter results by POI landmark subtype. * * @since 1.3.2 */ public static final String TYPE_POI_LANDMARK = "poi.landmark"; /** * Filter results by distance. * * @since 3.3.0 */ public static final String REVERSE_MODE_DISTANCE = "distance"; /** * Filter results by score. * * @since 3.3.0 */ public static final String REVERSE_MODE_SCORE = "score"; private GeocodingCriteria() { // Empty private constructor } /** * Retention policy for the various geocoding modes. * * @since 3.0.0 */ @Retention(RetentionPolicy.CLASS) @StringDef( { MODE_PLACES, MODE_PLACES_PERMANENT }) public @interface GeocodingModeCriteria { } /** * Retention policy for the various filter result types. * * @since 3.0.0 */ @Retention(RetentionPolicy.CLASS) @StringDef( { TYPE_COUNTRY, TYPE_REGION, TYPE_POSTCODE, TYPE_DISTRICT, TYPE_PLACE, TYPE_LOCALITY, TYPE_NEIGHBORHOOD, TYPE_ADDRESS, TYPE_POI, TYPE_POI_LANDMARK }) public @interface GeocodingTypeCriteria { } /** * Retention policy for reverseMode filter result types. * * @since 3.0.0 */ @Retention(RetentionPolicy.CLASS) @StringDef( { REVERSE_MODE_DISTANCE, REVERSE_MODE_SCORE }) public @interface GeocodingReverseModeCriteria { } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/GeocodingService.java
package com.nbmap.api.geocoding.v5; import com.nbmap.api.geocoding.v5.models.GeocodingResponse; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the geocoding service. * * @since 1.0.0 */ public interface GeocodingService { /** * Constructs the html call using the information passed in through the * {@link NbmapGeocoding.Builder}. * * @param userAgent The user * @param mode nbmap.places or nbmap.places-permanent for batch and permanent geocoding. * @param query a location; a place name for forward geocoding or a coordinate pair * (longitude, latitude location) for reverse geocoding * @param accessToken Nbmap 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. * @param limit Optionally pass in a limit the amount of returning results. * @param language The locale in which results should be returned. * @param reverseMode Set the factors that are used to sort nearby results. * @param fuzzyMatch Set whether to allow the geocoding API to attempt exact matching or not. * @return A retrofit Call object * @since 1.0.0 */ @GET("/geocoding/v5/{mode}/{query}.json") Call<GeocodingResponse> getCall( @Header("User-Agent") String userAgent, @Path("mode") String mode, @Path("query") String query, @Query("key") String accessToken, @Query("country") String country, @Query("proximity") String proximity, @Query("types") String types, @Query("autocomplete") Boolean autocomplete, @Query("bbox") String bbox, @Query("limit") String limit, @Query("language") String language, @Query("reverseMode") String reverseMode, @Query("fuzzyMatch") Boolean fuzzyMatch); /** * Constructs the html call using the information passed in through the * {@link NbmapGeocoding.Builder}. * * @param userAgent The user * @param mode nbmap.places-permanent for batch geocoding. * @param query a location; a place name for forward geocoding or a coordinate pair * (longitude, latitude location) for reverse geocoding * @param accessToken Nbmap 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. * @param limit Optionally pass in a limit the amount of returning results. * @param language The locale in which results should be returned. * @param reverseMode Set the factors that are used to sort nearby results. * @param fuzzyMatch Set whether to allow the geocoding API to attempt exact matching or not. * @return A retrofit Call object * @since 1.0.0 */ @GET("/geocoding/v5/{mode}/{query}.json") Call<List<GeocodingResponse>> getBatchCall( @Header("User-Agent") String userAgent, @Path("mode") String mode, @Path("query") String query, @Query("key") String accessToken, @Query("country") String country, @Query("proximity") String proximity, @Query("types") String types, @Query("autocomplete") Boolean autocomplete, @Query("bbox") String bbox, @Query("limit") String limit, @Query("language") String language, @Query("reverseMode") String reverseMode, @Query("fuzzyMatch") Boolean fuzzyMatch); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/NbmapGeocoding.java
package com.nbmap.api.geocoding.v5; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.api.geocoding.v5.GeocodingCriteria.GeocodingTypeCriteria; import com.nbmap.api.geocoding.v5.models.GeocodingAdapterFactory; import com.nbmap.api.geocoding.v5.models.GeocodingResponse; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.ApiCallHelper; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.BoundingBox; import com.nbmap.geojson.GeometryAdapterFactory; import com.nbmap.geojson.Point; import com.nbmap.geojson.gson.BoundingBoxTypeAdapter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * This class gives you access to both Nbmap forward and reverse geocoding. * <p> * Forward geocoding lets you convert location text into geographic coordinates, turning * {@code 2 Lincoln Memorial Circle NW} into a {@link Point} with the coordinates * {@code -77.050, 38.889}. * <p> * Reverse geocoding turns geographic coordinates into place names, turning {@code -77.050, 38.889} * into {@code 2 Lincoln Memorial Circle NW}. These place names can vary from specific addresses to * states and countries that contain the given coordinates. * <p> * Batch Geocoding * The {@link #mode()} must be set to * {@link GeocodingCriteria#MODE_PLACES_PERMANENT}. * For more information about batch geocoding, contact <a href="https://www.nbmap.com/contact/sales/">Nbmap sales</a>. * <p> * Batch requests have the same parameters as normal requests, but can include more than one query * by using {@link NbmapGeocoding.Builder#query(String)} and separating queries with the {@code ;} * character. * <p> * With the {@link GeocodingCriteria#MODE_PLACES_PERMANENT} mode, you can make up to 50 forward or * reverse geocoding queries in a single request. The response is a list of individual * {@link GeocodingResponse}s. Each query in a batch request counts individually against your * account's rate limits. * * @see <a href="https://www.nbmap.com/android-docs/java-sdk/overview/geocoder/">Android * Geocoding documentation</a> * @since 1.0.0 */ @AutoValue public abstract class NbmapGeocoding extends NbmapService<GeocodingResponse, GeocodingService> { private Call<List<GeocodingResponse>> batchCall; protected NbmapGeocoding() { super(GeocodingService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) .registerTypeAdapterFactory(GeometryAdapterFactory.create()) .registerTypeAdapterFactory(SingleElementSafeListTypeAdapter.FACTORY) .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()); } @Override protected Call<GeocodingResponse> initializeCall() { if (mode().contains(GeocodingCriteria.MODE_PLACES_PERMANENT)) { throw new IllegalArgumentException("Use getBatchCall() for batch calls."); } return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), mode(), query(), accessToken(), country(), proximity(), geocodingTypes(), autocomplete(), bbox(), limit(), languages(), reverseMode(), fuzzyMatch()); } private Call<List<GeocodingResponse>> getBatchCall() { // No need to recreate it if (batchCall != null) { return batchCall; } if (mode().equals(GeocodingCriteria.MODE_PLACES)) { throw new ServicesException( "Use getCall() for non-batch calls or set the mode to `permanent` for batch requests." ); } batchCall = getService().getBatchCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), mode(), query(), accessToken(), country(), proximity(), geocodingTypes(), autocomplete(), bbox(), limit(), languages(), reverseMode(), fuzzyMatch()); return batchCall; } /** * Wrapper method for Retrofits {@link Call#execute()} call returning a batch response specific to * the Geocoding API. * * @return the Geocoding v5 batch response once the call completes successfully * @throws IOException Signals that an I/O exception of some sort has occurred. * @since 1.0.0 */ public Response<List<GeocodingResponse>> executeBatchCall() throws IOException { return getBatchCall().execute(); } /** * Wrapper method for Retrofits {@link Call#enqueue(Callback)} call returning a batch response * specific to the Geocoding batch API. Use this method to make a geocoding request on the Main * Thread. * * @param callback a {@link Callback} which is used once the {@link GeocodingResponse} is created. * @since 1.0.0 */ public void enqueueBatchCall(Callback<List<GeocodingResponse>> callback) { getBatchCall().enqueue(callback); } /** * Wrapper method for Retrofits {@link Call#cancel()} call, important to manually cancel call if * the user dismisses the calling activity or no longer needs the returned results. * * @since 1.0.0 */ public void cancelBatchCall() { getBatchCall().cancel(); } /** * Wrapper method for Retrofits {@link Call#clone()} call, useful for getting call information. * * @return cloned call * @since 1.0.0 */ public Call<List<GeocodingResponse>> cloneBatchCall() { return getBatchCall().clone(); } @NonNull abstract String query(); @NonNull abstract String mode(); @NonNull abstract String accessToken(); @NonNull @Override protected abstract String baseUrl(); @Nullable abstract String country(); @Nullable abstract String proximity(); @Nullable abstract String geocodingTypes(); @Nullable abstract Boolean autocomplete(); @Nullable abstract String bbox(); @Nullable abstract String limit(); @Nullable abstract String languages(); @Nullable abstract String reverseMode(); @Nullable abstract Boolean fuzzyMatch(); @Nullable abstract String clientAppName(); /** * Build a new {@link NbmapGeocoding} object with the initial values set for * {@link #baseUrl()} and {@link #mode()}. * * @return a {@link Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_NbmapGeocoding.Builder() .baseUrl(Constants.BASE_API_URL) .mode(GeocodingCriteria.MODE_PLACES); } /** * This builder is used to create a new request to the Nbmap Geocoding API. At a bare minimum, * your request must include an access token and a query of some kind. All other fields can * be left alone in order to use the default behaviour of the API. * <p> * By default, the geocoding mode is set to nbmap.places. * The mode can be changed to nbmap.places-permanent * to enable batch and permanent geocoding. For more information about * nbmap.places-permanent, contact <a href="https://www.nbmap.com/contact/sales/">Nbmap sales</a>. * </p><p> * Note to contributors: All optional booleans in this builder use the object {@code Boolean} * rather than the primitive to allow for unset (null) values. * </p> * * @since 1.0.0 */ @AutoValue.Builder public abstract static class Builder { private List<String> countries = new ArrayList<>(); private List<String> intersectionStreets = new ArrayList<>(); /** * Perform a reverse geocode on the provided {@link Point}. Only one point can be passed in as * the query and isn't guaranteed to return a result. If you * want to do a batch reverse Geocode, you can use the {@link #query(String)} method * separating them with a semicolon. For more information about batch geocoding, contact <a href="https://www.nbmap.com/contact/sales/">Nbmap sales</a>. * * @param point a GeoJSON point which matches to coordinate you'd like to reverse geocode * @return this builder for chaining options together * @since 3.0.0 */ public Builder query(@NonNull Point point) { query(String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(point.longitude()), TextUtils.formatCoordinate(point.latitude()))); return this; } /** * This method can be used for performing a forward geocode on a string representing a address * or POI. If you want to perform a batch geocode, separate your * queries with a semicolon. For more information about batch geocoding, * contact <a href="https://www.nbmap.com/contact/sales/">Nbmap sales</a>. * * @param query a String containing the text you'd like to forward geocode * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder query(@NonNull String query); /** * This sets the kind of geocoding result you desire, either ephemeral geocoding or batch * geocoding. * <p> * To access batch geocoding, contact <a href="https://www.nbmap.com/contact/sales/">Nbmap sales</a>. * If you do not have access to batch geocoding, it will return * an error code rather than a successful result. * </p><p> * Options avaliable to pass in include, {@link GeocodingCriteria#MODE_PLACES} for a ephemeral * geocoding result (default) or {@link GeocodingCriteria#MODE_PLACES_PERMANENT} for * batch and permanent geocoding. * </p> * * @param mode nbmap.places or nbmap.places-permanent for batch and permanent geocoding * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder mode(@NonNull @GeocodingCriteria.GeocodingModeCriteria String mode); /** * Bias local results base on a provided {@link Point}. This oftentimes increases accuracy in * the returned results. * * @param proximity a point defining the proximity you'd like to bias the results around * @return this builder for chaining options together * @since 1.0.0 */ public Builder proximity(@NonNull Point proximity) { proximity(String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(proximity.longitude()), proximity.latitude())); return this; } abstract Builder proximity(String proximity); /** * This optionally can be set to filter the results returned back after making your forward or * reverse geocoding request. A null value can't be passed in and only values defined in * {@link GeocodingTypeCriteria} are allowed. * <p> * Note that {@link GeocodingCriteria#TYPE_POI_LANDMARK} returns a subset of the results * returned by {@link GeocodingCriteria#TYPE_POI}. More than one type can be specified. * </p> * * @param geocodingTypes optionally filter the result types by one or more defined types inside * the {@link GeocodingTypeCriteria} * @return this builder for chaining options together * @since 1.0.0 */ public Builder geocodingTypes(@NonNull @GeocodingTypeCriteria String... geocodingTypes) { geocodingTypes(TextUtils.join(",", geocodingTypes)); return this; } abstract Builder geocodingTypes(String geocodingTypes); /** * Add a single country locale to restrict the results. This method can be called as many times * as needed inorder to add multiple countries. * * @param country limit geocoding results to one * @return this builder for chaining options together * @since 3.0.0 */ public Builder country(Locale country) { countries.add(country.getCountry()); return this; } /** * Limit results to one or more countries. Options are ISO 3166 alpha 2 country codes separated * by commas. * * @param country limit geocoding results to one * @return this builder for chaining options together * @since 3.0.0 */ public Builder country(String... country) { countries.addAll(Arrays.asList(country)); return this; } /** * Limit results to one or more countries. Options are ISO 3166 alpha 2 country codes separated * by commas. * * @param country limit geocoding results to one * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder country(String country); /** * This controls whether autocomplete results are included. Autocomplete results can partially * match the query: for example, searching for {@code washingto} could include washington even * though only the prefix matches. Autocomplete is useful for offering fast, type-ahead results * in user interfaces. * <p> * If your queries represent complete addresses or place names, you can disable this behavior * and exclude partial matches by setting this to false, the defaults true. * * @param autocomplete optionally set whether to allow returned results to attempt prediction of * the full words prior to the user completing the search terms * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder autocomplete(Boolean autocomplete); /** * Limit the results to a defined bounding box. Unlike {@link #proximity()}, this will strictly * limit results to within the bounding box only. If simple biasing is desired rather than a * strict region, use proximity instead. * * @param bbox the bounding box as a {@link BoundingBox} * @return this builder for chaining options together * @since 4.7.0 */ public Builder bbox(BoundingBox bbox) { bbox(bbox.southwest().longitude(), bbox.southwest().latitude(), bbox.northeast().longitude(), bbox.northeast().latitude()); return this; } /** * Limit the results to a defined bounding box. Unlike {@link #proximity()}, this will strictly * limit results to within the bounding box only. If simple biasing is desired rather than a * strict region, use proximity instead. * * @param northeast the northeast corner of the bounding box as a {@link Point} * @param southwest the southwest corner of the bounding box as a {@link Point} * @return this builder for chaining options together * @since 1.0.0 */ public Builder bbox(Point southwest, Point northeast) { bbox(southwest.longitude(), southwest.latitude(), northeast.longitude(), northeast.latitude()); return this; } /** * Limit the results to a defined bounding box. Unlike {@link #proximity()}, this will strictly * limit results to within the bounding box only. If simple biasing is desired rather than a * strict region, use proximity instead. * * @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 this builder for chaining options together * @since 1.0.0 */ public Builder bbox(@FloatRange(from = -180, to = 180) double minX, @FloatRange(from = -90, to = 90) double minY, @FloatRange(from = -180, to = 180) double maxX, @FloatRange(from = -90, to = 90) double maxY) { bbox(String.format(Locale.US, "%s,%s,%s,%s", TextUtils.formatCoordinate(minX), TextUtils.formatCoordinate(minY), TextUtils.formatCoordinate(maxX), TextUtils.formatCoordinate(maxY)) ); return this; } /** * Limit the results to a defined bounding box. Unlike {@link #proximity()}, this will strictly * limit results to within the bounding box only. If simple biasing is desired rather than a * strict region, use proximity instead. * * @param bbox a String defining the bounding box for biasing results ordered in * {@code minX,minY,maxX,maxY} * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder bbox(@NonNull String bbox); /** * This optionally specifies the maximum number of results to return. For forward geocoding, the * default is 5 and the maximum is 10. For reverse geocoding, the default is 1 and the maximum * is 5. If a limit other than 1 is used for reverse geocoding, a single types option must also * be specified. * * @param limit the number of returned results * @return this builder for chaining options together * @since 2.0.0 */ public Builder limit(@IntRange(from = 1, to = 10) int limit) { limit(String.valueOf(limit)); return this; } abstract Builder limit(String limit); /** * This optionally specifies the desired response language for user queries. For forward * geocodes, results that match the requested language are favored over results in other * languages. If more than one language tag is supplied, text in all requested languages will be * returned. For forward geocodes with more than one language tag, only the first language will * be used to weight results. * <p> * Any valid IETF language tag can be submitted, and a best effort will be made to return * results in the requested language or languages, falling back first to similar and then to * common languages in the event that text is not available in the requested language. In the * event a fallback language is used, the language field will have a different value than the * one requested. * <p> * Translation availability varies by language and region, for a full list of supported regions, * see the link provided below. * * @param languages one or more locale's specifying the language you'd like results to support * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/search/#language-coverage">Supported languages * </a> * @since 2.0.0 */ public Builder languages(Locale... languages) { String[] languageStrings = new String[languages.length]; for (int i = 0; i < languages.length; i++) { languageStrings[i] = languages[i].getLanguage(); } languages(TextUtils.join(",", languageStrings)); return this; } /** * This optionally specifies the desired response language for user queries. For forward * geocodes, results that match the requested language are favored over results in other * languages. If more than one language tag is supplied, text in all requested languages will be * returned. For forward geocodes with more than one language tag, only the first language will * be used to weight results. * <p> * Any valid IETF language tag can be submitted, and a best effort will be made to return * results in the requested language or languages, falling back first to similar and then to * common languages in the event that text is not available in the requested language. In the * event a fallback language is used, the language field will have a different value than the * one requested. * <p> * Translation availability varies by language and region, for a full list of supported regions, * see the link provided below. * * @param languages a String specifying the language or languages you'd like results to support * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/search/#language-coverage">Supported languages * </a> * @since 2.0.0 */ public abstract Builder languages(String languages); /** * Set the factors that are used to sort nearby results. * Options avaliable to pass in include, {@link GeocodingCriteria#REVERSE_MODE_DISTANCE} for * nearest feature result (default) or {@link GeocodingCriteria#REVERSE_MODE_SCORE} * the notability of features within approximately 1 kilometer of the queried point * along with proximity. * * @param reverseMode limit geocoding results based on the reverseMode * @return this builder for chaining options together * @since 3.3.0 */ public abstract Builder reverseMode( @Nullable @GeocodingCriteria.GeocodingReverseModeCriteria String reverseMode); /** * Specify whether the Geocoding API should attempt approximate, as well as exact, * matching when performing searches (true, default), or whether it should opt out * of this behavior and only attempt exact matching (false). For example, the default * setting might return Washington, DC for a query of <code>wahsington</code>, even * though the query was misspelled. * * @param fuzzyMatch optionally set whether to allow the geocoding API to attempt * exact matching or not. * @return this builder for chaining options together * @since 4.9.0 */ public abstract Builder fuzzyMatch(Boolean fuzzyMatch); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Geocoding API * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); abstract NbmapGeocoding autoBuild(); /** * Specify the two street names for intersection search. * * @param streetOneName First street name of the intersection * @param streetTwoName Second street name of the intersection * @return this builder for chaining options together * @since 4.9.0 */ public Builder intersectionStreets(@NonNull String streetOneName, @NonNull String streetTwoName) { intersectionStreets.add(streetOneName); intersectionStreets.add(streetTwoName); return this; } /** * Build a new {@link NbmapGeocoding} object. * * @return a new {@link NbmapGeocoding} using the provided values in this builder * @since 3.0.0 */ public NbmapGeocoding build() { if (!countries.isEmpty()) { country(TextUtils.join(",", countries.toArray())); } if (intersectionStreets.size() == 2) { query(TextUtils.join(" and ", intersectionStreets.toArray())); geocodingTypes(GeocodingCriteria.TYPE_ADDRESS); } // Generate build so that we can check that values are valid. NbmapGeocoding geocoding = autoBuild(); if (!NbmapUtils.isAccessTokenValid(geocoding.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } if (geocoding.query().isEmpty()) { throw new ServicesException("A query with at least one character or digit is required."); } if (geocoding.reverseMode() != null && geocoding.limit() != null && !geocoding.limit().equals("1")) { throw new ServicesException("Limit must be combined with a single type parameter"); } if (intersectionStreets.size() == 2) { if (!(geocoding.mode().equals(GeocodingCriteria.MODE_PLACES) || geocoding.mode().equals(GeocodingCriteria.MODE_PLACES_PERMANENT))) { throw new ServicesException("Geocoding mode must be GeocodingCriteria.MODE_PLACES " + "or GeocodingCriteria.MODE_PLACES_PERMANENT for intersection search."); } if (TextUtils.isEmpty(geocoding.geocodingTypes()) || !geocoding.geocodingTypes().equals(GeocodingCriteria.TYPE_ADDRESS)) { throw new ServicesException("Geocoding type must be set to Geocoding " + "Criteria.TYPE_ADDRESS for intersection search."); } if (TextUtils.isEmpty(geocoding.proximity())) { throw new ServicesException("Geocoding proximity must be set for intersection search."); } } return geocoding; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/SingleElementSafeListTypeAdapter.java
package com.nbmap.api.geocoding.v5; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.$Gson$Types; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import com.google.gson.stream.MalformedJsonException; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * Similar to {@link com.google.gson.internal.bind.CollectionTypeAdapterFactory}, * safely adapts single element list represented as Json object or primitive. * * Note: unlike {@link com.google.gson.internal.bind.CollectionTypeAdapterFactory}, * this adapter does not perform advanced type analyse and always returns instance of ArrayList * which may not work if it is used to deserialize JSON elements into another subtype of List * (LinkedList for example). * * @param <E> collection element type * * @since 5.4.0 */ class SingleElementSafeListTypeAdapter<E> extends TypeAdapter<List<E>> { static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) { final Class<? super T> rawType = typeToken.getRawType(); if (!List.class.isAssignableFrom(rawType)) { return null; } final Type elementType = $Gson$Types.getCollectionElementType(typeToken.getType(), rawType); final TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType)); @SuppressWarnings("unchecked") final TypeAdapter<T> adapter = (TypeAdapter<T>) new SingleElementSafeListTypeAdapter<>(elementTypeAdapter); return adapter; } }; private final TypeAdapter<E> elementTypeAdapter; private SingleElementSafeListTypeAdapter(final TypeAdapter<E> elementTypeAdapter) { this.elementTypeAdapter = elementTypeAdapter; } @Override public List<E> read(final JsonReader in) throws IOException { final JsonToken token = in.peek(); final List<E> elements = new ArrayList<>(); switch (token) { case BEGIN_ARRAY: in.beginArray(); while (in.hasNext()) { elements.add(elementTypeAdapter.read(in)); } in.endArray(); return elements; case BEGIN_OBJECT: case STRING: case NUMBER: case BOOLEAN: elements.add(elementTypeAdapter.read(in)); return elements; case NULL: in.nextNull(); return null; case NAME: case END_ARRAY: case END_OBJECT: case END_DOCUMENT: throw new MalformedJsonException("Unexpected token: " + token); default: throw new IllegalStateException("Unprocessed token: " + token); } } @Override public void write(final JsonWriter out, final List<E> value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginArray(); for (E element : value) { elementTypeAdapter.write(out, element); } out.endArray(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/package-info.java
/** * Contains the Nbmap Java Services classes related to the Nbmap Geocoding API. */ package com.nbmap.api.geocoding.v5;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/models/CarmenContext.java
package com.nbmap.api.geocoding.v5.models; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Array representing a hierarchy of parents. Each parent includes id, text keys along with * (if avaliable) a wikidata, short_code, and Maki key. * * @see <a href="https://github.com/nbmap/carmen/blob/master/carmen-geojson.md">Carmen Geojson information</a> * @see <a href="https://www.nbmap.com/api-documentation/search/#geocoding">Nbmap geocoder documentation</a> * @since 1.0.0 */ @AutoValue public abstract class CarmenContext implements Serializable { /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ public static Builder builder() { return new AutoValue_CarmenContext.Builder(); } /** * Create a CarmenContext object from JSON. * * @param json string of JSON making up a carmen context * @return this class using the defined information in the provided JSON string * @since 3.0.0 */ @SuppressWarnings("unused") public static CarmenContext fromJson(@NonNull String json) { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) .create(); return gson.fromJson(json, CarmenContext.class); } /** * ID of the feature of the form {index}.{id} where index is the id/handle of the data-source * that contributed the result. * * @return string containing the ID * @since 1.0.0 */ @Nullable public abstract String id(); /** * A string representing the feature. * * @return text representing the feature (e.g. "Austin") * @since 1.0.0 */ @Nullable public abstract String text(); /** * The ISO 3166-1 country and ISO 3166-2 region code for the returned feature. * * @return a String containing the country or region code * @since 1.0.0 */ @Nullable @SerializedName("short_code") public abstract String shortCode(); /** * The WikiData identifier for a country, region or place. * * @return a unique identifier WikiData uses to query and gather more information about this * specific feature * @since 1.2.0 */ @Nullable public abstract String wikidata(); /** * provides the categories that define this features POI if applicable. * * @return comma-separated list of categories applicable to a poi * @since 1.0.0 */ @Nullable public abstract String category(); /** * Suggested icon mapping from the most current version of the Maki project for a poi feature, * based on its category. Note that this doesn't actually return the image but rather the * identifier which can be used to download the correct image manually. * * @return string containing the recommended Maki icon * @since 1.2.0 */ @Nullable public abstract String maki(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<CarmenContext> typeAdapter(Gson gson) { return new AutoValue_CarmenContext.GsonTypeAdapter(gson); } /** * This takes the currently defined values found inside this instance and converts it to a JSON * string. * * @return a JSON string which represents this CarmenContext * @since 3.0.0 */ @SuppressWarnings("unused") public String toJson() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) .create(); return gson.toJson(this); } /** * Convert current instance values into another Builder to quickly change one or more values. * * @return a new instance of {@link CarmenContext} using the newly defined values * @since 3.0.0 */ @SuppressWarnings("unused") public abstract Builder toBuilder(); /** * This builder can be used to set the values describing the {@link CarmenFeature}. * * @since 3.0.0 */ @AutoValue.Builder @SuppressWarnings("unused") public abstract static class Builder { /** * ID of the feature of the form {index}.{id} where index is the id/handle of the data-source * that contributed the result. * * @param id string containing the ID * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder id(@Nullable String id); /** * A string representing the feature. * * @param text representing the feature (e.g. "Austin") * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder text(String text); /** * The ISO 3166-1 country and ISO 3166-2 region code for the returned feature. * * @param shortCode a String containing the country or region code * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder shortCode(@Nullable String shortCode); /** * The WikiData identifier for a country, region or place. * * @param wikidata a unique identifier WikiData uses to query and gather more information about * this specific feature * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder wikidata(@Nullable String wikidata); /** * provides the categories that define this features POI if applicable. * * @param category comma-separated list of categories applicable to a poi * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder category(@Nullable String category); /** * Suggested icon mapping from the most current version of the Maki project for a poi feature, * based on its category. Note that this doesn't actually return the image but rather the * identifier which can be used to download the correct image manually. * * @param maki string containing the recommended Maki icon * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder maki(@Nullable String maki); /** * Build a new {@link CarmenContext} object. * * @return a new {@link CarmenContext} using the provided values in this builder * @since 3.0.0 */ public abstract CarmenContext build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/models/CarmenFeature.java
package com.nbmap.api.geocoding.v5.models; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import com.nbmap.api.geocoding.v5.GeocodingCriteria.GeocodingTypeCriteria; import com.nbmap.geojson.BoundingBox; import com.nbmap.geojson.Feature; import com.nbmap.geojson.GeoJson; import com.nbmap.geojson.Geometry; import com.nbmap.geojson.GeometryAdapterFactory; import com.nbmap.geojson.Point; import com.nbmap.geojson.gson.BoundingBoxTypeAdapter; import java.util.List; /** * The Features key in the geocoding API response contains the majority of information you'll want * to use. It extends the {@link GeoJson} object in GeoJSON and adds several additional attribute * which further describe the geocoding result. * <p> * A Geocoding id is a String in the form {@code {type}.{id}} where {@code {type}} is the lowest * hierarchy feature in the place_type field. The {id} suffix of the feature id is unstable and * may change within versions. * <p> * Note: this class doesn't actually extend Feature due to the inherit rule in AutoValue (see link * below). * * @see <a href="https://github.com/nbmap/carmen/blob/master/carmen-geojson.md">Carmen Geojson information</a> * @see <a href="https://www.nbmap.com/api-documentation/search/#geocoding">Nbmap geocoder documentation</a> * @see <a href='geojson.org/geojson-spec.html#feature-objects'>Official GeoJson Feature Specifications</a> * @see <a href="https://github.com/google/auto/blob/master/value/userguide/howto.md#inherit">AutoValue inherit rule</a> * @since 1.0.0 */ @AutoValue public abstract class CarmenFeature implements GeoJson { private static final String TYPE = "Feature"; /** * Create a CarmenFeature object from JSON. * * @param json string of JSON making up a carmen feature * @return this class using the defined information in the provided JSON string * @since 2.0.0 */ @NonNull public static CarmenFeature fromJson(@NonNull String json) { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeometryAdapterFactory.create()) .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()) .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) .create(); CarmenFeature feature = gson.fromJson(json, CarmenFeature.class); // Even thought properties are Nullable, // Feature object will be created with properties set to an empty object, return feature.properties() == null ? feature.toBuilder().properties(new JsonObject()).build() : feature; } /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ @NonNull public static Builder builder() { return new AutoValue_CarmenFeature.Builder() .type(TYPE) .properties(new JsonObject()); } // // Feature specific attributes // // Note that CarmenFeature cannot extend Feature due to AutoValue limitations /** * This describes the TYPE of GeoJson geometry this object is, thus this will always return * {@link Feature}. * * @return a String which describes the TYPE of geometry, for this object it will always return * {@code Feature} * @since 1.0.0 */ @NonNull @SerializedName("type") @Override public abstract String type(); /** * A {@link CarmenFeature} might have a member named {@code bbox} to include information on the * coordinate range for it's {@link Geometry}. The value of the bbox member MUST be a list of * size 2*n where n is the number of dimensions represented in the contained feature geometries, * with all axes of the most southwesterly point followed by all axes of the more northeasterly * point. The axes order of a bbox follows the axes order of geometries. * * @return a {@link BoundingBox} object containing the information * @since 3.0.0 */ @Nullable @Override public abstract BoundingBox bbox(); /** * A feature may have a commonly used identifier which is either a unique String or number. * * @return a String containing this features unique identification or null if one wasn't given * during creation. * @since 1.0.0 */ @Nullable public abstract String id(); /** * The geometry which makes up this feature. A Geometry object represents points, curves, and * surfaces in coordinate space. One of the seven geometries provided inside this library can be * passed in through one of the static factory methods. * * @return a single defined {@link Geometry} which makes this feature spatially aware * @since 1.0.0 */ @Nullable public abstract Geometry geometry(); /** * This contains the JSON object which holds the feature properties. The value of the properties * member is a {@link JsonObject} and might be empty if no properties are provided. * * @return a {@link JsonObject} which holds this features current properties * @since 1.0.0 */ @Nullable public abstract JsonObject properties(); // // CarmenFeature specific attributes // /** * A string representing the feature in the requested language, if specified. * * @return text representing the feature (e.g. "Austin") * @since 1.0.0 */ @Nullable public abstract String text(); /** * A string representing the feature in the requested language, if specified, and its full result * hierarchy. * * @return human-readable text representing the full result hierarchy (e.g. "Austin, Texas, * United States") * @since 1.0.0 */ @Nullable @SerializedName("place_name") public abstract String placeName(); /** * A list of feature types describing the feature. Options are one of the following types defined * in the {@link GeocodingTypeCriteria}. Most features have only one type, but if the feature has * multiple types, (for example, Vatican City is a country, region, and place), all applicable * types will be provided in the list. * * @return a list containing the place type * @since 1.0.0 */ @Nullable @SerializedName("place_type") public abstract List<String> placeType(); /** * A string of the house number for the returned {@code address} feature. Note that unlike the * address property for {@code poi} features, this property is outside the properties object. * * @return while the string content isn't guaranteed, and might return null, in many cases, this * will be the house number * @since 1.0.0 */ @Nullable public abstract String address(); /** * A {@link Point} object which represents the center point inside the {@link #bbox()} if one is * provided. * * @return a GeoJson {@link Point} which defines the center location of this feature * @since 1.0.0 */ @Nullable public Point center() { // Store locally since rawCenter() is mutable double[] center = rawCenter(); if (center != null && center.length == 2) { return Point.fromLngLat(center[0], center[1]); } return null; } // No public access thus, we lessen enforcement on mutability here. @Nullable @SerializedName("center") @SuppressWarnings("mutable") abstract double[] rawCenter(); /** * A list representing the hierarchy of encompassing parent features. This is where you can find * telephone, address, and other information pertaining to this feature. * * @return a list made up of {@link CarmenContext} which might contain additional information * about this specific feature * @since 1.0.0 */ @Nullable public abstract List<CarmenContext> context(); /** * A numerical score from 0 (least relevant) to 0.99 (most relevant) measuring how well each * returned feature matches the query. You can use this property to remove results which don't * fully match the query. * * @return the relevant score between 0 and 1 * @since 1.0.0 */ @Nullable public abstract Double relevance(); /** * A string analogous to the {@link #text()} field that more closely matches the query than * results in the specified language. For example, querying &quot;K&#246;ln, Germany&quot; with * language set to English might return a feature with the {@link #text()} &quot;Cologne&quot; * and this would be &quot;K&#246;ln&quot;. * * @return a string containing the matching text * @since 2.2.0 */ @Nullable @SerializedName("matching_text") public abstract String matchingText(); /** * A string analogous to the {@link #placeName()} field that more closely matches the query than * results in the specified language. For example, querying "K&#246;ln, Germany" with language * set to English might return a feature with the {@link #placeName()} "Cologne, Germany" * and this would return "K&#246;ln, North Rhine-Westphalia, Germany". * * @return a string containing the matching place name * @since 2.2.0 */ @Nullable @SerializedName("matching_place_name") public abstract String matchingPlaceName(); /** * A string of the IETF language tag of the query's primary language. * * @return string containing the query's primary language * @see <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IETF language tag Wikipedia page</a> * @since 2.2.0 */ @Nullable public abstract String language(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<CarmenFeature> typeAdapter(Gson gson) { return new AutoValue_CarmenFeature.GsonTypeAdapter(gson); } /** * This takes the currently defined values found inside this instance and converts it to a JSON * string. * * @return a JSON string which represents this CarmenFeature * @since 3.0.0 */ @Override @SuppressWarnings("unused") public String toJson() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeometryAdapterFactory.create()) .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()) .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) .create(); // Empty properties -> should not appear in json string CarmenFeature feature = this; if (properties() != null && properties().size() == 0) { feature = toBuilder().properties(null).build(); } return gson.toJson(feature, CarmenFeature.class); } /** * Convert current instance values into another Builder to quickly change one or more values. * * @return a new instance of {@link CarmenFeature} using the newly defined values * @since 3.0.0 */ @SuppressWarnings("unused") public abstract Builder toBuilder(); /** * This builder can be used to set the values describing the {@link CarmenFeature}. * * @since 3.0.0 */ @AutoValue.Builder @SuppressWarnings("unused") public abstract static class Builder { // Type will always be set to "Feature" abstract Builder type(@NonNull String type); /** * A Feature might have a member named {@code bbox} to include information on the coordinate * range for it's {@link Feature}s. The value of the bbox member MUST be a list of size 2*n * where n is the number of dimensions represented in the contained feature geometries, with all * axes of the most southwesterly point followed by all axes of the more northeasterly point. * The axes order of a bbox follows the axes order of geometries. * * @param bbox a list of double coordinate values describing a bounding box * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder bbox(@Nullable BoundingBox bbox); /** * A feature may have a commonly used identifier which is either a unique String or number. * * @param id a String containing this features unique identification or null if one wasn't given * during creation. * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder id(@Nullable String id); /** * The geometry which makes up this feature. A Geometry object represents points, curves, and * surfaces in coordinate space. One of the seven geometries provided inside this library can be * passed in through one of the static factory methods. * * @param geometry a single defined {@link Geometry} which makes this feature spatially aware * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder geometry(@Nullable Geometry geometry); /** * This contains the JSON object which holds the feature properties. The value of the properties * member is a {@link JsonObject} and might be empty if no properties are provided. * * @param properties a {@link JsonObject} which holds this features current properties * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder properties(@Nullable JsonObject properties); /** * A string representing the feature in the requested language. * * @param text text representing the feature (e.g. "Austin") * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder text(@Nullable String text); /** * A string representing the feature in the requested language, if specified, and its full * result hierarchy. * * @param placeName human-readable text representing the full result hierarchy (e.g. "Austin, * Texas, United States") * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder placeName(@Nullable String placeName); /** * A list of feature types describing the feature. Options are one of the following types * defined in the {@link GeocodingTypeCriteria}. Most features have only one type, but if the * feature has multiple types, (for example, Vatican City is a country, region, and place), all * applicable types will be provided in the list. * * @param placeType a list containing the place type * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder placeType(@Nullable List<String> placeType); /** * A string of the house number for the returned {@code address} feature. Note that unlike the * address property for {@code poi} features, this property is outside the properties object. * * @param address while the string content isn't guaranteed, and might return null, in many * cases, this will be the house number * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder address(@Nullable String address); /** * A {@link Point} object which represents the center point inside the {@link #bbox()} if one is * provided. * * @param center a GeoJson {@link Point} which defines the center location of this feature * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder rawCenter(@Nullable double[] center); /** * A list representing the hierarchy of encompassing parent features. This is where you can find * telephone, address, and other information pertaining to this feature. * * @param contexts a list made up of {@link CarmenContext} which might contain additional * information about this specific feature * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder context(@Nullable List<CarmenContext> contexts); /** * A numerical score from 0 (least relevant) to 0.99 (most relevant) measuring how well each * returned feature matches the query. You can use this property to remove results which don't * fully match the query. * * @param relevance the relevant score between 0 and 1 * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder relevance(@Nullable Double relevance); /** * A string analogous to the {@link #text()} field that more closely matches the query than * results in the specified language. For example, querying "K&#246;ln, Germany" with language * set to English might return a feature with the {@link #text()} "Cologne" and this * would be "K&#246;ln". * * @param matchingText a string containing the matching text * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder matchingText(@Nullable String matchingText); /** * A string analogous to the {@link #placeName()} field that more closely matches the query than * results in the specified language. For example, querying "K&#246;ln, Germany" with language * set to English might return a feature with the {@link #placeName()} "Cologne, Germany" * and this would return "K&#246;ln, North Rhine-Westphalia, Germany". * * @param matchingPlaceName a string containing the matching place name * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder matchingPlaceName(@Nullable String matchingPlaceName); /** * A string of the IETF language tag of the query's primary language. * * @param language string containing the query's primary language * @return this builder for chaining options together * @see <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IETF language tag Wikipedia page</a> * @since 2.2.0 */ public abstract Builder language(@Nullable String language); /** * Build a new {@link CarmenFeature} object. * * @return a new {@link CarmenFeature} using the provided values in this builder * @since 3.0.0 */ public abstract CarmenFeature build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/models/GeocodingAdapterFactory.java
package com.nbmap.api.geocoding.v5.models; import com.google.gson.TypeAdapterFactory; import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory; /** * A Geocoding type adapter factory for convenience when using AutoValue and handling * serialization/deserialization. The majority of this class gets generated during compilation time. * * @since 3.0.0 */ @GsonTypeAdapterFactory public abstract class GeocodingAdapterFactory implements TypeAdapterFactory { /** * Create a new instance of this Geocoding type adapter factory, this is passed into the Gson * Builder. * * @return a new GSON TypeAdapterFactory * @since 3.0.0 */ public static TypeAdapterFactory create() { return new AutoValueGson_GeocodingAdapterFactory(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/models/GeocodingResponse.java
package com.nbmap.api.geocoding.v5.models; import androidx.annotation.NonNull; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.nbmap.geojson.BoundingBox; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.GeometryAdapterFactory; import com.nbmap.geojson.gson.BoundingBoxTypeAdapter; import java.io.Serializable; import java.util.List; /** * This is the initial object which gets returned when the geocoding request receives a result. * Since each result is a {@link CarmenFeature}, the response simply returns a list of those * features. * * @since 1.0.0 */ @AutoValue public abstract class GeocodingResponse implements Serializable { private static final String TYPE = "FeatureCollection"; /** * Create a new instance of this class by passing in a formatted valid JSON String. * * @param json a formatted valid JSON string defining a GeoJson Geocoding Response * @return a new instance of this class defined by the values passed inside this static factory * method * @since 3.0.0 */ @NonNull public static GeocodingResponse fromJson(@NonNull String json) { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeometryAdapterFactory.create()) .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()) .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) .create(); return gson.fromJson(json, GeocodingResponse.class); } /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ @NonNull public static Builder builder() { return new AutoValue_GeocodingResponse.Builder() .type(TYPE); } /** * A geocoding response will always be an extension of a {@link FeatureCollection} containing * additional information. * * @return the type of GeoJSON this is * @since 1.0.0 */ @NonNull public abstract String type(); /** * A list of space and punctuation-separated strings from the original query. * * @return a list containing the original query * @since 1.0.0 */ @NonNull public abstract List<String> query(); /** * A list of the CarmenFeatures which contain the results and are ordered from most relevant to * least. * * @return a list of {@link CarmenFeature}s which each represent an individual result from the * query * @since 1.0.0 */ @NonNull public abstract List<CarmenFeature> features(); /** * A string attributing the results of the Nbmap Geocoding API to Nbmap and links to Nbmap's * terms of service and data sources. * * @return information about Nbmap's terms of service and the data sources * @since 1.0.0 */ @NonNull public abstract String attribution(); /** * Convert the current {@link GeocodingResponse} to its builder holding the currently assigned * values. This allows you to modify a single variable and then rebuild the object resulting in * an updated and modified {@link GeocodingResponse}. * * @return a {@link GeocodingResponse.Builder} with the same values set to match the ones defined * in this {@link GeocodingResponse} * @since 3.0.0 */ @NonNull public abstract Builder toBuilder(); /** * This takes the currently defined values found inside this instance and converts it to a GeoJson * string. * * @return a JSON string which represents this Geocoding Response * @since 1.0.0 */ @NonNull public String toJson() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeometryAdapterFactory.create()) .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()) .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) .create(); return gson.toJson(this, GeocodingResponse.class); } /** * Gson TYPE adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the TYPE adapter for this class * @since 3.0.0 */ public static TypeAdapter<GeocodingResponse> typeAdapter(Gson gson) { return new AutoValue_GeocodingResponse.GsonTypeAdapter(gson); } /** * This builder can be used to set the values describing the {@link GeocodingResponse}. * * @since 3.0.0 */ @AutoValue.Builder @SuppressWarnings("unused") public abstract static class Builder { /** * This describes the TYPE of GeoJson geometry this object is, thus this will always return * {@link FeatureCollection}. Note that this isn't public since it should always be set to * "FeatureCollection" * * @param type a String which describes the TYPE of geometry, for this object it will always * return {@code FeatureCollection} * @return this builder for chaining options together * @since 3.0.0 */ abstract Builder type(@NonNull String type); /** * A list of space and punctuation-separated strings from the original query. * * @param query a list containing the original query * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder query(@NonNull List<String> query); /** * A list of the CarmenFeatures which contain the results and are ordered from most relevant to * least. * * @param features a list of {@link CarmenFeature}s which each represent an individual result * from the query * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder features(@NonNull List<CarmenFeature> features); /** * A string attributing the results of the Nbmap Geocoding API to Nbmap and links to Nbmap's * terms of service and data sources. * * @param attribution information about Nbmap's terms of service and the data sources * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder attribution(@NonNull String attribution); /** * Build a new {@link GeocodingResponse} object. * * @return a new {@link GeocodingResponse} using the provided values in this builder * @since 3.0.0 */ public abstract GeocodingResponse build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/geocoding/v5/models/package-info.java
/** * Contains the Geocoding Response model classes which are useful when working with the requested * results. */ package com.nbmap.api.geocoding.v5.models;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/isochrone/IsochroneCriteria.java
package com.nbmap.api.isochrone; import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Constants that should be used when using the Isochrone API. * * @since 4.6.0 */ public class IsochroneCriteria { /** * Nbmap default username. * * @since 4.7.0 */ public static final String PROFILE_DEFAULT_USER = "nbmap"; /** * For walking routing. This profile shows routes that are short and safe for cyclist, avoiding * highways and preferring streets with bike lanes. * * @since 4.6.0 */ public static final String PROFILE_WALKING = "walking"; /** * For car routing. This profile shows the fastest routes by * preferring high-speed roads like highways. * * @since 4.6.0 */ public static final String PROFILE_DRIVING = "driving"; /** * For bicycle routing. This profile shows routes that are short and safe for cyclist, avoiding * highways and preferring streets with bike lanes. * * @since 4.6.0 */ public static final String PROFILE_CYCLING = "cycling"; /** * Queries for a specific geometry type selector. * * @since 4.6.0 */ @Retention(RetentionPolicy.CLASS) @StringDef( { PROFILE_WALKING, PROFILE_DRIVING, PROFILE_CYCLING }) public @interface IsochroneProfile { } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/isochrone/IsochroneService.java
package com.nbmap.api.isochrone; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.Point; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the Isochrone API service. * * @since 4.6.0 */ public interface IsochroneService { /** * Constructs the HTTP request for the specified parameters. * * @param user The username for the account that the Isochrone engine runs on. * In most cases, this should always remain the default value of * {@link IsochroneCriteria#PROFILE_DEFAULT_USER}. * @param profile A Nbmap Directions routing profile ID. Options are * {@link IsochroneCriteria#PROFILE_DRIVING} for travel times * by car, {@link IsochroneCriteria#PROFILE_WALKING} for pedestrian * and hiking travel times,and {@link IsochroneCriteria#PROFILE_CYCLING} * for travel times by bicycle. * @param coordinates A {@link Point} object which represents a * {longitude,latitude} coordinate pair around which to center * the isochrone lines. * @param contoursMinutes A single String which has a comma-separated time in minutes to use for * each isochrone contour. * @param accessToken A valid Nbmap access token. * @param contoursColors The colors to use for each isochrone contour, specified as hex values * without a leading # (for example, ff0000 for red). If this parameter is * used, there must be the same number of colors as there are entries in * contours_minutes. If no colors are specified, the Isochrone API will * assign a default rainbow color scheme to the output. * @param polygons Specify whether to return the contours as GeoJSON polygons (true) or * linestrings (false, default). When polygons=true, any contour that * forms a ring is returned as a polygon. * @param denoise A floating point value from 0.0 to 1.0 that can be used to remove * smaller contours. The default is 1.0. A value of 1.0 will only * return the largest contour for a given time value. A value of 0.5 * drops any contours that are less than half the area of the largest * contour in the set of contours for that same time value. * @param generalize A positive floating point value in meters used as the tolerance for * Douglas-Peucker generalization. There is no upper bound. If no value is * specified in the request, the Isochrone API will choose the most * optimized generalization to use for the request. Note that the * generalization of contours can lead to self-intersections, as well * as intersections of adjacent contours. * @return a {@link FeatureCollection} in a Call wrapper * @since 4.7.0 */ @GET("/isochrone/v1/{user}/{profile}/{coordinates}") Call<FeatureCollection> getCall( @Path("user") String user, @Path("profile") String profile, @Path("coordinates") String coordinates, @Query("contours_minutes") String contoursMinutes, @Query("key") String accessToken, @Query("contours_colors") String contoursColors, @Query("polygons") Boolean polygons, @Query("denoise") Float denoise, @Query("generalize") Float generalize); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/isochrone/NbmapIsochrone.java
package com.nbmap.api.isochrone; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.GeometryAdapterFactory; import com.nbmap.geojson.Point; import com.nbmap.geojson.gson.GeoJsonAdapterFactory; import java.util.Locale; import retrofit2.Call; /** * An isochrone, from the Greek root words iso (equal) and chrone (time), is a line that connects * points of equal travel time around a given location. The Nbmap Isochrone API computes areas * that are reachable within a specified amount of time from a location, and returns the reachable * regions as contours of polygons or lines that you can display on a map. * <p> * Given a location and a routing profile, retrieve up to four isochrone contours. The contours * are calculated using rasters and are returned as either polygon or line features, depending * on your input setting for the polygons parameter. * <p> * The Isochrone API is limited to 300 requests per minute. The Isochrone API supports 1 coordinate * per request. The Isochrone API can support a maximum of 4 isochrone contours per request. * The maximum time that can be specified for an isochrone contour is 60 minutes. Results must be * displayed on a Nbmap map using one of the Nbmap libraries or SDKs. If you require a higher * rate limit, contact us. * <p> * * @see <a href="https://docs.nbmap.com/api/navigation/#isochrone">API documentation</a> * @since 4.6.0 */ @AutoValue public abstract class NbmapIsochrone extends NbmapService<FeatureCollection, IsochroneService> { protected NbmapIsochrone() { super(IsochroneService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(GeoJsonAdapterFactory.create()) .registerTypeAdapterFactory(GeometryAdapterFactory.create()); } @Override protected Call<FeatureCollection> initializeCall() { return getService().getCall( user(), profile(), coordinates(), contoursMinutes(), accessToken(), contoursColors(), polygons(), denoise(), generalize() ); } /** * Build a new {@link NbmapIsochrone} object with the initial value set for * {@link #baseUrl()}. * * @return a {@link NbmapIsochrone.Builder} object for creating this object * @since 4.6.0 */ public static Builder builder() { return new AutoValue_NbmapIsochrone.Builder() .baseUrl(Constants.BASE_API_URL) .user(IsochroneCriteria.PROFILE_DEFAULT_USER); } @NonNull @Override protected abstract String baseUrl(); @NonNull abstract String accessToken(); @NonNull abstract String user(); @NonNull abstract String profile(); @NonNull abstract String coordinates(); @NonNull abstract String contoursMinutes(); @Nullable abstract String contoursColors(); @Nullable abstract Boolean polygons(); @Nullable abstract Float denoise(); @Nullable abstract Float generalize(); /** * This builder is used to create a new request to the Nbmap Isochrone API. At a bare minimum, * your request must include an access token, a directions routing profile (driving, walking, * or cycling),and a comma separated list of time for the contours. All other fields can be * left alone in order to use the default behaviour of the API. * <p> * Note to contributors: All optional booleans in this builder use the object {@code Boolean} * rather than the primitive to allow for unset (null) values. * </p> * * @since 4.6.0 */ @AutoValue.Builder public abstract static class Builder { private Integer[] contoursMinutes; private String[] contoursColors; /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 4.6.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * A valid Nbmap access token. * * @param accessToken the Nbmap access token to use for the Isochrone API call * @return this builder for chaining options together * @since 4.6.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * The username for the account that the Isochrone engine runs on. In most cases, this should * always remain the default value of {@link IsochroneCriteria#PROFILE_DEFAULT_USER}. * * @param user a non-null string which will replace the default user used in the Isochrone * request * @return this builder for chaining options together * @since 4.7.0 */ public abstract Builder user(@NonNull String user); /** * A Nbmap Directions routing profile ID. Options are * {@link IsochroneCriteria#PROFILE_DRIVING} for travel times by car, * {@link IsochroneCriteria#PROFILE_WALKING} for pedestrian and hiking travel times, * and {@link IsochroneCriteria#PROFILE_CYCLING} for travel times by bicycle. * * @param profile a Nbmap Directions profile * @return this builder for chaining options together * @since 4.6.0 */ public abstract Builder profile(@Nullable @IsochroneCriteria.IsochroneProfile String profile); /** * A {@link Point} object which represents a {longitude,latitude} coordinate * pair around which to center the isochrone lines. * * @param queryPoint center query point for the isochrone calculation * @return this builder for chaining options together * @since 4.6.0 */ public Builder coordinates(@NonNull Point queryPoint) { coordinates(String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(queryPoint.longitude()), TextUtils.formatCoordinate(queryPoint.latitude()))); return this; } /** * A string which represents a {longitude,latitude} coordinate pair * around which to center the isochrone lines. The String should be * "longitude,latitude". * * @param queryPoint center query point for the isochrone calculation * @return this builder for chaining options together * @since 4.6.0 */ public abstract Builder coordinates(@NonNull String queryPoint); /** * An integer list of minute values to use for each isochrone contour. * You must pass in at least one minute amount and you can specify * up to four contours. Times must be in increasing order. For example, * "5,20,40,50" and not "20,10,40,55". The maximum time that can be * specified is 60 minutes. * * @param listOfMinuteValues an integer list with at least one number * for the minutes which represent each contour * @return this builder for chaining options together * @since 4.6.0 */ public Builder addContoursMinutes(@NonNull @IntRange(from = 0, to = 60) Integer... listOfMinuteValues) { this.contoursMinutes = listOfMinuteValues; return this; } /** * A single String which is a comma-separated list of time(s) in minutes * to use for each isochrone contour. You must pass in at least one minute * amount and you can specify up to four contours. Times must be in increasing order. * For example "5,20,40,50" is valid and "20,10,40,55" is invalid. * The maximum time that can be specified is 60 minutes. * * @param stringListOfMinuteValues a String of at least one number for the * minutes which represent each contour * @return this builder for chaining optio.ns together */ // Required for matching with NbmapIsochrone addContoursMinutes() method. @SuppressWarnings("WeakerAccess") abstract Builder contoursMinutes(@NonNull String stringListOfMinuteValues); /** * A list of separate String which has a list of comma-separated * HEX color values to use for each isochrone contour. * <p> * For example, .contoursColors("6706ce","04e813","4286f4") * <p> * The colors should be specified as hex values without a * leading # (for example, ff0000 for red). If this parameter is * used, there must be the same number of colors as there are entries in * contours_minutes. If no colors are specified, the Isochrone API will * assign a default rainbow color scheme to the output. * * @param contoursColors the list of at least one color value to use for * the polygon fill areas in the API response * @return this builder for chaining options together * @since 4.6.0 */ public Builder addContoursColors(@Nullable String... contoursColors) { this.contoursColors = contoursColors; return this; } // Required for matching with NbmapIsochrone addContoursColors() method. abstract Builder contoursColors(@Nullable String countoursColorList); /** * Specify whether to return the contours as GeoJSON * {@link com.nbmap.geojson.Polygon} (true) or {@link com.nbmap.geojson.LineString} (false). * If no boolean is set, false is the default, which results in * {@link com.nbmap.geojson.LineString} being delivered. * <p> * When polygons=true, any contour that forms a ring is returned as * a {@link com.nbmap.geojson.Polygon}. * * @param polygons a boolean whether you want the API response to include * {@link com.nbmap.geojson.Polygon} geometries to represent the * various contours. * @return this builder for chaining options together * @since 4.6.0 */ public abstract Builder polygons(@Nullable Boolean polygons); /** * A floating point value from 0.0 to 1.0 that can be used to remove smaller contours. * The default is 1.0. A value of 1.0 will only return the largest contour for a given time * value. A value of 0.5 drops any contours that are less than half the area of the * largest contour in the set of contours for that same time value. * * @param denoise an optional number to determine the shape of small contours * @return this builder for chaining options together * @since 4.6.0 */ public abstract Builder denoise(@Nullable @FloatRange(from = 0.0, to = 1.0) Float denoise); /** * A positive floating point value in meters used as the tolerance for Douglas-Peucker * generalization. There is no upper bound. If no value is specified in the request, * the Isochrone API will choose the most optimized generalization to use for the request. * Note that the generalization of contours can lead to self-intersections, as well as * intersections of adjacent contours. * * @param generalize an optional number to determine how smooth or jagged the contour * lines/polygons contours are * @return this builder for chaining options together * @since 4.6.0 */ public abstract Builder generalize(@Nullable @FloatRange(from = 0.0) Float generalize); /** * @return this builder for chaining options together * @since 4.6.0 */ abstract NbmapIsochrone autoBuild(); /** * Build a new {@link NbmapIsochrone} object. * * @return this builder for chaining options together * @since 4.6.0 */ public NbmapIsochrone build() { if (contoursMinutes != null) { if (contoursMinutes.length < 1) { throw new ServicesException("A query with at least one specified " + "minute amount is required."); } if (contoursMinutes.length >= 2) { for (int x = 0; x < contoursMinutes.length - 1; x++) { if (contoursMinutes[x] > contoursMinutes[x + 1]) { throw new ServicesException("The minutes must be listed" + " in order from the lowest number to the highest number."); } } } contoursMinutes(TextUtils.join(",", contoursMinutes)); } if (contoursColors != null) { contoursColors(TextUtils.join(",", contoursColors)); } if (contoursColors != null && contoursMinutes != null && contoursColors.length != contoursMinutes.length) { throw new ServicesException("Number of color elements " + "must match number of minute elements provided."); } NbmapIsochrone isochrone = autoBuild(); if (!NbmapUtils.isAccessTokenValid(isochrone.accessToken())) { throw new ServicesException("Using the Nbmap Isochrone API requires setting " + "a valid access token."); } if (TextUtils.isEmpty(isochrone.coordinates())) { throw new ServicesException("A query with longitude and latitude values is " + "required."); } if (TextUtils.isEmpty(isochrone.profile())) { throw new ServicesException("A query with a set Directions profile (cycling," + " walking, or driving) is required."); } if (TextUtils.isEmpty(isochrone.contoursMinutes())) { throw new ServicesException("A query with at least one specified minute amount" + " is required."); } if (isochrone.contoursColors() != null) { if (isochrone.contoursColors().contains("#")) { throw new ServicesException("Make sure that none of the contour color HEX" + " values have a # in front of it. Provide a list of the HEX values " + "without any # symbols."); } } return isochrone; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/isochrone/package-info.java
/** * Contains the Nbmap Java Services classes related to the Nbmap Isochrone API. */ package com.nbmap.api.isochrone;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/isochrone
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/isochrone/models/package-info.java
/** * Contains the Nbmap Java Services model classes related to the Nbmap Isochrone API. */ package com.nbmap.api.isochrone.models;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/MapMatchingService.java
package com.nbmap.api.matching.v5; import com.nbmap.api.matching.v5.models.MapMatchingResponse; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the map matching service. * * @since 2.0.0 */ public interface MapMatchingService { /** * Constructs the GET call using the information passed in through the * {@link NbmapMapMatching.Builder}. * * @param userAgent user agent * @param user user * @param profile directions profile ID; either nbmap/driving, nbmap/walking, * or nbmap/cycling * @param coordinates inaccurate traces from a GPS unit or a phone * @param accessToken Nbmap access token * @param geometries format of the returned geometry. Allowed values are: geojson * (as LineString), polyline with precision 5, polyline6. The default * value is polyline * @param radiuses a list of integers in meters indicating the assumed precision of * the used tracking device. There must be as many radiuses as there * are coordinates in the request, each separated by ;. Values can be * a number between 0 and 30. Use higher numbers (20-30) for noisy * traces and lower numbers (1-10) for clean traces. The default value * is 5 * @param steps whether to return steps and turn-by-turn instructions. Can be true * or false. The default is false * @param overview type of returned overview geometry. Can be full (the most detailed * geometry available), simplified (a simplified version of the full * geometry), or false (no overview geometry). The default is simplified * @param timestamps timestamps corresponding to each coordinate provided in the request; * must be numbers in Unix time (seconds since the Unix epoch). There * must be as many timestamps as there are coordinates in the request, * each separated by {@code ;} * @param annotations whether or not to return additional metadata for each coordinate * along the match geometry. Can be one or all of 'duration', * 'distance', or 'nodes', each separated by ,. See the response * object for more details on what it is included with annotations * @param language language of returned turn-by-turn text instructions * @param tidy whether or not to transparently remove clusters and re-sample * traces for improved map matching results * @param roundaboutExits Whether or not to emit instructions at roundabout exits. * @param bannerInstructions Whether or not to return banner objects associated with * the `routeSteps`. Should be used in conjunction with `steps`. * @param voiceInstructions whether or not to return * marked-up text for voice guidance along the route. * @param voiceUnits voice units * @param waypointIndices which input coordinates should be treated as waypoints/separate legs. * Note: coordinate indices not added here act as silent waypoints * @param waypointNames custom names for waypoints used for the arrival instruction. * @param approaches which side of the road to approach a waypoint. * @return the MapMatchingResponse in a Call wrapper * @since 2.0.0 */ // @GET("matching/v5/{user}/{profile}/{coordinates}") @GET("snapToRoads/json") Call<MapMatchingResponse> getCall( @Header("User-Agent") String userAgent, @Path("user") String user, @Path("profile") String profile, @Path("coordinates") String coordinates, @Query("key") String accessToken, @Query("geometries") String geometries, @Query("radiuses") String radiuses, @Query("steps") Boolean steps, @Query("overview") String overview, @Query("timestamps") String timestamps, @Query("annotations") String annotations, @Query("language") String language, @Query("tidy") Boolean tidy, @Query("roundabout_exits") Boolean roundaboutExits, @Query("banner_instructions") Boolean bannerInstructions, @Query("voice_instructions") Boolean voiceInstructions, @Query("voice_units") String voiceUnits, @Query("waypoints") String waypointIndices, @Query("waypoint_names") String waypointNames, @Query("approaches") String approaches); /** * Constructs the POST call using the information passed in through the * {@link NbmapMapMatching.Builder}. * * @param userAgent user agent * @param user user * @param profile directions profile ID; either nbmap/driving, nbmap/walking, * or nbmap/cycling * @param coordinates inaccurate traces from a GPS unit or a phone * @param accessToken Nbmap access token * @param geometries format of the returned geometry. Allowed values are: geojson * (as LineString), polyline with precision 5, polyline6. The default * value is polyline * @param radiuses a list of integers in meters indicating the assumed precision of * the used tracking device. There must be as many radiuses as there * are coordinates in the request, each separated by ;. Values can be * a number between 0 and 30. Use higher numbers (20-30) for noisy * traces and lower numbers (1-10) for clean traces. The default value * is 5 * @param steps whether to return steps and turn-by-turn instructions. Can be true * or false. The default is false * @param overview type of returned overview geometry. Can be full (the most detailed * geometry available), simplified (a simplified version of the full * geometry), or false (no overview geometry). The default is simplified * @param timestamps timestamps corresponding to each coordinate provided in the request; * must be numbers in Unix time (seconds since the Unix epoch). There * must be as many timestamps as there are coordinates in the request, * each separated by {@code ;} * @param annotations whether or not to return additional metadata for each coordinate * along the match geometry. Can be one or all of 'duration', * 'distance', or 'nodes', each separated by ,. See the response * object for more details on what it is included with annotations * @param language language of returned turn-by-turn text instructions * @param tidy whether or not to transparently remove clusters and re-sample * traces for improved map matching results * @param roundaboutExits Whether or not to emit instructions at roundabout exits. * @param bannerInstructions Whether or not to return banner objects associated with * the `routeSteps`. Should be used in conjunction with `steps`. * @param voiceInstructions whether or not to return * marked-up text for voice guidance along the route. * @param voiceUnits voice units * @param waypointIndices which input coordinates should be treated as waypoints/separate legs. * Note: coordinate indices not added here act as silent waypoints * @param waypointNames custom names for waypoints used for the arrival instruction. * @param approaches which side of the road to approach a waypoint. * @return the MapMatchingResponse in a Call wrapper * @since 4.4.0 */ @FormUrlEncoded @POST("matching/v5/{user}/{profile}") Call<MapMatchingResponse> postCall( @Header("User-Agent") String userAgent, @Path("user") String user, @Path("profile") String profile, @Field("coordinates") String coordinates, @Query("key") String accessToken, @Field("geometries") String geometries, @Field("radiuses") String radiuses, @Field("steps") Boolean steps, @Field("overview") String overview, @Field("timestamps") String timestamps, @Field("annotations") String annotations, @Field("language") String language, @Field("tidy") Boolean tidy, @Field("roundabout_exits") Boolean roundaboutExits, @Field("banner_instructions") Boolean bannerInstructions, @Field("voice_instructions") Boolean voiceInstructions, @Field("voice_units") String voiceUnits, @Field("waypoints") String waypointIndices, @Field("waypoint_names") String waypointNames, @Field("approaches") String approaches); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/MatchingResponseFactory.java
package com.nbmap.api.matching.v5; import com.nbmap.api.directions.v5.models.RouteOptions; import com.nbmap.api.directions.v5.utils.ParseUtils; import com.nbmap.api.matching.v5.models.MapMatchingMatching; import com.nbmap.api.matching.v5.models.MapMatchingResponse; import com.nbmap.geojson.Point; import java.util.ArrayList; import java.util.List; import retrofit2.Response; /** * @since 4.4.0 */ class MatchingResponseFactory { private static final String PLACEHOLDER_UUID = "mapmatching"; private final NbmapMapMatching nbmapMapMatching; MatchingResponseFactory(NbmapMapMatching nbmapMapMatching) { this.nbmapMapMatching = nbmapMapMatching; } Response<MapMatchingResponse> generate(Response<MapMatchingResponse> response) { if (isNotSuccessful(response)) { return response; } else { return Response.success( response .body() .toBuilder() .matchings(generateRouteOptions(response)) .build(), new okhttp3.Response.Builder() .code(200) .message("OK") .protocol(response.raw().protocol()) .headers(response.headers()) .request(response.raw().request()) .build()); } } private boolean isNotSuccessful(Response<MapMatchingResponse> response) { return !response.isSuccessful() || response.body() == null || response.body().matchings() == null || response.body().matchings().isEmpty(); } private List<MapMatchingMatching> generateRouteOptions(Response<MapMatchingResponse> response) { List<MapMatchingMatching> matchings = response.body().matchings(); List<MapMatchingMatching> modifiedMatchings = new ArrayList<>(); for (MapMatchingMatching matching : matchings) { modifiedMatchings.add(matching.toBuilder().routeOptions( RouteOptions.builder() .profile(nbmapMapMatching.profile()) .coordinates(formatCoordinates(nbmapMapMatching.coordinates())) .annotations(nbmapMapMatching.annotations()) .approachesList(ParseUtils.parseToStrings(nbmapMapMatching.approaches())) .language(nbmapMapMatching.language()) .radiusesList(ParseUtils.parseToDoubles(nbmapMapMatching.radiuses())) .user(nbmapMapMatching.user()) .voiceInstructions(nbmapMapMatching.voiceInstructions()) .bannerInstructions(nbmapMapMatching.bannerInstructions()) .roundaboutExits(nbmapMapMatching.roundaboutExits()) .geometries(nbmapMapMatching.geometries()) .overview(nbmapMapMatching.overview()) .steps(nbmapMapMatching.steps()) .voiceUnits(nbmapMapMatching.voiceUnits()) .requestUuid(PLACEHOLDER_UUID) .accessToken(nbmapMapMatching.accessToken()) .waypointIndicesList(ParseUtils.parseToIntegers(nbmapMapMatching.waypointIndices())) .waypointNamesList(ParseUtils.parseToStrings(nbmapMapMatching.waypointNames())) .baseUrl(nbmapMapMatching.baseUrl()) .build() ).build()); } return modifiedMatchings; } private static List<Point> formatCoordinates(String coordinates) { String[] coordPairs = coordinates.split(";", -1); List<Point> coordinatesFormatted = new ArrayList<>(); for (String coordPair : coordPairs) { String[] coords = coordPair.split(",", -1); coordinatesFormatted.add( Point.fromLngLat(Double.valueOf(coords[0]), Double.valueOf(coords[1]))); } return coordinatesFormatted; } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/NbmapMapMatching.java
package com.nbmap.api.matching.v5; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.api.directions.v5.DirectionsAdapterFactory; import com.nbmap.api.directions.v5.DirectionsCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.AnnotationCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.GeometriesCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.OverviewCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.ProfileCriteria; import com.nbmap.api.directions.v5.utils.FormatUtils; import com.nbmap.api.matching.v5.models.MapMatchingAdapterFactory; import com.nbmap.api.matching.v5.models.MapMatchingResponse; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.ApiCallHelper; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.Point; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * The Nbmap map matching interface (v5) * <p> * The Nbmap Map Matching API snaps fuzzy, inaccurate traces from a GPS unit or a phone to the * OpenStreetMap road and path network using the Directions API. This produces clean paths that can * be displayed on a map or used for other analysis. * * @see <a href="https://www.nbmap.com/api-documentation/navigation/#map-matching">Map matching API * documentation</a> * @since 2.0.0 */ @AutoValue public abstract class NbmapMapMatching extends NbmapService<MapMatchingResponse, MapMatchingService> { protected NbmapMapMatching() { super(MapMatchingService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(MapMatchingAdapterFactory.create()) .registerTypeAdapterFactory(DirectionsAdapterFactory.create()); } @Override protected Call<MapMatchingResponse> initializeCall() { if (usePostMethod() == null) { return callForUrlLength(); } if (usePostMethod()) { return post(); } return get(); } private Call<MapMatchingResponse> callForUrlLength() { Call<MapMatchingResponse> get = get(); if (get.request().url().toString().length() < MAX_URL_SIZE) { return get; } return post(); } private Call<MapMatchingResponse> get() { return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), user(), profile(), coordinates(), accessToken(), geometries(), radiuses(), steps(), overview(), timestamps(), annotations(), language(), tidy(), roundaboutExits(), bannerInstructions(), voiceInstructions(), voiceUnits(), waypointIndices(), waypointNames(), approaches()); } private Call<MapMatchingResponse> post() { return getService().postCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), user(), profile(), coordinates(), accessToken(), geometries(), radiuses(), steps(), overview(), timestamps(), annotations(), language(), tidy(), roundaboutExits(), bannerInstructions(), voiceInstructions(), voiceUnits(), waypointIndices(), waypointNames(), approaches()); } /** * Wrapper method for Retrofits {@link Call#execute()} call returning a response specific to the * Map Matching API. * * @return the Map Matching v5 response once the call completes successfully * @throws IOException Signals that an I/O exception of some sort has occurred * @since 1.0.0 */ @Override public Response<MapMatchingResponse> executeCall() throws IOException { Response<MapMatchingResponse> response = getCall().execute(); MatchingResponseFactory factory = new MatchingResponseFactory(NbmapMapMatching.this); return factory.generate(response); } /** * Wrapper method for Retrofits {@link Call#enqueue(Callback)} call returning a response specific * to the Map Matching API. Use this method to make a directions request on the Main Thread. * * @param callback a {@link Callback} which is used once the {@link MapMatchingResponse} is * created. * @since 1.0.0 */ @Override public void enqueueCall(final Callback<MapMatchingResponse> callback) { getCall().enqueue(new Callback<MapMatchingResponse>() { @Override public void onResponse(Call<MapMatchingResponse> call, Response<MapMatchingResponse> response) { MatchingResponseFactory factory = new MatchingResponseFactory(NbmapMapMatching.this); Response<MapMatchingResponse> generatedResponse = factory.generate(response); callback.onResponse(call, generatedResponse); } @Override public void onFailure(Call<MapMatchingResponse> call, Throwable throwable) { callback.onFailure(call, throwable); } }); } @Nullable abstract Boolean usePostMethod(); @Nullable abstract String clientAppName(); @NonNull abstract String accessToken(); @Nullable abstract Boolean tidy(); @NonNull abstract String user(); @NonNull abstract String profile(); @NonNull abstract String coordinates(); @Nullable abstract String geometries(); @Nullable abstract String radiuses(); @Nullable abstract Boolean steps(); @Nullable abstract String overview(); @Nullable abstract String timestamps(); @Nullable abstract String annotations(); @Nullable abstract String language(); @Nullable abstract Boolean roundaboutExits(); @Nullable abstract Boolean bannerInstructions(); @Nullable abstract Boolean voiceInstructions(); @Nullable abstract String voiceUnits(); @Nullable abstract String waypointIndices(); @Nullable abstract String waypointNames(); @Nullable abstract String approaches(); @NonNull @Override protected abstract String baseUrl(); /** * Build a new {@link NbmapMapMatching} object with the initial values set for * {@link #baseUrl()}, {@link #profile()}, {@link #geometries()}, and {@link #user()}. * * @return a {@link Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_NbmapMapMatching.Builder() .baseUrl(Constants.BASE_API_URL) .profile(DirectionsCriteria.PROFILE_DRIVING) .geometries(DirectionsCriteria.GEOMETRY_POLYLINE6) .user(DirectionsCriteria.PROFILE_DEFAULT_USER); } /** * Builds your map matching query by adding parameters. * * @since 2.0.0 */ @AutoValue.Builder public abstract static class Builder { private List<Point> coordinates = new ArrayList<>(); private String[] annotations; private String[] timestamps; private Double[] radiuses; private Integer[] waypointIndices; private String[] waypointNames; private String[] approaches; /** * Use POST method to request data. * The default is to use GET. * @return this builder for chaining options together * @since 4.4.0 */ public Builder post() { usePostMethod(true); return this; } /** * Use GET method to request data. * @return this builder for chaining options together * @since 4.4.0 */ public Builder get() { usePostMethod(false); return this; } abstract Builder usePostMethod(@NonNull Boolean usePost); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Map Matching API * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Whether or not to transparently remove clusters and re-sample traces for improved map * matching results. Pass in null to reset to the APIs default setting. * * @param tidy true if you'd like the API to remove coordinates clustered together, otherwise * false * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder tidy(@Nullable Boolean tidy); /** * The username for the account that the directions engine runs on. In most cases, this should * always remain the default value of {@link DirectionsCriteria#PROFILE_DEFAULT_USER}. * * @param user a non-null string which will replace the default user used in the map matching * request * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder user(@NonNull String user); /** * This selects which mode of transportation the user will be using to accurately give the * map matching route. The options include driving, driving considering traffic, walking, and * cycling. Using each of these profiles will result in different durations * * @param profile required to be one of the String values found in the {@link ProfileCriteria} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder profile(@NonNull @ProfileCriteria String profile); /** * alter the default geometry being returned for the map matching route. A null value will reset * this field to the APIs default value vs this SDKs default value of * {@link DirectionsCriteria#GEOMETRY_POLYLINE6}. * <p> * Note that while the API supports GeoJson as an option for geometry, this SDK intentionally * removes this as an option since an encoded string for the geometry significantly reduces * bandwidth on mobile devices and speeds up response time. * </p> * * @param geometries null if you'd like the default geometry, else one of the options found in * {@link GeometriesCriteria}. * @return this builder for chaining options together * @since 2.0.0 */ public abstract Builder geometries(@Nullable @GeometriesCriteria String geometries); /** * Optionally, set the maximum distance in meters that each coordinate is allowed to move when * snapped to a nearby road segment. There must be as many radiuses as there are coordinates in * the request. Values can be any number greater than 0 or they can be unlimited simply by * passing {@link Double#POSITIVE_INFINITY}. * <p> * If no routable road is found within the radius, a {@code NoSegment} error is returned. * </p> * * @param radiuses double array containing the radiuses defined in unit meters. * @return this builder for chaining options together * @since 1.0.0 */ public Builder radiuses(@Nullable @FloatRange(from = 0) Double... radiuses) { this.radiuses = radiuses; return this; } // Required for matching with NbmapMapMatching radiuses() method. abstract Builder radiuses(@Nullable String radiuses); /** * Optionally, set which input coordinates should be treated as waypoints. * <p> * Most useful in combination with steps=true and requests based on traces * with high sample rates. Can be an index corresponding to any of the input coordinates, * but must contain the first ( 0 ) and last coordinates' index separated by ; . * {@link #steps()} * </p> * * @param waypoints integer array of coordinate indices to be used as waypoints * @return this builder for chaining options together * @since 3.0.0 * @deprecated you should now use {@link #waypointIndices(Integer[])} */ @Deprecated public Builder waypoints(@Nullable @IntRange(from = 0) Integer... waypoints) { this.waypointIndices = waypoints; return this; } /** * Optionally, set which input coordinates should be treated as waypoints / separate legs. * Note: coordinate indices not added here act as silent waypoints * <p> * Most useful in combination with steps=true and requests based on traces * with high sample rates. Can be an index corresponding to any of the input coordinates, * but must contain the first ( 0 ) and last coordinates' index separated by ; . * {@link #steps()} * </p> * * @param waypointIndices integer array of coordinate indices to be used as waypoints * @return this builder for chaining options together * @since 3.0.0 */ public Builder waypointIndices(@Nullable @IntRange(from = 0) Integer... waypointIndices) { this.waypointIndices = waypointIndices; return this; } abstract Builder waypointIndices(@Nullable String waypointIndices); /** * Setting this will determine whether to return steps and turn-by-turn instructions. Can be * set to either true or false to enable or disable respectively. null can also optionally be * passed in to set the default behavior to match what the API does by default. * * @param steps true if you'd like step information * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder steps(@Nullable Boolean steps); /** * Type of returned overview geometry. Can be {@link DirectionsCriteria#OVERVIEW_FULL} (the most * detailed geometry available), {@link DirectionsCriteria#OVERVIEW_SIMPLIFIED} (a simplified * version of the full geometry), or {@link DirectionsCriteria#OVERVIEW_FALSE} (no overview * geometry). The default is simplified. Passing in null will use the APIs default setting for * the overview field. * * @param overview null or one of the options found in {@link OverviewCriteria} * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder overview(@Nullable @OverviewCriteria String overview); /** * Setting this will determine Whether or not to return banner objects associated with * the `routeSteps`. Should be used in conjunction with `steps`. * Can be set to either true or false to enable or * disable respectively. null can also optionally be * passed in to set the default behavior to match what the API does by default. * * @param bannerInstructions true if you'd like step information * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder bannerInstructions(@Nullable Boolean bannerInstructions); /** * Setting this will determine whether to return steps and turn-by-turn instructions. Can be * set to either true or false to enable or disable respectively. null can also optionally be * passed in to set the default behavior to match what the API does by default. * * @param voiceInstructions true if you'd like step information * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder voiceInstructions(@Nullable Boolean voiceInstructions); /** * Specify what unit you'd like voice and banner instructions to use. * * @param voiceUnits either Imperial (default) or Metric * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder voiceUnits( @Nullable @DirectionsCriteria.VoiceUnitCriteria String voiceUnits ); /** * Setting this will determine whether to return steps and turn-by-turn instructions. Can be * set to either true or false to enable or disable respectively. null can also optionally be * passed in to set the default behavior to match what the API does by default. * * @param roundaboutExits true if you'd like step information * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder roundaboutExits(@Nullable Boolean roundaboutExits); /** * Whether or not to return additional metadata along the route. Possible values are: * {@link DirectionsCriteria#ANNOTATION_DISTANCE}, * {@link DirectionsCriteria#ANNOTATION_DURATION}, * {@link DirectionsCriteria#ANNOTATION_DURATION} and * {@link DirectionsCriteria#ANNOTATION_CONGESTION}. * * @param annotations string referencing one of the annotation direction criteria's. The strings * restricted to one or multiple values inside the {@link AnnotationCriteria} * or null which will result in no annotations being used * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#route-leg-object">RouteLeg object * documentation</a> * @since 2.1.0 */ public Builder annotations(@Nullable @AnnotationCriteria String... annotations) { this.annotations = annotations; return this; } // Required for matching with NbmapMapMatching annotations() method. @SuppressWarnings("WeakerAccess") protected abstract Builder annotations(@Nullable String annotations); /** * Timestamps corresponding to each coordinate provided in the request; must be numbers in Unix * time (seconds since the Unix epoch) converted to a String. There must be as many timestamps * as there are coordinates in the request. * * @param timestamps timestamp corresponding to the coordinate added at the identical index * @return this builder for chaining options together * @since 2.1.0 */ public Builder timestamps(@Nullable String... timestamps) { this.timestamps = timestamps; return this; } // Required for matching with NbmapMapMatching timestamps() method. @SuppressWarnings("WeakerAccess") protected abstract Builder timestamps(@Nullable String timestamps); /** * Add a list of {@link Point}'s which define the points to perform the map matching on. The * minimum points is 2 and the maximum points allowed in totals 100. You can use this method in * conjunction with {@link #coordinate(Point)}. * * @param coordinates a List full of {@link Point}s which define the points to perform the map * matching on * @return this builder for chaining options together * @since 2.1.0 */ public Builder coordinates(@NonNull List<Point> coordinates) { this.coordinates.addAll(coordinates); return this; } // Required for matching with NbmapMapMatching coordinates() method. @SuppressWarnings("WeakerAccess") protected abstract Builder coordinates(@NonNull String coordinates); /** * This will add a single {@link Point} to the coordinate list which is used to determine the * duration between points. This can be called up to 100 times until you hit the maximum allowed * points. You can use this method in conjunction with {@link #coordinates(List)}. * * @param coordinate a {@link Point} which you'd like the map matching APi to perform on * @return this builder for chaining options together * @since 3.0.0 */ public Builder coordinate(@NonNull Point coordinate) { this.coordinates.add(coordinate); return this; } /** * Set the instruction language for the map matching request, the default is english. Only a * select number of languages are currently supported, reference the table provided in the see * link below. * * @param language a Locale value representing the language you'd like the instructions to be * written in when returned * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#instructions-languages">Supported * Languages</a> * @since 3.0.0 */ public Builder language(@Nullable Locale language) { if (language != null) { language(language.getLanguage()); } return this; } /** * Set the instruction language for the map matching request, the default is english. Only a * select number of languages are currently supported, reference the table provided in the see * link below. * * @param language a String value representing the language you'd like the instructions to be * written in when returned * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#instructions-languages">Supported * Languages</a> * @since 2.2.0 */ public abstract Builder language(String language); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); /** * Optionally used to indicate how map matched routes consider * rom which side of the road to approach a waypoint. * Accepts unrestricted (default), curb or null. * If set to unrestricted , the map matched route can approach waypoints * from either side of the road. If set to curb , the map matched route will be returned * so that on arrival, the waypoint will be found on the side that corresponds with the * driving_side of the region in which the returned route is located. * If provided, the list of approaches must be the same length as the list of waypoints. * * @param approaches null if you'd like the default approaches, * else one of the options found in * {@link DirectionsCriteria.ApproachesCriteria}. * @return this builder for chaining options together * @since 3.2.0 */ public Builder addApproaches(@Nullable String... approaches) { this.approaches = approaches; return this; } abstract Builder approaches(@Nullable String approaches); /** * Custom names for waypoints used for the arrival instruction, * each separated by ; . Values can be any string and total number of all characters cannot * exceed 500. If provided, the list of waypointNames must be the same length as the list of * waypoints, but you can skip a coordinate and show its position with the ; separator. * * @param waypointNames Custom names for waypoints used for the arrival instruction. * @return this builder for chaining options together * @since 3.3.0 */ public Builder addWaypointNames(@Nullable String... waypointNames) { this.waypointNames = waypointNames; return this; } abstract Builder waypointNames(@Nullable String waypointNames); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder baseUrl(String baseUrl); @SuppressWarnings("WeakerAccess") protected abstract NbmapMapMatching autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and first checks that all * values are valid, formats the values as strings for easier consumption by the API, and lastly * creates a new {@link NbmapMapMatching} object with the values provided. * * @return a new instance of Nbmap Map Matching * @throws ServicesException when a provided parameter is detected to be incorrect * @since 2.1.0 */ public NbmapMapMatching build() { if (coordinates == null || coordinates.size() < 2) { throw new ServicesException("At least two coordinates must be provided with your API" + " request."); } if (radiuses != null && radiuses.length != coordinates.size()) { throw new ServicesException( "There must be as many radiuses as there are coordinates."); } if (timestamps != null && timestamps.length != coordinates.size()) { throw new ServicesException( "There must be as many timestamps as there are coordinates."); } if (waypointIndices != null) { if (waypointIndices.length < 2) { throw new ServicesException( "Waypoints must be a list of at least two indexes separated by ';'"); } if (waypointIndices[0] != 0 || waypointIndices[waypointIndices.length - 1] != coordinates.size() - 1) { throw new ServicesException( "Waypoints must contain indices of the first and last coordinates" ); } for (int i = 1; i < waypointIndices.length - 1; i++) { if (waypointIndices[i] < 0 || waypointIndices[i] >= coordinates.size()) { throw new ServicesException( "Waypoints index too large (no corresponding coordinate)"); } } } if (waypointNames != null) { final String waypointNamesStr = FormatUtils.formatWaypointNames(Arrays.asList(waypointNames)); waypointNames(waypointNamesStr); } if (approaches != null) { if (approaches.length != coordinates.size()) { throw new ServicesException("Number of approach elements must match " + "number of coordinates provided."); } String formattedApproaches = FormatUtils.formatApproaches(Arrays.asList(approaches)); if (formattedApproaches == null) { throw new ServicesException("All approaches values must be one of curb, unrestricted"); } approaches(formattedApproaches); } coordinates(formatCoordinates(coordinates)); timestamps(TextUtils.join(";", timestamps)); annotations(TextUtils.join(",", annotations)); radiuses(TextUtils.join(";", radiuses)); waypointIndices(TextUtils.join(";", waypointIndices)); // Generate build so that we can check that values are valid. NbmapMapMatching mapMatching = autoBuild(); if (!NbmapUtils.isAccessTokenValid(mapMatching.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } return mapMatching; } private static String formatCoordinates(List<Point> coordinates) { List<String> coordinatesFormatted = new ArrayList<>(); for (Point point : coordinates) { coordinatesFormatted.add(String.format(Locale.US, "%s,%s", FormatUtils.formatCoordinate(point.longitude()), FormatUtils.formatCoordinate(point.latitude()))); } return TextUtils.join(";", coordinatesFormatted.toArray()); } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/package-info.java
/** * Contains the Nbmap Java Services wrapper for the Map Matching API. * * @since 2.0.0 */ package com.nbmap.api.matching.v5;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/models/MapMatchingAdapterFactory.java
package com.nbmap.api.matching.v5.models; import com.google.gson.TypeAdapterFactory; import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory; /** * A MapMatching type adapter factory for convenience when using AutoValue and handling * serialization/deserialization. The majority of this class gets generated during compilation time. * * @since 3.0.0 */ @GsonTypeAdapterFactory public abstract class MapMatchingAdapterFactory implements TypeAdapterFactory { /** * Create a new instance of this MapMatching type adapter factory, this is passed into the Gson * Builder. * * @return a new GSON TypeAdapterFactory * @since 3.0.0 */ public static TypeAdapterFactory create() { return new AutoValueGson_MapMatchingAdapterFactory(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/models/MapMatchingError.java
package com.nbmap.api.matching.v5.models; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import java.io.Serializable; /** * If an InvalidInput error is thrown, this class can be used to get both the code and the message * which holds an explanation of the invalid input. * * On error, the server responds with different HTTP status codes. * For responses with HTTP status codes lower than 500, the JSON response body includes the code * property, which may be used by client programs to manage control flow. * The response body may also include a message property, with a human-readable explaination * of the error. If a server error occurs, the HTTP status code will be 500 or higher and * the response will not include a code property. * * @since 3.0.0 */ @AutoValue public abstract class MapMatchingError implements Serializable { /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ public static Builder builder() { return new AutoValue_MapMatchingError.Builder(); } /** * String indicating the state of the response. This is a separate code than the HTTP status code. * On normal valid responses, the value will be Ok. The possible responses are listed below: * <ul> * <li><strong>Ok</strong> Normal case.</li> * <li><strong>NoMatch</strong> The input did not produce any matches, or the waypoints requested * were not found in the resulting match. features will be an empty array.</li> * <li><strong>TooManyCoordinates</strong> There are more than 100 points in the request.</li> * <li><strong>ProfileNotFound</strong> Needs to be a valid profile. </li> * <li><strong>InvalidInput</strong>message will hold an explanation of the invalid input.</li> * </ul> * * @return a string with one of the given values described in the list above * @since 3.0.0 */ @Nullable public abstract String code(); /** * Provides a short message with the explanation of the invalid input. * * @return a string containing the message API MapMatching response * @since 3.0.0 */ @Nullable public abstract String message(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<MapMatchingError> typeAdapter(Gson gson) { return new AutoValue_MapMatchingError.GsonTypeAdapter(gson); } /** * This builder can be used to set the values describing the {@link MapMatchingError}. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * String indicating the state of the response. This is a separate code than the HTTP status * code. On normal valid responses, the value will be Ok. The possible responses are listed * below: * <ul> * <li><strong>Ok</strong> Normal case.</li> * <li><strong>NoMatch</strong> The input did not produce any matches, or the waypoints * requested were not found in the resulting match. features will be an empty array.</li> * <li><strong>TooManyCoordinates</strong> There are more than 100 points in the request.</li> * <li><strong>ProfileNotFound</strong> Needs to be a valid profile. </li> * <li><strong>InvalidInput</strong>message will hold an explanation of the invalid input.</li> * </ul> * * @param code a string with one of the given values described in the list above * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder code(String code); /** * Provides a short message with the explanation of the invalid input. * * @param message a string containing the message API Directions response * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder message(String message); /** * Build a new {@link MapMatchingError} object. * * @return a new {@link MapMatchingError} using the provided values in this builder * @since 3.0.0 */ public abstract MapMatchingError build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/models/MapMatchingMatching.java
package com.nbmap.api.matching.v5.models; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import com.nbmap.api.directions.v5.models.DirectionsRoute; import com.nbmap.api.directions.v5.models.RouteLeg; import com.nbmap.api.directions.v5.models.RouteOptions; import java.io.Serializable; import java.util.List; /** * A match object is a {@link DirectionsRoute} object with an * additional confidence field. * * @since 2.0.0 */ @AutoValue public abstract class MapMatchingMatching implements Serializable { /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ public static Builder builder() { return new AutoValue_MapMatchingMatching.Builder(); } /** * The distance traveled from origin to destination. * * @return a double number with unit meters * @since 1.0.0 */ public abstract double distance(); /** * The estimated travel time from origin to destination. * * @return a double number with unit seconds * @since 1.0.0 */ public abstract double 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 */ @Nullable public abstract String geometry(); /** * The calculated weight of the route. * * @return the weight value provided from the API as a {@code double} value * @since 2.1.0 */ public abstract double weight(); /** * The name of the weight profile used while calculating during extraction phase. The default is * {@code routability} which is duration based, with additional penalties for less desirable * maneuvers. * * @return a String representing the weight profile used while calculating the route * @since 2.1.0 */ @SerializedName("weight_name") public abstract String weightName(); /** * A Leg is a route between only two waypoints. * * @return list of {@link RouteLeg} objects * @since 1.0.0 */ public abstract List<RouteLeg> legs(); /** * A number between 0 (low) and 1 (high) indicating level of confidence in the returned match. * * @return confidence value * @since 2.0.0 */ public abstract double confidence(); /** * Holds onto the parameter information used when making the directions request. Useful for * re-requesting a directions route using the same information previously used. * * @return a {@link RouteOptions}s object which holds onto critical information from the request * that cannot be derived directly from the directions route * @since 3.0.0 */ @Nullable public abstract RouteOptions routeOptions(); /** * String of the language to be used for voice instructions. Defaults to en, and * can be any accepted instruction language. Will be <tt>null</tt> when the language provided * via {@link com.nbmap.api.matching.v5.NbmapMapMatching#language()} is not compatible * with API Voice. * * @return String compatible with voice instructions, null otherwise * @since 3.4.0 */ @Nullable @SerializedName("voiceLocale") public abstract String voiceLanguage(); /** * Convert the current {@link MapMatchingMatching} to its builder holding the currently assigned * values. This allows you to modify a single variable and then rebuild the object resulting in * an updated and modified {@link MapMatchingMatching}. * * @return a {@link MapMatchingMatching.Builder} with the same values set to match the ones * defined in this {@link MapMatchingMatching} * @since 3.0.0 */ public abstract Builder toBuilder(); /** * Map this MapMatchingMatching object to a {@link DirectionsRoute} object. * * @return a {@link DirectionsRoute} object */ public DirectionsRoute toDirectionRoute() { return DirectionsRoute.builder() .legs(legs()) .geometry(geometry()) .weightName(weightName()) .weight(weight()) .duration(duration()) .distance(distance()) .routeOptions(routeOptions()) .voiceLanguage(voiceLanguage()) .build(); } /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<MapMatchingMatching> typeAdapter(Gson gson) { return new AutoValue_MapMatchingMatching.GsonTypeAdapter(gson); } /** * This builder can be used to set the values describing the {@link MapMatchingResponse}. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * The distance traveled from origin to destination. * * @param distance a double number with unit meters * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder distance(double distance); /** * The estimated travel time from origin to destination. * * @param duration a double number with unit seconds * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder duration(double duration); /** * Gives the geometry of the route. Commonly used to draw the route on the map view. * * @param geometry an encoded polyline string * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder geometry(@Nullable String geometry); /** * The calculated weight of the route. * * @param weight the weight value provided from the API as a {@code double} value * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder weight(double weight); /** * The name of the weight profile used while calculating during extraction phase. The default is * {@code routability} which is duration based, with additional penalties for less desirable * maneuvers. * * @param weightName a String representing the weight profile used while calculating the route * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder weightName(String weightName); /** * A Leg is a route between only two waypoints. * * @param legs list of {@link RouteLeg} objects * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder legs(List<RouteLeg> legs); /** * A number between 0 (low) and 1 (high) indicating level of confidence in the returned match. * * @param confidence confidence value * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder confidence(double confidence); /** * Holds onto the parameter information used when making the directions request. * * @param routeOptions a {@link RouteOptions}s object which holds onto critical information from * the request that cannot be derived directly from the directions route * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder routeOptions(@Nullable RouteOptions routeOptions); /** * String of the language to be used for voice instructions. Defaults to en, and * can be any accepted instruction language. Should be <tt>null</tt> when the language provided * via {@link com.nbmap.api.matching.v5.NbmapMapMatching#language()} is not * compatible with API Voice. * * @param voiceLanguage String compatible with voice instructions, null otherwise * @return this builder for chaining options together * @since 3.4.0 */ public abstract Builder voiceLanguage(@Nullable String voiceLanguage); /** * Build a new {@link MapMatchingMatching} object. * * @return a new {@link MapMatchingMatching} using the provided values in this builder * @since 3.0.0 */ public abstract MapMatchingMatching build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/models/MapMatchingResponse.java
package com.nbmap.api.matching.v5.models; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.nbmap.api.directions.v5.DirectionsAdapterFactory; import java.io.Serializable; import java.util.List; /** * Nbmap map matching API response and convenience getter methods for optional properties. * * @see <a href="https://www.nbmap.com/api-documentation/navigation/#map-matching">Map Matching API Documentation</a> * @since 2.0.0 */ @AutoValue public abstract class MapMatchingResponse implements Serializable { /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ public static Builder builder() { return new AutoValue_MapMatchingResponse.Builder(); } /** * A string depicting the state of the response. * <ul> * <li>"Ok" - Normal case</li> * <li>"NoMatch" - The input did not produce any matches. matchings will be an empty array.</li> * <li>"TooManyCoordinates" - There are more than 100 points in the request.</li> * <li>"InvalidInput" - message will hold an explanation of the invalid input.</li> * <li>"ProfileNotFound" - Profile should be {@code nbmap.driving}, {@code nbmap.walking}, * or {@code nbmap.cycling}.</li> * </ul> * * @return string containing the code * @since 2.0.0 */ @NonNull public abstract String code(); /** * Optionally shows up in a directions response if an error or something unexpected occurred. * * @return a string containing the message API MapMatching response with if an error occurred * @since 3.0.0 */ @Nullable public abstract String message(); /** * List of {@link MapMatchingMatching} objects, essentially a DirectionsWaypoint object with the * addition of a confidence value. * * @return a list made up of {@link MapMatchingMatching} objects * @since 2.0.0 */ @Nullable public abstract List<MapMatchingMatching> matchings(); /** * A list of {@link MapMatchingTracepoint} objects representing the location an input point was * matched with. list of Waypoint objects representing all input points of the trace in the order * they were matched. If a trace point is omitted by map matching because it is an outlier, the * entry will be null. * * @return tracepoints list * @since 2.0.0 */ @Nullable public abstract List<MapMatchingTracepoint> tracepoints(); /** * Convert the current {@link MapMatchingResponse} to its builder holding the currently assigned * values. This allows you to modify a single variable and then rebuild the object resulting in * an updated and modified {@link MapMatchingResponse}. * * @return a {@link MapMatchingResponse.Builder} with the same values set to match the ones * defined in this {@link MapMatchingResponse} * @since 3.0.0 */ public abstract Builder toBuilder(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<MapMatchingResponse> typeAdapter(Gson gson) { return new AutoValue_MapMatchingResponse.GsonTypeAdapter(gson); } /** * Create a new instance of this class by passing in a formatted valid JSON String. * * @param json a formatted valid JSON string defining a GeoJson Map Matching response * @return a new instance of this class defined by the values passed inside this static factory * method * @since 3.4.0 */ public static MapMatchingResponse fromJson(String json) { GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapterFactory(MapMatchingAdapterFactory.create()); gson.registerTypeAdapterFactory(DirectionsAdapterFactory.create()); return gson.create().fromJson(json, MapMatchingResponse.class); } /** * This builder can be used to set the values describing the {@link MapMatchingResponse}. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * A string depicting the state of the response. * <ul> * <li>"Ok" - Normal case</li> * <li>"NoMatch" - The input did not produce any matches. matchings will be an empty array.</li> * <li>"TooManyCoordinates" - There are more than 100 points in the request.</li> * <li>"InvalidInput" - message will hold an explanation of the invalid input.</li> * <li>"ProfileNotFound" - Profile should be {@code nbmap.driving}, {@code nbmap.walking}, * or {@code nbmap.cycling}.</li> * </ul> * * @param code string containing the code * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder code(@Nullable String code); /** * Optionally shows up in a map maptching response if an error or something unexpected occurred. * * @param message a string containing the message API MapMatching response with if an error * occurred * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder message(@Nullable String message); /** * List of {@link MapMatchingMatching} objects, essentially a DirectionsWaypoint object with the * addition of a confidence value. * * @param matchings a list made up of {@link MapMatchingMatching} objects * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder matchings(@Nullable List<MapMatchingMatching> matchings); /** * A list of {@link MapMatchingTracepoint} objects representing the location an input point was * matched with. list of Waypoint objects representing all input points of the trace in the * order they were matched. If a trace point is omitted by map matching because it is an * outlier, the entry will be null. * * @param tracepoints tracepoints list * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder tracepoints(@Nullable List<MapMatchingTracepoint> tracepoints); /** * Build a new {@link MapMatchingResponse} object. * * @return a new {@link MapMatchingResponse} using the provided values in this builder * @since 3.0.0 */ public abstract MapMatchingResponse build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/models/MapMatchingTracepoint.java
package com.nbmap.api.matching.v5.models; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import com.nbmap.geojson.Point; import com.nbmap.api.directions.v5.models.DirectionsWaypoint; import java.io.Serializable; /** * A tracepoint object is {@link DirectionsWaypoint} object with two * additional fields. * * @since 2.0.0 */ @AutoValue public abstract class MapMatchingTracepoint implements Serializable { /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ public static Builder builder() { return new AutoValue_MapMatchingTracepoint.Builder(); } /** * Index to the match object in matchings the sub-trace was matched to. * * @return index value * @since 2.2.0 */ @Nullable @SerializedName("matchings_index") public abstract Integer matchingsIndex(); /** * Number of probable alternative matchings for this trace point. A value of zero indicates that * this point was matched unambiguously. Split the trace at these points for incremental map * matching. * * @return an integer representing the alternatives count * @since 2.2.0 */ @Nullable @SerializedName("alternatives_count") public abstract Integer alternativesCount(); /** * Index of the waypoint inside the matched route. * * @return index value * @since 2.2.0 */ @Nullable @SerializedName("waypoint_index") public abstract Integer waypointIndex(); /** * A {@link Point} representing this waypoint location. * * @return GeoJson Point representing this waypoint location * @since 3.0.0 */ @Nullable public Point location() { return Point.fromLngLat(rawLocation()[0], rawLocation()[1]); } /** * Provides the way name which the waypoint's coordinate is snapped to. * * @return string with the name of the way the coordinate snapped to * @since 1.0.0 */ @Nullable public abstract String name(); /** * The rawLocation as a double array, since we convert this array to a {@link Point} there's no * need to expose this to developers. * <p> * Note that the mutable suppress warnings used here since this isn't publicly exposed and * internally, we do not mess with these values. * </p> * * @return a double array used for creating the public {@link Point} object * @since 3.0.0 */ @Nullable @SerializedName("location") @SuppressWarnings("mutable") abstract double[] rawLocation(); /** * Convert the current {@link MapMatchingTracepoint} to its builder holding the currently assigned * values. This allows you to modify a single variable and then rebuild the object resulting in * an updated and modified {@link MapMatchingTracepoint}. * * @return a {@link MapMatchingTracepoint.Builder} with the same values set to match the ones * defined in this {@link MapMatchingTracepoint} * @since 3.1.0 */ public abstract Builder toBuilder(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<MapMatchingTracepoint> typeAdapter(Gson gson) { return new AutoValue_MapMatchingTracepoint.GsonTypeAdapter(gson); } /** * This builder can be used to set the values describing the {@link MapMatchingTracepoint}. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * The rawLocation as a double array. Once the {@link MapMatchingTracepoint} object's created, * this raw location gets converted into a {@link Point} object and is public exposed as such. * The double array should have a length of two, index 0 being the longitude and index 1 being * latitude. * * @param rawLocation a double array with a length of two, index 0 being the longitude and * index 1 being latitude. * @return a double array used for creating the public {@link Point} object * @since 3.0.0 */ public abstract Builder rawLocation(double[] rawLocation); /** * Index to the match object in matchings the sub-trace was matched to. * * @param matchingsIndex index value * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder matchingsIndex(@Nullable Integer matchingsIndex); /** * Number of probable alternative matchings for this trace point. A value of zero indicates that * this point was matched unambiguously. Split the trace at these points for incremental map * matching. * * @param alternativesCount an integer representing the alternatives count * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder alternativesCount(@Nullable Integer alternativesCount); /** * Index of the waypoint inside the matched route. * * @param waypointIndex index value * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder waypointIndex(@Nullable Integer waypointIndex); /** * Provides the way name which the waypoint's coordinate is snapped to. * * @param name string with the name of the way the coordinate snapped to * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder name(@Nullable String name); /** * Build a new {@link MapMatchingTracepoint} object. * * @return a new {@link MapMatchingTracepoint} using the provided values in this builder * @since 3.0.0 */ public abstract MapMatchingTracepoint build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matching/v5/models/package-info.java
/** * Contains the Nbmap Matching response model classes. */ package com.nbmap.api.matching.v5.models;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1/MatrixAdapterFactory.java
package com.nbmap.api.matrix.v1; import com.google.gson.TypeAdapterFactory; import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory; /** * Required so that AutoValue can generate specific type adapters when needed inside the matrix * packages. * * @since 3.0.0 */ @GsonTypeAdapterFactory public abstract class MatrixAdapterFactory implements TypeAdapterFactory { /** * Creates a TypeAdapter that AutoValues uses to generate specific type adapters when needed * inside the matrix package classes. * * @return 3.0.0 */ public static TypeAdapterFactory create() { return new AutoValueGson_MatrixAdapterFactory(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1/MatrixService.java
package com.nbmap.api.matrix.v1; import com.nbmap.api.matrix.v1.models.MatrixResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the directions matrix service (v1). * * @since 2.1.0 */ public interface MatrixService { /** * 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 Nbmap access token * @param annotations Used to specify the resulting matrices. * Possible values are: duration (default), * distance, or both values separated by comma * @param approaches A semicolon-separated list indicating the side of the road from * which to approach waypoints in a requested route. * Accepts unrestricted (default, route can arrive at the waypoint * from either side of the road) or curb (route will arrive at * the waypoint on the driving_side of the region). * If provided, the number of approaches must be the same * as the number of waypoints. * However, you can skip a coordinate and * show its position in the list with the ; separator. * @param destinations array of waypoint objects. Each waypoints is an input coordinate snapped to * the road and path network. The waypoints appear in the array in the order * of the input coordinates, or in the order as specified in the destinations * query parameter * @param sources array of waypoint objects. Each waypoints is an input coordinate snapped to * the road and path network. The waypoints appear in the array in the order * of the input coordinates, or in the order as specified in the sources query * parameter * @return the {@link MatrixResponse} in a Call wrapper * @since 2.1.0 */ // @GET("directions-matrix/v1/{user}/{profile}/{coordinates}") @GET("distancematrix/json") Call<MatrixResponse> getCall( // NOTE: DirectionsMatrixServiceRx should be updated as well @Header("User-Agent") String userAgent, @Path("user") String user, @Path("profile") String profile, @Path("coordinates") String coordinates, @Query("key") String accessToken, @Query("annotations") String annotations, @Query("approaches") String approaches, @Query("destinations") String destinations, @Query("sources") String sources ); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1/NbmapMatrix.java
package com.nbmap.api.matrix.v1; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.api.directions.v5.DirectionsAdapterFactory; import com.nbmap.api.directions.v5.DirectionsCriteria; import com.nbmap.api.directions.v5.utils.FormatUtils; import com.nbmap.api.matrix.v1.models.MatrixResponse; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.ApiCallHelper; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.Point; import java.util.ArrayList; import java.util.List; import java.util.Locale; import retrofit2.Call; /** * the Matrix API returns all travel times between many points. The Matrix API will always return * the duration on the fastest route. Durations between points may not be symmetric (for example A * to B may have a different duration than B to A), as the routes may differ by direction due to * one-way streets or turn restrictions. The Matrix API returns durations in seconds. It does not * return route geometries or distances. * <p> * This API allows you to build tools that efficiently check the reachability of coordinates from * each other, filter points by travel time, or run your own algorithms for solving optimization * problems. * <p> * The standard limit for request are a maximum 60 requests per minute and maximum 25 input * coordinates. For example you can request a symmetric 25x25 matrix, an asymmetric 1x24 matrix with * distinct coordinates or a 12x24 where sources and destinations share some coordinates. For higher * volumes contact us. * <p> * * @see <a href="https://www.nbmap.com/api-documentation/navigation/#matrix">API documentation</a> * @since 2.1.0 */ @AutoValue public abstract class NbmapMatrix extends NbmapService<MatrixResponse, MatrixService> { protected NbmapMatrix() { super(MatrixService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(MatrixAdapterFactory.create()) .registerTypeAdapterFactory(DirectionsAdapterFactory.create()); } @Override protected Call<MatrixResponse> initializeCall() { return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), user(), profile(), coordinates(), accessToken(), annotations(), approaches(), destinations(), sources()); } @Nullable abstract String clientAppName(); @NonNull abstract String user(); @NonNull abstract String coordinates(); @NonNull abstract String accessToken(); @NonNull abstract String profile(); @Nullable abstract String sources(); @Nullable abstract String annotations(); @Nullable abstract String approaches(); @Nullable abstract String destinations(); @NonNull @Override protected abstract String baseUrl(); /** * Build a new {@link NbmapMatrix} object with the initial values set for {@link #baseUrl()}, * {@link #profile()}, and {@link #user()}. * * @return a {@link Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_NbmapMatrix.Builder() .baseUrl(Constants.BASE_API_URL) .profile(DirectionsCriteria.PROFILE_DRIVING) .user(DirectionsCriteria.PROFILE_DEFAULT_USER); } /** * This builder is used to create a new request to the Nbmap Matrix API. At a bare minimum, * your request must include an access token, and a list of coordinates. All other fields can * be left alone inorder to use the default behaviour of the API. * <p> * By default, the directions profile is set to driving (without traffic) but can be changed to * reflect your users use-case. * </p><p> * Note to contributors: All optional booleans in this builder use the object {@code Boolean} * rather than the primitive to allow for unset (null) values. * </p> * * @since 1.0.0 */ @AutoValue.Builder public abstract static class Builder { private List<Point> coordinates = new ArrayList<>(); private String[] annotations; private String[] approaches; private Integer[] destinations; private Integer[] sources; private Integer coordinateListSizeLimit; /** * The username for the account that the directions engine runs on. In most cases, this should * always remain the default value of {@link DirectionsCriteria#PROFILE_DEFAULT_USER}. * * @param user a non-null string which will replace the default user used in the directions * request * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder user(String user); /** * Add a list of {@link Point}'s which define the points to perform the matrix on. The minimum * points is 2 and the maximum points allowed in totals 25. You can use this method in * conjunction with {@link #coordinate(Point)}. * * @param coordinates a List full of {@link Point}s which define the points to perform the * matrix on * @return this builder for chaining options together * @since 2.1.0 */ public Builder coordinates(List<Point> coordinates) { this.coordinates.addAll(coordinates); return this; } // Required for matching with NbmapMatrix coordinates() method. abstract Builder coordinates(@NonNull String coordinates); /** * This will add a single {@link Point} to the coordinate list which is used to determine the * duration between points. This can be called up to 25 times until you hit the maximum allowed * points. You can use this method in conjunction with {@link #coordinates(List)}. * * @param coordinate a {@link Point} which you'd like the duration between all other points * @return this builder for chaining options together * @since 3.0.0 */ public Builder coordinate(@NonNull Point coordinate) { this.coordinates.add(coordinate); return this; } /** * This selects which mode of transportation the user will be using to accurately give the * matrix durations. The options include driving, driving considering traffic, walking, and * cycling. Using each of these profiles will result in different durations. * * @param profile required to be one of the String values found in the * {@link DirectionsCriteria.ProfileCriteria} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder profile(@NonNull @DirectionsCriteria.ProfileCriteria String profile); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Optimization API * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Optionally pass in annotations to control to change which data to return. * * @param annotations 1 or more annotations * @return this builder for chaining options together * @since 4.1.0 */ public Builder addAnnotations( @Nullable @DirectionsCriteria.AnnotationCriteria String... annotations) { this.annotations = annotations; return this; } // Required for matching with NbmapMatrix annotations() method. abstract Builder annotations(@Nullable String annotations); /** * A semicolon-separated list indicating the side of the road from * which to approach waypoints in a requested route. * Accepts unrestricted (default, route can arrive at the waypoint from either * side of the road) or curb (route will arrive at the waypoint on * the driving_side of the region). * If provided, the number of approaches must be the same as the number of waypoints. * However, you can skip a coordinate and show its position in the list with the ; separator. * * @param approaches null if you'd like the default approaches, * else one of the options found in * {@link DirectionsCriteria.ApproachesCriteria}. * @return this builder for chaining options together * @since 4.1.0 */ public Builder addApproaches(@Nullable String... approaches) { this.approaches = approaches; return this; } abstract Builder approaches( @Nullable @DirectionsCriteria.ApproachesCriteria String approaches); /** * Optionally pass in indexes to generate an asymmetric matrix. * * @param destinations 1 or more indexes as a integer, if more then one, separate with a comma * @return this builder for chaining options together * @since 2.1.0 */ public Builder destinations(@Nullable Integer... destinations) { this.destinations = destinations; return this; } // Required for matching with NbmapMatrix destinations() method. abstract Builder destinations(@Nullable String destinations); /** * Optionally pass in indexes to generate an asymmetric matrix. * * @param sources 1 or more indexes as a integer, if more then one, separate with a comma * @return Builder * @since 2.1.0 */ public Builder sources(@Nullable Integer... sources) { this.sources = sources; return this; } // Required for matching with NbmapMatrix sources() method. abstract Builder sources(@Nullable String sources); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * Override the standard maximum coordinate list size of 25 so that you can * make a Matrix API call with a list of coordinates as large as the value you give to * this method. * * You should only use this method if the Nbmap team has enabled your Nbmap * account to be able to request Matrix API information with a list of more than 25 * coordinates. * * @param coordinateListSizeLimit the max limit of coordinates used by a single call * * @return this builder for chaining options together * @since 5.1.0 */ public Builder coordinateListSizeLimit(@NonNull Integer coordinateListSizeLimit) { this.coordinateListSizeLimit = coordinateListSizeLimit; return this; } abstract NbmapMatrix autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and first checks that all * values are valid, formats the values as strings for easier consumption by the API, and lastly * creates a new {@link NbmapMatrix} object with the values provided. * * @return a new instance of Nbmap Matrix * @since 2.1.0 */ public NbmapMatrix build() { if (coordinates == null || coordinates.size() < 2) { throw new ServicesException("At least two coordinates must be provided with your API" + " request."); } else if (coordinateListSizeLimit != null && coordinateListSizeLimit < 0) { throw new ServicesException("If you're going to use the coordinateListSizeLimit() method, " + "please pass through a number that's greater than zero."); } else if (coordinateListSizeLimit == null && coordinates.size() > 25) { throw new ServicesException("A maximum of 25 coordinates is the default " + " allowed for this API. If your Nbmap account has been enabled by the" + " Nbmap team to make a request with more than 25 coordinates, please use" + " the builder's coordinateListSizeLimit() method and pass through your account" + "-specific maximum."); } else if (coordinateListSizeLimit != null && coordinateListSizeLimit < coordinates.size()) { throw new ServicesException("If you're going to use the coordinateListSizeLimit() method," + " please pass through a number that's equal to or greater than the size of" + " your coordinate list."); } coordinates(formatCoordinates(coordinates)); sources(TextUtils.join(";", sources)); destinations(TextUtils.join(";", destinations)); annotations(TextUtils.join(",", annotations)); approaches(TextUtils.join(";", approaches)); // Generate build so that we can check that values are valid. NbmapMatrix matrix = autoBuild(); if (!NbmapUtils.isAccessTokenValid(matrix.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } return matrix; } private static String formatCoordinates(List<Point> coordinates) { List<String> coordinatesFormatted = new ArrayList<>(); for (Point point : coordinates) { coordinatesFormatted.add(String.format(Locale.US, "%s,%s", FormatUtils.formatCoordinate(point.longitude()), FormatUtils.formatCoordinate(point.latitude()))); } return TextUtils.join(";", coordinatesFormatted.toArray()); } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1/package-info.java
/** * Contains the Nbmap Java Services classes for Matrix API. * * @since 2.1.0 */ package com.nbmap.api.matrix.v1;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1/models/MatrixResponse.java
package com.nbmap.api.matrix.v1.models; import java.io.Serializable; import java.util.List; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.nbmap.api.directions.v5.models.DirectionsWaypoint; import androidx.annotation.NonNull; /** * This contains the Matrix API response information which can be used to display the results. * * @since 2.1.0 */ @AutoValue public abstract class MatrixResponse implements Serializable { /** * Create a new instance of this class using the {@link MatrixResponse.Builder} which provides a * to pass in variables which define the instance. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ public static Builder builder() { return new AutoValue_MatrixResponse.Builder(); } /** * String indicating the state of the response. This is a separate code than the HTTP status code. * On normal valid responses, the value will be {@code Ok}. * <p> * On error, the server responds with different HTTP status codes. For responses with HTTP status * codes lower than 500, the JSON response body includes the code property, which may be used by * client programs to manage control flow. The response body may also include a message property, * with a human-readable explanation of the error. If a server error occurs, the HTTP status code * will be 500 or higher and the response will not include a code property. * </p><p> * Note that in cases where no route is found between a source and destination, no error will be * returned, but instead the respective value in the durations matrix will be null. * </p> * * @return "Ok", "NoRoute", "ProfileNotFound", or "InvalidInput" * @since 2.1.0 */ @NonNull public abstract String code(); /** * List of {@link DirectionsWaypoint} objects. Each waypoint is an input coordinate snapped to the * road and path network. The waypoints appear in the list in the order of the input coordinates, * or in the order as specified in the destinations query parameter. * * @return list object with each item being a {@link DirectionsWaypoint} * @since 2.1.0 */ @Nullable public abstract List<DirectionsWaypoint> destinations(); /** * List of {@link DirectionsWaypoint} objects. Each waypoints is an input coordinate snapped to * the road and path network. The waypoints appear in the list in the order of the input * coordinates, or in the order as specified in the sources query parameter. * * @return list object with each item being a {@link DirectionsWaypoint} * @since 2.1.0 */ @Nullable public abstract List<DirectionsWaypoint> sources(); /** * Durations as a list of arrays representing the matrix in row-major order. durations[i][j] gives * the travel time from the i-th source to the j-th destination. All values are in seconds. The * duration between the same coordinate is always 0. If a duration can not be found, the result is * null. * * @return an array of array with each entry being a duration value given in seconds. * @since 2.1.0 */ @Nullable public abstract List<Double[]> durations(); /** * Distances as a list of arrays representing the matrix in row-major order. * distances[i][j] gives the travel distance from the i-th source to the j-th destination. * All values are in meters. The duration between the same coordinate is always 0. * If a distance can not be found, the result is null. * * @return an array of array with each entry being a distance value given in meters. * @since 4.1.0 */ @Nullable public abstract List<Double[]> distances(); /** * Convert the current {@link MatrixResponse} to its builder holding the currently assigned * values. This allows you to modify a single variable and then rebuild the object resulting in * an updated and modified {@link MatrixResponse}. * * @return a {@link MatrixResponse.Builder} with the same values set to match the ones * defined in this {@link MatrixResponse} * @since 3.1.0 */ public abstract Builder toBuilder(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<MatrixResponse> typeAdapter(Gson gson) { return new AutoValue_MatrixResponse.GsonTypeAdapter(gson); } /** * This builder can be used to set the values describing the {@link MatrixResponse}. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * String indicating the state of the response. This is a separate code than the HTTP status * code. On normal valid responses, the value will be {@code Ok}. * <p> * On error, the server responds with different HTTP status codes. For responses with HTTP * status codes lower than 500, the JSON response body includes the code property, which may be * used by client programs to manage control flow. The response body may also include a message * property, with a human-readable explanation of the error. If a server error occurs, the HTTP * status code will be 500 or higher and the response will not include a code property. * </p><p> * Note that in cases where no route is found between a source and destination, no error will be * returned, but instead the respective value in the durations matrix will be null. * </p> * * @param code "Ok", "NoRoute", "ProfileNotFound", or "InvalidInput" * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder code(@NonNull String code); /** * List of {@link DirectionsWaypoint} objects. Each waypoint is an input coordinate snapped to * the road and path network. The waypoints appear in the list in the order of the input * coordinates, or in the order as specified in the destinations query parameter. * * @param destinations list object with each item being a {@link DirectionsWaypoint} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder destinations(@Nullable List<DirectionsWaypoint> destinations); /** * List of {@link DirectionsWaypoint} objects. Each waypoints is an input coordinate snapped to * the road and path network. The waypoints appear in the list in the order of the input * coordinates, or in the order as specified in the sources query parameter. * * @param sources list object with each item being a {@link DirectionsWaypoint} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder sources(@Nullable List<DirectionsWaypoint> sources); /** * Durations as array of arrays representing the matrix in row-major order. durations[i][j] * gives the travel time from the i-th source to the j-th destination. All values are in * seconds. The duration between the same coordinate is always 0. If a duration can not be * found, the result is null. * * @param durations an array of array with each entry being a duration value given in seconds. * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder durations(@Nullable List<Double[]> durations); /** * Distances as a list of arrays representing the matrix in row-major order. * distances[i][j] gives the travel distance from the i-th source to the j-th destination. * All values are in meters. The duration between the same coordinate is always 0. * If a distance can not be found, the result is null. * * @param distances an array of array with each entry being a distance value given in meters * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder distances(@Nullable List<Double[]> distances); /** * Build a new {@link MatrixResponse} object. * * @return a new {@link MatrixResponse} using the provided values in this builder * @since 3.0.0 */ public abstract MatrixResponse build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/matrix/v1/models/package-info.java
/** * Contains the Nbmap Matrix response model classes. */ package com.nbmap.api.matrix.v1.models;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1/NbmapOptimization.java
package com.nbmap.api.optimization.v1; import androidx.annotation.FloatRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.api.directions.v5.DirectionsAdapterFactory; import com.nbmap.api.directions.v5.DirectionsCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.AnnotationCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.DestinationCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.GeometriesCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.OverviewCriteria; import com.nbmap.api.directions.v5.DirectionsCriteria.ProfileCriteria; import com.nbmap.api.directions.v5.utils.FormatUtils; import com.nbmap.api.optimization.v1.models.OptimizationAdapterFactory; import com.nbmap.api.optimization.v1.models.OptimizationResponse; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.ApiCallHelper; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import retrofit2.Call; /** * The Nbmap Optimization API returns a duration-optimized trip between the input coordinates. * This is also known as solving the Traveling Salesperson Problem. A typical use case for this API * is planning the route for deliveries in a city. Optimized trips can be retrieved for car driving, * bicycling and walking or hiking. * <p> * Under normal plans, a maximum of 12 coordinates can be passed in at once at a maximum 60 requests * per minute. For higher volumes, reach out through our contact page. * <p> * Note that for under 10 coordinates, the returned results will be optimal. For 10 and more * coordinates, the results will be optimized approximations. * * @see <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem">Traveling Salesperson * Problem</a> * @see <a href="https://www.nbmap.com/api-documentation/navigation/#optimization">API documentation</a> * @since 2.1.0 */ @AutoValue public abstract class NbmapOptimization extends NbmapService<OptimizationResponse, OptimizationService> { protected NbmapOptimization() { super(OptimizationService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(OptimizationAdapterFactory.create()) .registerTypeAdapterFactory(DirectionsAdapterFactory.create()); } @Override protected Call<OptimizationResponse> initializeCall() { return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), user(), profile(), coordinates(), accessToken(), roundTrip(), radiuses(), bearings(), steps(), overview(), geometries(), annotations(), destination(), source(), language(), distributions()); } @NonNull abstract String user(); @NonNull abstract String profile(); @Nullable abstract Boolean roundTrip(); @Nullable abstract String distributions(); @Nullable abstract String source(); @Nullable abstract String destination(); @Nullable abstract String geometries(); @Nullable abstract String overview(); @Nullable abstract Boolean steps(); @Nullable abstract String clientAppName(); @NonNull abstract String accessToken(); @NonNull @Override protected abstract String baseUrl(); @Nullable abstract String language(); @Nullable abstract String radiuses(); @Nullable abstract String bearings(); @NonNull abstract String coordinates(); @Nullable abstract String annotations(); /** * Build a new {@link NbmapOptimization} object with the initial values set for * {@link #baseUrl()}, {@link #profile()}, {@link #user()}, and {@link #geometries()}. * * @return a {@link Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_NbmapOptimization.Builder() .baseUrl(Constants.BASE_API_URL) .profile(DirectionsCriteria.PROFILE_DRIVING) .user(DirectionsCriteria.PROFILE_DEFAULT_USER) .geometries(DirectionsCriteria.GEOMETRY_POLYLINE6); } /** * Optimization v1 builder. * * @since 2.1.0 */ @AutoValue.Builder public abstract static class Builder { private List<Integer[]> distributions = new ArrayList<>(); private List<List<Double>> bearings = new ArrayList<>(); private List<Point> coordinates = new ArrayList<>(); private String[] annotations; private double[] radiuses; /** * The username for the account that the directions engine runs on. In most cases, this should * always remain the default value of {@link DirectionsCriteria#PROFILE_DEFAULT_USER}. * * @param user a non-null string which will replace the default user used in the directions * request * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder user(@NonNull String user); /** * Add a list of {@link Point}'s which define the route which will become optimized. The minimum * points is 2 and the maximum points allowed in totals 12. You can use this method in * conjunction with {@link #coordinate(Point)}. * * @param coordinates a List full of {@link Point}s which define the route * @return this builder for chaining options together * @since 2.1.0 */ public Builder coordinates(@NonNull List<Point> coordinates) { this.coordinates.addAll(coordinates); return this; } // Required for matching with NbmapOptimization coordinates() method. abstract Builder coordinates(@NonNull String coordinates); /** * This will add a single {@link Point} to the coordinate list which is used to determine the * most optimal route. This can be called up to 12 times until you hit the maximum allowed * points. You can use this method in conjunction with {@link #coordinates(List)}. * * @param coordinate a {@link Point} which you'd like the optimized route to pass through * @return this builder for chaining options together * @since 3.0.0 */ public Builder coordinate(@NonNull Point coordinate) { this.coordinates.add(coordinate); return this; } /** * This selects which mode of transportation the user will be using while navigating from the * origin to the final destination. The options include driving, driving considering traffic, * walking, and cycling. Using each of these profiles will result in different routing biases. * * @param profile required to be one of the String values found in the {@link ProfileCriteria} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder profile(@NonNull @ProfileCriteria String profile); /** * Returned route is a roundtrip (route returns to first location). Allowed values are: * {@code true} (default), {@code false} and null (to reset to the default value). If the * roundtrip is set to false, then {@link #source()} and {@link #destination()} parameters are * required but not all combinations are possible. * <p> * It is possible to explicitly set the start or end coordinate of the trip. When source? is set * to first, the first coordinate is used as the start coordinate of the trip in the output. * When destination is set to last, the last coordinate will be used as destination of the trip * in the returned output. If you specify {@link DirectionsCriteria#DESTINATION_ANY}/ * {@link DirectionsCriteria#SOURCE_ANY}, any of the coordinates can be used as the first or * last coordinate in the output. * * @param roundTrip true if you'd like the route to return to the origin, else false * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#retrieve-an-optimization">Possible * roundtrip combinations</a> * @since 2.1.0 */ public abstract Builder roundTrip(@Nullable Boolean roundTrip); /** * Returned route starts at {@link DirectionsCriteria#SOURCE_ANY} or * {@link DirectionsCriteria#SOURCE_FIRST} coordinate. Null can also be passed in to reset * this value back to the API default if needed. * * @param source one of the values in {@link DirectionsCriteria.SourceCriteria} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder source(@Nullable @DirectionsCriteria.SourceCriteria String source); /** * Returned route ends at {@link DirectionsCriteria#DESTINATION_ANY} or * {@link DirectionsCriteria#DESTINATION_LAST} coordinate. * * @param destination either {@code "any" or "last"} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder destination(@Nullable @DestinationCriteria String destination); /** * alter the default geometry being returned for the directions route. A null value will reset * this field to the APIs default value vs this SDKs default value of * {@link DirectionsCriteria#GEOMETRY_POLYLINE6}. * <p> * Note that while the API supports GeoJson as an option for geometry, this SDK intentionally * removes this as an option since an encoded string for the geometry significantly reduces * bandwidth on mobile devices and speeds up response time. * </p> * * @param geometries null if you'd like the default geometry, else one of the options found in * {@link GeometriesCriteria}. * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder geometries(@Nullable @GeometriesCriteria String geometries); /** * Type of returned overview geometry. Can be {@link DirectionsCriteria#OVERVIEW_FULL} (the most * detailed geometry available), {@link DirectionsCriteria#OVERVIEW_SIMPLIFIED} (a simplified * version of the full geometry), or {@link DirectionsCriteria#OVERVIEW_FALSE} (no overview * geometry). The default is simplified. Passing in null will use the APIs default setting for * the overview field. * * @param overview null or one of the options found in {@link OverviewCriteria} * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder overview(@Nullable @OverviewCriteria String overview); /** * Optionally, set the maximum distance in meters that each coordinate is allowed to move when * snapped to a nearby road segment. There must be as many radiuses as there are coordinates in * the request. Values can be any number greater than 0 or they can be unlimited simply by * passing {@link Double#POSITIVE_INFINITY}. * <p> * If no routable road is found within the radius, a {@code NoSegment} error is returned. * </p> * * @param radiuses double array containing the radiuses defined in unit meters. * @return this builder for chaining options together * @since 2.1.0 */ public Builder radiuses(@FloatRange(from = 0) double... radiuses) { this.radiuses = radiuses; return this; } // Required for matching with NbmapOptimization radiuses() method. abstract Builder radiuses(@Nullable String radiuses); /** * Optionally, Use to filter the road segment the waypoint will be placed on by direction and * dictates the angle of approach. This option should always be used in conjunction with the * {@link #radiuses(double...)} parameter. * <p> * The parameter takes two values per waypoint: the first is an angle clockwise from true north * between 0 and 360. The second is the range of degrees the angle can deviate by. We recommend * a value of 45 degrees or 90 degrees for the range, as bearing measurements tend to be * inaccurate. This is useful for making sure we reroute vehicles on new routes that continue * traveling in their current direction. A request that does this would provide bearing and * radius values for the first waypoint and leave the remaining values empty. If provided, the * list of bearings must be the same length as the list of waypoints, but you can skip a * coordinate and show its position by passing in null value for both the angle and tolerance * values. * </p><p> * Each bearing value gets associated with the same order which coordinates are arranged in this * builder. For example, the first bearing added in this builder will be associated with the * origin {@code Point}, the nth bearing being associated with the nth waypoint added (if added) * and the last bearing being added will be associated with the destination. * </p> * * @param angle double value used for setting the corresponding coordinate's angle of travel * when determining the route * @param tolerance the deviation the bearing angle can vary while determining the route, * recommended to be either 45 or 90 degree tolerance * @return this builder for chaining options together * @since 2.1.0 */ public Builder bearing(@Nullable @FloatRange(from = 0, to = 360) Double angle, @Nullable @FloatRange(from = 0, to = 360) Double tolerance) { bearings.add(Arrays.asList(angle, tolerance)); return this; } // Required for matching with NbmapOptimization bearings() method. abstract Builder bearings(@Nullable String bearings); /** * Setting this will determine whether to return steps and turn-by-turn instructions. Can be * set to either true or false to enable or disable respectively. null can also optionally be * passed in to set the default behavior to match what the API does by default. * * @param steps true if you'd like step information * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder steps(@Nullable Boolean steps); /** * Whether or not to return additional metadata along the route. Possible values are: * {@link DirectionsCriteria#ANNOTATION_DISTANCE}, * {@link DirectionsCriteria#ANNOTATION_DURATION}, * {@link DirectionsCriteria#ANNOTATION_DURATION} and * {@link DirectionsCriteria#ANNOTATION_CONGESTION}. Several annotation can be used by * separating them with {@code ,}. * * @param annotations string referencing one of the annotation direction criteria's. The strings * restricted to one or multiple values inside the {@link AnnotationCriteria} * or null which will result in no annotations being used * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#route-leg-object">RouteLeg object * documentation</a> * @since 2.1.0 */ public Builder annotations(@Nullable @AnnotationCriteria String... annotations) { this.annotations = annotations; return this; } // Required for matching with NbmapOptimization annotations() method. abstract Builder annotations(@Nullable String annotations); /** * Set the instruction language for the directions request, the default is english. Only a * select number of languages are currently supported, reference the table provided in the see * link below. * * @param language a Locale value representing the language you'd like the instructions to be * written in when returned * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#instructions-languages">Supported * Languages</a> * @since 3.0.0 */ public Builder language(@Nullable Locale language) { if (language != null) { language(language.getLanguage()); } return this; } /** * Set the instruction language for the directions request, the default is english. Only a * select number of languages are currently supported, reference the table provided in the see * link below. It is recommended to use the {@link #language(Locale)} method to prevent errors * when making the request. * * @param language a String value representing the language you'd like the instructions to be * written in when returned * @return this builder for chaining options together * @see <a href="https://www.nbmap.com/api-documentation/navigation/#instructions-languages">Supported * Languages</a> * @since 2.2.0 */ public abstract Builder language(@Nullable String language); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Optimization API * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * Specify pick-up and drop-off locations for a trip by providing a {@code pickup} and * {@code dropOff} value correspond with the coordinates list. The first number indicates what * place the coordinate of the pick-up location is in the coordinates list, and the second * number indicates what place the coordinate of the drop-off location is in the coordinates * list. Pick-up and drop-off locations in one pair cannot be the same. The returned solution * will visit pick-up locations before visiting drop-off locations. The depot (first location) * can only be a pick-up location but not a drop-off location. * * @param dropOff the coordinate index in the coordinates list which should be the drop off * location * @param pickup the coordinate index in the coordinates list which should be the pick-up * location * @return this builder for chaining options together * @since 2.2.0 */ public Builder distribution(@Nullable Integer pickup, @Nullable Integer dropOff) { distributions.add(new Integer[] {pickup, dropOff}); return this; } // Required for matching with NbmapOptimization distributions() method. abstract Builder distributions(@Nullable String distributions); abstract NbmapOptimization autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and first checks that all * values are valid, formats the values as strings for easier consumption by the API, and lastly * creates a new {@link NbmapOptimization} object with the values provided. * * @return a new instance of Nbmap Optimization * @since 2.1.0 */ public NbmapOptimization build() { if (coordinates == null || coordinates.size() < 2) { throw new ServicesException("At least two coordinates must be provided with your API" + "request."); } else if (coordinates.size() > 12) { throw new ServicesException("Maximum of 12 coordinates are allowed for this API."); } coordinates(formatCoordinates(coordinates)); bearings(FormatUtils.formatBearings(bearings)); annotations(TextUtils.join(",", annotations)); radiuses(TextUtils.formatRadiuses(radiuses)); distributions(FormatUtils.formatDistributions(distributions)); // Generate build so that we can check that values are valid. NbmapOptimization optimization = autoBuild(); if (!NbmapUtils.isAccessTokenValid(optimization.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } return optimization; } private static String formatCoordinates(List<Point> coordinates) { List<String> coordinatesFormatted = new ArrayList<>(); for (Point point : coordinates) { coordinatesFormatted.add(String.format(Locale.US, "%s,%s", FormatUtils.formatCoordinate(point.longitude()), FormatUtils.formatCoordinate(point.latitude()))); } return TextUtils.join(";", coordinatesFormatted.toArray()); } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1/OptimizationService.java
package com.nbmap.api.optimization.v1; import com.nbmap.api.optimization.v1.models.OptimizationResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the Optimization service (v1). * * @since 2.1.0 */ public interface OptimizationService { /** * @param userAgent the application information * @param user the user which the OSRM engine should run on, typically Nbmap * @param profile the profile optimization should use * @param coordinates the coordinates used to calculate the trip * @param accessToken valid nbmap access token * @param roundTrip returned route is a round trip (route returns to first location). Allowed * values are: true (default) or false * @param radiuses maximum distance in meters that each coordinate is allowed to move when * snapped to a nearby road segment. There must be as many radiuses as there * are coordinates in the request. Values can be any number greater than 0 or * they can be the string unlimited. If no routable road is found within the * radius, a NoSegment error is returned * @param bearings used to filter the road segment the waypoint will be placed on by * direction and dictates the angle of approach * @param steps define if you'd like the route steps inside the response * @param overview route geometry can be simplified or full * @param geometries route geometry * @param annotations an annotations object that contains additional details about each line * segment along the route geometry. Each entry in an annotations field * corresponds to a coordinate along the route geometry * @param destination returned route ends at any or last coordinate. Allowed values are: any * (default) or last * @param source returned route starts at any or first coordinate. Allowed values are: any * (default) or first * @param language language of returned turn-by-turn text instructions * @param distributions specify pick-up and drop-off locations * @return The {@link OptimizationResponse} in a Call wrapper * @since 2.1.0 */ @GET("optimized-trips/v1/{user}/{profile}/{coordinates}") Call<OptimizationResponse> getCall( @Header("User-Agent") String userAgent, @Path("user") String user, @Path("profile") String profile, @Path("coordinates") String coordinates, @Query("key") String accessToken, @Query("roundtrip") Boolean roundTrip, @Query("radiuses") String radiuses, @Query("bearings") String bearings, @Query("steps") Boolean steps, @Query("overview") String overview, @Query("geometries") String geometries, @Query("annotations") String annotations, @Query("destination") String destination, @Query("source") String source, @Query("language") String language, @Query("distributions") String distributions ); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1/package-info.java
/** * Contains classes for accessing the Nbmap Optimization API. * * @since 3.0.0 */ package com.nbmap.api.optimization.v1;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1/models/OptimizationAdapterFactory.java
package com.nbmap.api.optimization.v1.models; import com.google.gson.TypeAdapterFactory; import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory; /** * Required so that AutoValue can generate specific type adapters when needed inside the * optimization packages. * * @since 3.0.0 */ @GsonTypeAdapterFactory public abstract class OptimizationAdapterFactory implements TypeAdapterFactory { /** * Creates a TypeAdapter that AutoValues uses to generate specific type adapters when needed * inside the optimization package classes. * * @return 3.0.0 */ public static TypeAdapterFactory create() { return new AutoValueGson_OptimizationAdapterFactory(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1/models/OptimizationResponse.java
package com.nbmap.api.optimization.v1.models; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.nbmap.api.directions.v5.models.DirectionsRoute; import java.io.Serializable; import java.util.List; /** * When the Nbmap Optimization API response, this will be the root class for accessing all the * response information provided. * * @since 2.1.0 */ @AutoValue public abstract class OptimizationResponse implements Serializable { /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ @NonNull public static Builder builder() { return new AutoValue_OptimizationResponse.Builder(); } /** * String indicating the state of the response. This is a separate code than the HTTP status code. * On normal valid responses, the value will be {@code Ok}. * <p> * On error, the server responds with different HTTP status codes. For responses with HTTP status * codes lower than 500, the JSON response body includes the code property, which may be used by * client programs to manage control flow. The response body may also include a message property, * with a human-readable explanation of the error. If a server error occurs, the HTTP status code * will be 500 or higher and the response will not include a code property. Possible errors * include: * <ul> * <li><strong>Ok</strong>: {@code 200} Normal success case</li> * <li><strong>NoTrips</strong>: {@code 200} For one coordinate no route to other coordinates * could be found. Check for impossible routes (e.g. routes over oceans without ferry * connections).</li> * <li><strong>NotImplemented</strong>: {@code 200} For the given combination of {@code source}, * {@code destination} and {@code roundtrip}, this request is not supported.</li> * <li><strong>ProfileNotFound</strong>: {@code 404} Use a valid profile</li> * <li><strong>InvalidInput</strong>: {@code 422} The given request was not valid. The message key * of the response will hold an explanation of the invalid input.</li> * </ul> * * @return string containing the response code. In normal conditions this will return {@code OK} * @since 2.1.0 */ @Nullable public abstract String code(); /** * List of {@link OptimizationWaypoint} objects. Each waypoint is an input coordinate snapped to * the road and path network. The waypoints appear in the list in the order of the input * coordinates. * * @return a list of {@link OptimizationWaypoint}s in the order of the input coordinates * @since 2.1.0 */ @Nullable public abstract List<OptimizationWaypoint> waypoints(); /** * List of trip {@link DirectionsRoute} objects. Will have zero or one trip. * * @return list of {@link DirectionsRoute} either having a size zero or one * @since 2.1.0 */ @Nullable public abstract List<DirectionsRoute> trips(); /** * Convert the current {@link OptimizationResponse} to its builder holding the currently assigned * values. This allows you to modify a single variable and then rebuild the object resulting in * an updated and modified {@link OptimizationResponse}. * * @return a {@link OptimizationResponse.Builder} with the same values set to match the ones * defined in this {@link OptimizationResponse} * @since 3.1.0 */ public abstract Builder toBuilder(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<OptimizationResponse> typeAdapter(Gson gson) { return new AutoValue_OptimizationResponse.GsonTypeAdapter(gson); } /** * This builder can be used to set the values describing the {@link OptimizationResponse}. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * String indicating the state of the response. This is a separate code than the HTTP status * code. On normal valid responses, the value will be {@code Ok}. * <p> * On error, the server responds with different HTTP status codes. For responses with HTTP * status codes lower than 500, the JSON response body includes the code property, which may be * used by client programs to manage control flow. The response body may also include a message * property, with a human-readable explanation of the error. If a server error occurs, the HTTP * status code * will be 500 or higher and the response will not include a code property. Possible errors * include: * <ul> * <li><strong>Ok</strong>: {@code 200} Normal success case</li> * <li><strong>NoTrips</strong>: {@code 200} For one coordinate no route to other coordinates * could be found. Check for impossible routes (e.g. routes over oceans without ferry * connections).</li> * <li><strong>NotImplemented</strong>: {@code 200} For the given combination of {@code source}, * {@code destination} and {@code roundtrip}, this request is not supported.</li> * <li><strong>ProfileNotFound</strong>: {@code 404} Use a valid profile</li> * <li><strong>InvalidInput</strong>: {@code 422} The given request was not valid. The message * key of the response will hold an explanation of the invalid input.</li> * </ul> * * @param code string containing the response code. In normal conditions this will return * {@code OK} * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder code(@Nullable String code); /** * List of {@link OptimizationWaypoint} objects. Each waypoint is an input coordinate snapped to * the road and path network. The waypoints appear in the list in the order of the input * coordinates. * * @param waypoints a list of {@link OptimizationWaypoint}s in the order of the input * coordinates * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder waypoints(@Nullable List<OptimizationWaypoint> waypoints); /** * List of trip {@link DirectionsRoute} objects. Will have zero or one trip. * * @param trips list of {@link DirectionsRoute} either having a size zero or one * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder trips(@Nullable List<DirectionsRoute> trips); /** * Build a new {@link OptimizationResponse} object. * * @return a new {@link OptimizationResponse} using the provided values in this builder * @since 3.0.0 */ public abstract OptimizationResponse build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1/models/OptimizationWaypoint.java
package com.nbmap.api.optimization.v1.models; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import com.nbmap.geojson.Point; import java.io.Serializable; /** * This is a single input coordinated snapped to the road and path network. The full list of the * waypoints appear in the list in the order of the input coordinates. * * @since 2.2.0 */ @AutoValue public abstract class OptimizationWaypoint implements Serializable { /** * Create a new instance of this class by using the {@link Builder} class. * * @return this classes {@link Builder} for creating a new instance * @since 3.0.0 */ @NonNull public static Builder builder() { return new AutoValue_OptimizationWaypoint.Builder(); } /** * Index of the waypoint inside the optimization route. * * @return index value * @since 2.2.0 */ @SerializedName("waypoint_index") public abstract int waypointIndex(); /** * Index to the trip object in the trips array that contains this waypoint. * * @return index value * @since 2.2.0 */ @SerializedName("trips_index") public abstract int tripsIndex(); /** * Provides the way name which the waypoint's coordinate is snapped to. * * @return string with the name of the way the coordinate snapped to * @since 2.2.0 */ @Nullable public abstract String name(); /** * A {@link Point} representing this waypoint location. * * @return GeoJson Point representing this waypoint location * @since 3.0.0 */ @Nullable public Point location() { return Point.fromLngLat(rawLocation()[0], rawLocation()[1]); } /** * The rawLocation as a double array, since we convert this array to a {@link Point} there's no * need to expose this to developers. * <p> * Note that the mutable suppress warnings used here since this isn't publicly exposed and * internally, we do not mess with these values. * </p> * * @return a double array used for creating the public {@link Point} object * @since 3.0.0 */ @Nullable @SerializedName("location") @SuppressWarnings("mutable") abstract double[] rawLocation(); /** * Convert the current {@link OptimizationWaypoint} to its builder holding the currently assigned * values. This allows you to modify a single variable and then rebuild the object resulting in * an updated and modified {@link OptimizationWaypoint}. * * @return a {@link OptimizationWaypoint.Builder} with the same values set to match the ones * defined in this {@link OptimizationWaypoint} * @since 3.1.0 */ public abstract OptimizationWaypoint.Builder toBuilder(); /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 3.0.0 */ public static TypeAdapter<OptimizationWaypoint> typeAdapter(Gson gson) { return new AutoValue_OptimizationWaypoint.GsonTypeAdapter(gson); } /** * This builder can be used to set the values describing the {@link OptimizationWaypoint}. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * Index of the waypoint inside the optimization route. * * @param waypointIndex index value * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder waypointIndex(int waypointIndex); /** * Index to the trip object in the trips array that contains this waypoint. * * @param tripsIndex index value * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder tripsIndex(int tripsIndex); /** * Provides the way name which the waypoint's coordinate is snapped to. * * @param name string with the name of the way the coordinate snapped to * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder name(@Nullable String name); /** * The rawLocation as a double array. Once the {@link OptimizationWaypoint} objects created, * this raw location gets converted into a {@link Point} object and is public exposed as such. * The double array should have a length of two, index 0 being the longitude and index 1 being * latitude. * * @param rawLocation a double array with a length of two, index 0 being the longitude and * index 1 being latitude. * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder rawLocation(double[] rawLocation); /** * Build a new {@link OptimizationResponse} object. * * @return a new {@link OptimizationResponse} using the provided values in this builder * @since 3.0.0 */ public abstract OptimizationWaypoint build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/optimization/v1/models/package-info.java
/** * Contains the model classes which represent the Optimization API response. */ package com.nbmap.api.optimization.v1.models;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/NbmapRouteTiles.java
package com.nbmap.api.routetiles.v1; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.nbmap.api.routetiles.v1.versions.NbmapRouteTileVersions; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.ApiCallHelper; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.geojson.BoundingBox; import java.util.Locale; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; /** * The Route Tiles API allows the download of route tiles for the purpose of offline routing. To * get a list of the versions, use the {@link NbmapRouteTileVersions} API. * * @since 4.1.0 */ @AutoValue public abstract class NbmapRouteTiles extends NbmapService<ResponseBody, RouteTilesService> { protected NbmapRouteTiles() { super(RouteTilesService.class); } @Override protected Call<ResponseBody> initializeCall() { return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), formatBoundingBox(boundingBox()), version(), accessToken() ); } @Override protected synchronized OkHttpClient getOkHttpClient() { if (okHttpClient == null) { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); if (isEnableDebug()) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BASIC); httpClient.addInterceptor(logging); } Interceptor interceptor = interceptor(); if (interceptor != null) { httpClient.addInterceptor(interceptor); } Interceptor networkInterceptor = networkInterceptor(); if (networkInterceptor != null) { httpClient.addNetworkInterceptor(networkInterceptor); } okHttpClient = httpClient.build(); } return okHttpClient; } @Nullable abstract String clientAppName(); @NonNull abstract BoundingBox boundingBox(); @NonNull abstract String version(); @NonNull abstract String accessToken(); @Nullable abstract Interceptor interceptor(); @Nullable abstract Interceptor networkInterceptor(); @Override protected abstract String baseUrl(); /** * Build a new {@link NbmapRouteTiles} object. * * @return a {@link Builder} object for creating this object * @since 4.1.0 */ public static Builder builder() { return new AutoValue_NbmapRouteTiles.Builder() .baseUrl(Constants.BASE_API_URL); } /** * Returns the builder which created this instance of {@link NbmapRouteTiles} and allows for * modification and building a new route tiles request with new information. * * @return {@link Builder} with the same variables set as this route tiles object * @since 4.1.0 */ public abstract Builder toBuilder(); /** * This builder is used to create a new request to the Nbmap Route Tiles API. At a bare minimum, * your request must include an access token, a {@link BoundingBox}, and a version. * * @since 4.1.0 */ @AutoValue.Builder public abstract static class Builder { /** * The bounding box of which to download map route tiles. * * @param boundingBox of which to download map route tiles * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder boundingBox(@NonNull BoundingBox boundingBox); /** * The version of map tiles being requested. To get a list of the versions, use the * {@link NbmapRouteTileVersions} API. * * @param version of which to download * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder version(@NonNull String version); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Route Tiles API * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); /** * Adds an optional interceptor to set in the OkHttp client. * * @param interceptor to set for OkHttp * @return this builder for chaining options together */ public abstract Builder interceptor(Interceptor interceptor); /** * Adds an optional network interceptor to set in the OkHttp client. * * @param interceptor to set for OkHttp * @return this builder for chaining options together */ public abstract Builder networkInterceptor(Interceptor interceptor); abstract NbmapRouteTiles autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and first checks that all * values are valid, and creates a new {@link NbmapRouteTiles} object with the values provided. * * @return a new instance of Nbmap Route Tiles * @throws ServicesException when a provided parameter is detected to be incorrect * @since 4.1.0 */ public NbmapRouteTiles build() { NbmapRouteTiles nbmapRouteTiles = autoBuild(); if (!NbmapUtils.isAccessTokenValid(nbmapRouteTiles.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } return nbmapRouteTiles; } } private String formatBoundingBox(BoundingBox boundingBox) { return String.format(Locale.US, "%f,%f;%f,%f", boundingBox.west(), boundingBox.south(), boundingBox.east(), boundingBox.north() ); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/RouteTilesService.java
package com.nbmap.api.routetiles.v1; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the Route Tiles Service (v1). * * @since 4.1.0 */ public interface RouteTilesService { /** * Constructs the html call using the informmation passed in through the * {@link NbmapRouteTiles.Builder}. * * @param userAgent the user agent * @param coordinates a string value of the min and max longitude and latitude * @param version version which was previously fetched through * {@link com.nbmap.api.routetiles.v1.versions.NbmapRouteTileVersions} * @param accessToken Nbmap access token * @return the ResponseBody containing the data stream wrapped in a Call wrapper * @since 4.1.0 */ @GET("route-tiles/v1/{coordinates}") Call<ResponseBody> getCall( @Header("User-Agent") String userAgent, @Path("coordinates") String coordinates, @Query("version") String version, @Query("key") String accessToken ); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/package-info.java
/** * Contains classes for accessing the Nbmap route tiles API. * * @since 4.1.0 */ package com.nbmap.api.routetiles.v1;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions/NbmapRouteTileVersions.java
package com.nbmap.api.routetiles.v1.versions; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.api.routetiles.v1.NbmapRouteTiles; import com.nbmap.api.routetiles.v1.versions.models.RouteTileVersionsAdapterFactory; import com.nbmap.api.routetiles.v1.versions.models.RouteTileVersionsResponse; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.ApiCallHelper; import com.nbmap.core.utils.NbmapUtils; import retrofit2.Call; /** * The Route Tile Versions API allows the fetching of all available versions of route tiles * currently available. It is used in conjunction with the {@link NbmapRouteTiles} API. * * @since 4.1.0 */ @AutoValue public abstract class NbmapRouteTileVersions extends NbmapService<RouteTileVersionsResponse, RouteTileVersionsService> { protected NbmapRouteTileVersions() { super(RouteTileVersionsService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(RouteTileVersionsAdapterFactory.create()); } @Override protected Call<RouteTileVersionsResponse> initializeCall() { return getService().getCall( ApiCallHelper.getHeaderUserAgent(clientAppName()), accessToken() ); } @Nullable abstract String clientAppName(); @NonNull abstract String accessToken(); @Override protected abstract String baseUrl(); /** * Build a new {@link NbmapRouteTileVersions} object. * * @return a {@link Builder} object for creating this object * @since 4.1.0 */ public static Builder builder() { return new AutoValue_NbmapRouteTileVersions.Builder() .baseUrl(Constants.BASE_API_URL); } /** * Returns the builder which created this instance of {@link NbmapRouteTileVersions} and * allows for modification and building a new route tile versions request with new information. * * @return {@link Builder} with the same variables set as this route tile versions object * @since 4.1.0 */ public abstract Builder toBuilder(); /** * This builder is used to create a new request to the Nbmap Route Tiles API. At a bare minimum, * your request must include an access token. * * @since 4.1.0 */ @AutoValue.Builder public abstract static class Builder { /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Route Tiles API * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * Base package name or other simple string identifier. Used inside the calls user agent header. * * @param clientAppName base package name or other simple string identifier * @return this builder for chaining options together * @since 4.1.0 */ public abstract Builder clientAppName(@NonNull String clientAppName); abstract NbmapRouteTileVersions autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and first checks that all * values are valid, and creates a new {@link NbmapRouteTileVersions} object with the values * provided. * * @return a new instance of Nbmap Route Tiles Version * @throws ServicesException when a provided parameter is detected to be incorrect * @since 4.1.0 */ public NbmapRouteTileVersions build() { NbmapRouteTileVersions nbmapRouteTileVersions = autoBuild(); if (!NbmapUtils.isAccessTokenValid(nbmapRouteTileVersions.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } return nbmapRouteTileVersions; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions/RouteTileVersionsService.java
package com.nbmap.api.routetiles.v1.versions; import com.nbmap.api.routetiles.v1.versions.models.RouteTileVersionsResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Query; /** * Interface that defines the Route Tile Versions Service (v1). * * @since 4.1.0 */ public interface RouteTileVersionsService { /** * * @param userAgent the user agent * @param accessToken Nbmap access token * @return the ResponseBody containing the data stream wrapped in a Call wrapper * @since 4.1.0 */ @GET("route-tiles/v1/versions?") Call<RouteTileVersionsResponse> getCall( @Header("User-Agent") String userAgent, @Query("key") String accessToken ); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions/package-info.java
/** * Contains classes for accessing the Nbmap route tile versions API. * * @since 4.1.0 */ package com.nbmap.api.routetiles.v1.versions;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions/models/RouteTileVersionsAdapterFactory.java
package com.nbmap.api.routetiles.v1.versions.models; import com.google.gson.TypeAdapterFactory; import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory; /** * Required so that AutoValue can generate specific type adapters when needed inside the direction * packages. * * @since 4.1.0 */ @GsonTypeAdapterFactory public abstract class RouteTileVersionsAdapterFactory implements TypeAdapterFactory { /** * Creates a TypeAdapter that AutoValues uses to generate specific type adapters when needed * inside the direction package classes. * * @return autovalue type adapter factory * @since 4.1.0 */ public static TypeAdapterFactory create() { return new AutoValueGson_RouteTileVersionsAdapterFactory(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions/models/RouteTileVersionsResponse.java
package com.nbmap.api.routetiles.v1.versions.models; import androidx.annotation.NonNull; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.nbmap.api.routetiles.v1.versions.NbmapRouteTileVersions; import java.util.List; /** * This is the root Nbmap Route Tile Versions response object, returned by * {@link NbmapRouteTileVersions}. * * @since 4.1.0 */ @AutoValue public abstract class RouteTileVersionsResponse { /** * Returns the list of available versions. * * @return list of available versions * @since 4.1.0 */ @NonNull public abstract List<String> availableVersions(); /** * Build a new {@link RouteTileVersionsResponse} object. * * @param versions the versions to be included in the response * @return response with specified versions * @since 4.1.0 */ public RouteTileVersionsResponse create(List<String> versions) { return new AutoValue_RouteTileVersionsResponse(versions); } /** * Gson type adapter for parsing Gson to this class. * * @param gson the built {@link Gson} object * @return the type adapter for this class * @since 4.1.0 */ public static TypeAdapter<RouteTileVersionsResponse> typeAdapter(Gson gson) { return new AutoValue_RouteTileVersionsResponse.GsonTypeAdapter(gson); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/routetiles/v1/versions/models/package-info.java
/** * Contains the Nbmap Route Tile Versions response model classes. * * @since 4.1.0 */ package com.nbmap.api.routetiles.v1.versions.models;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/speech
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/speech/v1/NbmapSpeech.java
package com.nbmap.api.speech.v1; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.TextUtils; import java.util.logging.Logger; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; /** * The Speech API is a text-to-speech API with a server-side caching layer in front of AWS Polly. * The only requirements are text to dictate, and a Nbmap access token. For 3-step-ahead * client-side caching, cache directory is required. * * @since 3.0.0 */ @AutoValue public abstract class NbmapSpeech extends NbmapService<ResponseBody, SpeechService> { private static final Logger LOGGER = Logger.getLogger(NbmapSpeech.class.getName()); protected NbmapSpeech() { super(SpeechService.class); } @Override protected Call<ResponseBody> initializeCall() { return getService().getCall( instruction(), textType(), language(), outputType(), accessToken()); } @Nullable abstract String language(); @Nullable abstract String textType(); @Nullable abstract String outputType(); @Nullable abstract Cache cache(); @Nullable abstract Interceptor interceptor(); @Nullable abstract Interceptor networkInterceptor(); @NonNull abstract String accessToken(); @NonNull abstract String instruction(); @Override protected abstract String baseUrl(); @Override public synchronized OkHttpClient getOkHttpClient() { if (okHttpClient == null) { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); if (isEnableDebug()) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BASIC); httpClient.addInterceptor(logging); } if (cache() != null) { httpClient.cache(cache()); } if (interceptor() != null) { httpClient.addInterceptor(interceptor()); } if (networkInterceptor() != null) { httpClient.addNetworkInterceptor(networkInterceptor()); } okHttpClient = httpClient.build(); } return okHttpClient; } /** * Creates a builder for a NbmapSpeech object with a default cache size of 10 MB. * * @return a builder to create a NbmapSpeech object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_NbmapSpeech.Builder() .baseUrl(Constants.BASE_API_URL); } /** * This builder is used to create a NbmapSpeech instance, with details about how the API calls * should be made (input/output format, language, etc.). To use caching, specify a cache * directory. Access token and instruction are required, along with cache directory if you choose * to use caching. * * @since 3.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * Language of which to request the instructions be spoken. Default is "en-us" * * @param language as a string, i.e., "en-us" * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder language(String language); /** * Format which the input is specified. If not specified, default is text * * @param textType either text or ssml * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder textType(String textType); /** * Output format for spoken instructions. If not specified, default is mp3 * * @param outputType either mp3 or json * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder outputType(String outputType); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account in order to use * the Optimization API * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Add the instruction text to dictate, either as plain text or ssml. * * @param instruction to dictate * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder instruction(@NonNull String instruction); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * Adds an optional cache to set in the OkHttp client. * * @param cache to set for OkHttp * @return this builder for chaining options together * @since 3.0.0 */ public abstract Builder cache(Cache cache); /** * Adds an optional interceptor to set in the OkHttp client. * * @param interceptor to set for OkHttp * @return this builder for chaining options together */ public abstract Builder interceptor(Interceptor interceptor); /** * Adds an optional network interceptor to set in the OkHttp client. * * @param interceptor to set for OkHttp * @return this builder for chaining options together */ public abstract Builder networkInterceptor(Interceptor interceptor); abstract NbmapSpeech autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and first checks that all * values are valid, formats the values as strings for easier consumption by the API, and lastly * creates a new {@link NbmapSpeech} object with the values provided. * * @return a new instance of Nbmap Speech * @throws ServicesException when a provided parameter is detected to be incorrect * @since 3.0.0 */ public NbmapSpeech build() { NbmapSpeech nbmapSpeech = autoBuild(); if (TextUtils.isEmpty(nbmapSpeech.instruction())) { throw new ServicesException("Non-null, non-empty instruction text is required."); } return nbmapSpeech; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/speech
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/speech/v1/SpeechService.java
package com.nbmap.api.speech.v1; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the speech service. * * @since 3.0.0 */ public interface SpeechService { /** * Constructs the html call using the information passed in through the * {@link NbmapSpeech.Builder}. * * @param text text to dictate * @param textType text type, either "text" or "ssml" (default is "text") * @param language language locale, default is "en-us" * @param outputFormat output format, either "mp3" or "json", default is "mp3" * @param accessToken Nbmap access token * @return the NbmapSpeech response in a Call wrapper * @since 3.0.0 */ @GET("/voice/v1/speak/{text}") Call<ResponseBody> getCall( @Path("text") String text, @Query("textType") String textType, @Query("language") String language, @Query("outputFormat") String outputFormat, @Query("key") String accessToken); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/speech
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/speech/v1/package-info.java
/** * Contains the Nbmap Java Services wrapper for the Speech API. * * @since 3.0.0 */ package com.nbmap.api.speech.v1;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1/NbmapStaticMap.java
package com.nbmap.api.staticmap.v1; import androidx.annotation.FloatRange; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.nbmap.api.staticmap.v1.models.StaticMarkerAnnotation; import com.nbmap.api.staticmap.v1.models.StaticPolylineAnnotation; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.GeoJson; import com.nbmap.geojson.Point; import okhttp3.HttpUrl; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; /** * Static maps are standalone images that can be displayed in your mobile app without the aid of a * mapping library like the Nbmap Android SDK. They look like an embedded map without interactivity * or controls. the returned image can be a raster tile ans pulls from any map style in the Nbmap * Style Specification. * <p> * This class helps make a valid request and gets the information correctly formatted for Picaso or * Glide libraries which help download the image and place it into an Image View. * * @see <a href=https://www.nbmap.com/api-documentation/maps/#static>API Documentation</a> * @since 1.0.0 */ @AutoValue public abstract class NbmapStaticMap { private static final String BEFORE_LAYER = "before_layer"; private static final String CAMERA_AUTO = "auto"; @NonNull abstract String accessToken(); @NonNull abstract String baseUrl(); @NonNull abstract String user(); @NonNull abstract String styleId(); abstract boolean logo(); abstract boolean attribution(); abstract boolean retina(); @NonNull abstract Point cameraPoint(); abstract double cameraZoom(); abstract double cameraBearing(); abstract double cameraPitch(); abstract boolean cameraAuto(); @Nullable abstract String beforeLayer(); abstract int width(); abstract int height(); @Nullable abstract GeoJson geoJson(); @Nullable abstract List<StaticMarkerAnnotation> staticMarkerAnnotations(); @Nullable abstract List<StaticPolylineAnnotation> staticPolylineAnnotations(); abstract int precision(); /** * Returns the formatted URL string meant to be passed to your Http client for retrieval of the * actual Nbmap Static Image. * * @return a {@link HttpUrl} which can be used for making the request for the image * @since 3.0.0 */ public HttpUrl url() { HttpUrl.Builder urlBuilder = HttpUrl.parse(baseUrl()).newBuilder() .addPathSegment("styles") .addPathSegment("v1") .addPathSegment(user()) .addPathSegment(styleId()) .addPathSegment("static") .addQueryParameter("access_token", accessToken()); List<String> annotations = new ArrayList<>(); if (staticMarkerAnnotations() != null) { List<String> markerStrings = new ArrayList<>(staticMarkerAnnotations().size()); for (StaticMarkerAnnotation marker : staticMarkerAnnotations()) { markerStrings.add(marker.url()); } annotations.addAll(markerStrings); } if (staticPolylineAnnotations() != null) { String[] polylineStringArray = new String[staticPolylineAnnotations().size()]; for (StaticPolylineAnnotation polyline : staticPolylineAnnotations()) { polylineStringArray[staticPolylineAnnotations().indexOf(polyline)] = polyline.url(); } annotations.addAll(Arrays.asList(polylineStringArray)); } if (geoJson() != null) { annotations.add(String.format(Locale.US, "geojson(%s)", geoJson().toJson())); } if (!annotations.isEmpty()) { urlBuilder.addPathSegment(TextUtils.join(",", annotations.toArray())); } urlBuilder.addPathSegment(cameraAuto() ? CAMERA_AUTO : generateLocationPathSegment()); if (beforeLayer() != null) { urlBuilder.addQueryParameter(BEFORE_LAYER, beforeLayer()); } if (!attribution()) { urlBuilder.addQueryParameter("attribution", "false"); } if (!logo()) { urlBuilder.addQueryParameter("logo", "false"); } // Has to be last segment in URL urlBuilder.addPathSegment(generateSizePathSegment()); return urlBuilder.build(); } private String generateLocationPathSegment() { if (precision() > 0) { List<String> geoInfo = new ArrayList<>(); geoInfo.add(TextUtils.formatCoordinate(cameraPoint().longitude(), precision())); geoInfo.add(TextUtils.formatCoordinate(cameraPoint().latitude(), precision())); geoInfo.add(TextUtils.formatCoordinate(cameraZoom(), precision())); geoInfo.add(TextUtils.formatCoordinate(cameraBearing(), precision())); geoInfo.add(TextUtils.formatCoordinate(cameraPitch(), precision())); return TextUtils.join(",", geoInfo.toArray()); } else { return String.format(Locale.US, "%f,%f,%f,%f,%f", cameraPoint().longitude(), cameraPoint().latitude(), cameraZoom(), cameraBearing(), cameraPitch()); } } private String generateSizePathSegment() { return String.format(Locale.US, "%dx%d%s", width(), height(), retina() ? "@2x" : ""); } /** * Build a new {@link NbmapStaticMap} object with the initial values set for * {@link #baseUrl()}, {@link #user()}, {@link #attribution()}, {@link #styleId()}, * and {@link #retina()}. * * @return a {@link Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_NbmapStaticMap.Builder() .styleId(StaticMapCriteria.STREET_STYLE) .baseUrl(Constants.BASE_API_URL) .user(Constants.NBMAP_USER) .cameraPoint(Point.fromLngLat(0d, 0d)) .cameraAuto(false) .attribution(true) .width(250) .logo(true) .attribution(true) .retina(true) .height(250) .cameraZoom(0) .cameraPitch(0) .cameraBearing(0) .precision(0) .retina(false); } /** * Static image builder used to customize the image, including location, image width/height, * and camera position. * * @since 1.0.0 */ @AutoValue.Builder public abstract static class Builder { /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token, You must have a Nbmap account inorder to use * the Optimization API * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * Optionally change the APIs base URL to something other then the default Nbmap one. * * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * The username for the account that the directions engine runs on. In most cases, this should * always remain the default value of {@link Constants#NBMAP_USER}. * * @param user a non-null string which will replace the default user used in the directions * request * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder user(@NonNull String user); /** * The returning map images style, which can be one of the provided Nbmap Styles or a custom * style made inside Nbmap Studio. Passing null will revert to using the default map Street * style. * * @param styleId either one of the styles defined inside {@link StaticMapCriteria} or a custom * url pointing to a styled map made in Nbmap Studio * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder styleId(@NonNull String styleId); /** * Optionally, control whether there is a Nbmap logo on the image. Default is true. Check that * the current Nbmap plan you are under allows for hiding the Nbmap Logo from the mao. * * @param logo true places Nbmap logo on image * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder logo(boolean logo); /** * Optionally, control whether there is attribution on the image. Default is true. Check that * the current Nbmap plan you are under allows for hiding the Nbmap Logo from the mao. * * @param attribution true places attribution on image * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder attribution(boolean attribution); /** * Enhance your image by toggling retina to true. This will double the amount of pixels the * returning image will have. * * @param retina true if the desired image being returned should contain double pixels * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder retina(boolean retina); /** * Center point where the camera will be focused on. * * @param cameraPoint a GeoJSON Point object which defines the cameras center position * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder cameraPoint(@Nullable Point cameraPoint); /** * Static maps camera zoom level. This can be though of as how far away the camera is from the * subject (earth) thus a zoom of 0 will display the entire world vs zoom 16 which is street\ * level zoom level. Fractional zoom levels will be rounded to two decimal places. * * @param cameraZoom double number between 0 and 22 * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder cameraZoom(@FloatRange(from = 0, to = 22) double cameraZoom); /** * Optionally, bearing rotates the map around its center defined point given in * {@link #cameraPoint(Point)}. A value of 90 rotates the map 90 to the left. 180 flips the map. * Defaults is 0. * * @param cameraBearing double number between 0 and 360, interpreted as decimal degrees * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder cameraBearing(@FloatRange(from = 0, to = 360) double cameraBearing); /** * Optionally, pitch tilts the map, producing a perspective effect. Defaults is 0. * * @param cameraPitch double number between 0 and 60 * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder cameraPitch(@FloatRange(from = 0, to = 60) double cameraPitch); /** * If auto is set to true, the viewport will fit the bounds of the overlay. Using this will * replace any latitude or longitude you provide. * * @param auto true if you'd like the viewport to be centered to display all map annotations, * defaults false * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder cameraAuto(boolean auto); /** * String value for controlling where the overlay is inserted in the style. All overlays will be * inserted before this specified layer. * * @param beforeLayer s string representing the map layer you'd like to place your overlays * below. * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder beforeLayer(@Nullable String beforeLayer); /** * Width of the image. * * @param width int number between 1 and 1280. * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder width(@IntRange(from = 1, to = 1280) int width); /** * Height of the image. * * @param height int number between 1 and 1280. * @return Builder * @since 1.0.0 */ public abstract Builder height(@IntRange(from = 1, to = 1280) int height); /** * GeoJSON object which represents a specific annotation which will be placed on the static map. * The GeoJSON must be value. * * @param geoJson a formatted string ready to be added to the static map image URL * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder geoJson(@Nullable GeoJson geoJson); /** * Optionally provide a list of marker annotations which can be placed on the static map image * during the rendering process. * * @param staticMarkerAnnotations a list made up of {@link StaticMarkerAnnotation} objects * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder staticMarkerAnnotations( @Nullable List<StaticMarkerAnnotation> staticMarkerAnnotations); /** * Optionally provide a list of polyline annotations which can be placed on the static map image * during the rendering process. * * @param staticPolylineAnnotations a list made up of {@link StaticPolylineAnnotation} objects * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder staticPolylineAnnotations( @Nullable List<StaticPolylineAnnotation> staticPolylineAnnotations); /** * In order to make the returned image better cache-able on the client, you can set the * precision in decimals instead of manually round the parameters. * * @param precision integer value greater than zero which represents the decimal precision of * coordinate values * @return this builder for chaining options together * @since 1.0.0 */ public abstract Builder precision(@IntRange(from = 0) int precision); abstract NbmapStaticMap autoBuild(); /** * This uses the provided parameters set using the {@link Builder} and creates a new * {@link NbmapStaticMap} object. * * @return a new instance of {@link NbmapStaticMap} * @since 2.1.0 */ public NbmapStaticMap build() { NbmapStaticMap staticMap = autoBuild(); if (!NbmapUtils.isAccessTokenValid(staticMap.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access" + " token."); } if (staticMap.styleId().isEmpty()) { throw new ServicesException("You need to set a map style."); } return staticMap; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1/StaticMapCriteria.java
package com.nbmap.api.staticmap.v1; import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Constant values related to the Static Map API can be found in this class. * * @since 3.0.0 */ public final class StaticMapCriteria { /** * The Static Maps marker shape and size will be small. * * @since 3.0.0 */ public static final String SMALL_PIN = "pin-s"; /** * The Static Maps marker shape and size will be medium. * * @since 3.0.0 */ public static final String MEDIUM_PIN = "pin-m"; /** * The Static Maps marker shape and size will be large. * * @since 3.0.0 */ public static final String LARGE_PIN = "pin-l"; /** * Nbmap Streets is a comprehensive, general-purpose map that emphasizes accurate, legible * styling of road and transit networks. * * @since 3.0.0 */ public static final String STREET_STYLE = "streets-v11"; /** * Nbmap Outdoors is a general-purpose map with curated tilesets and specialized styling tailored * to hiking, biking, and the most adventurous use cases. * * @since 3.0.0 */ public static final String OUTDOORS_STYLE = "outdoors-v11"; /** * Nbmap Light style's a subtle, full-featured map designed to provide geographic context while * highlighting the data on your analytics dashboard, data visualization, or data overlay. * * @since 3.0.0 */ public static final String LIGHT_STYLE = "light-v10"; /** * Nbmap Dark style's a subtle, full-featured map designed to provide geographic context while * highlighting the data on your analytics dashboard, data visualization, or data overlay. * * @since 3.0.0 */ public static final String DARK_STYLE = "dark-v10"; /** * Nbmap Satellite is our full global base map that is perfect as a blank canvas or an overlay * for your own data. * * @since 3.0.0 */ public static final String SATELLITE_STYLE = "satellite-v9"; /** * Nbmap Satellite Streets combines our Nbmap Satellite with vector data from Nbmap Streets. * The comprehensive set of road, label, and POI information brings clarity and context to the * crisp detail in our high-resolution satellite imagery. * * @since 3.0.0 */ public static final String SATELLITE_STREETS_STYLE = "satellite-streets-v11"; /** * Navigation specific style that shows only the necessary information while a user is driving. * * @since 3.0.0 */ public static final String NAVIGATION_PREVIEW_DAY = "navigation-preview-day-v3"; /** * Navigation specific style that shows only the necessary information while a user is driving. * * @since 3.0.0 */ public static final String NAVIGATION_PREVIEW_NIGHT = "navigation-preview-night-v3"; /** * Navigation specific style that shows only the necessary information while a user is driving. * * @since 3.0.0 */ public static final String NAVIGATION_GUIDANCE_DAY = "navigation-guidance-day-v4"; /** * Navigation specific style that shows only the necessary information while a user is driving. * * @since 3.0.0 */ public static final String NAVIGATION_GUIDANCE_NIGHT = "navigation-guidance-night-v4"; private StaticMapCriteria() { throw new AssertionError("No Instances."); } /** * Retention policy for the pin parameter in the Static Map Marker Annotation API. * * @since 3.0.0 */ @Retention(RetentionPolicy.CLASS) @StringDef( { SMALL_PIN, MEDIUM_PIN, LARGE_PIN }) public @interface MarkerCriteria { } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1/package-info.java
/** * Contains the builders for Nbmap Static Map API. */ package com.nbmap.api.staticmap.v1;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1/models/StaticMarkerAnnotation.java
package com.nbmap.api.staticmap.v1.models; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import static com.nbmap.core.utils.ColorUtils.toHexString; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import com.google.auto.value.AutoValue; import com.nbmap.api.staticmap.v1.StaticMapCriteria; import com.nbmap.api.staticmap.v1.StaticMapCriteria.MarkerCriteria; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.Point; import java.util.Locale; /** * Nbmap Static Image API marker overlay. Building this object allows you to place a marker on top * or within your static image. The marker can either use the default marker (though you can change * it's color and size) or you have the option to also pass in a custom marker icon using it's url. * * @since 2.1.0 */ @AutoValue public abstract class StaticMarkerAnnotation { /** * Build a new {@link StaticMarkerAnnotation} object with the initial values set for the * {@link #name()} to {@link StaticMapCriteria#MEDIUM_PIN}. * * @return a {@link StaticMarkerAnnotation.Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_StaticMarkerAnnotation.Builder() .name(StaticMapCriteria.MEDIUM_PIN); } /** * <em>Used Internally.</em> * * @return a String representing the marker part of the URL * @since 2.1.0 */ @RestrictTo(LIBRARY) public String url() { String url; if (iconUrl() != null) { return String.format( Locale.US, "url-%s(%f,%f)", iconUrl(), lnglat().longitude(), lnglat().latitude()); } if (color() != null && !TextUtils.isEmpty(label())) { url = String.format(Locale.US, "%s-%s+%s", name(), label(), color()); } else if (!TextUtils.isEmpty(label())) { url = String.format(Locale.US, "%s-%s", name(), label()); } else if (color() != null) { url = String.format(Locale.US, "%s+%s", name(), color()); } else { url = name(); } return String.format(Locale.US, "%s(%f,%f)", url, lnglat().longitude(), lnglat().latitude()); } @Nullable abstract String name(); @Nullable abstract String label(); @Nullable abstract String color(); @Nullable abstract Point lnglat(); @Nullable abstract String iconUrl(); /** * Convert the current {@link StaticMarkerAnnotation} to its builder holding the currently * assigned values. This allows you to modify a single variable and then rebuild the object * resulting in an updated and modified {@link StaticMarkerAnnotation}. * * @return a {@link StaticMarkerAnnotation.Builder} with the same values set to match the ones * defined in this {@link StaticMarkerAnnotation} * @since 3.1.0 */ public abstract Builder toBuilder(); /** * This builder is used to create a new request to the Nbmap Static Map API. At a bare minimum, * your request must include a name and {@link StaticMarkerAnnotation.Builder#lnglat(Point)}. * All other fields can be left alone inorder to use the default behaviour of the API. * * @since 2.1.0 */ @AutoValue.Builder public abstract static class Builder { /** * Modify the markers scale factor using one of the pre defined * {@link StaticMapCriteria#SMALL_PIN}, {@link StaticMapCriteria#MEDIUM_PIN}, or * {@link StaticMapCriteria#LARGE_PIN}. * * @param name one of the three string sizes provided in this methods summary * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder name(@MarkerCriteria String name); /** * Marker symbol. Options are an alphanumeric label "a" through "z", "0" through "99", or a * valid Maki icon. If a letter is requested, it will be rendered uppercase only. * * @param label a valid alphanumeric value * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder label(String label); /** * A hex representation of the markers color. * * @param color hex reppresentation of the marker icon color * @return this builder for chaining options together * @since 3.1.0 */ public abstract Builder color(@Nullable String color); /** * A hex representation of the markers color. * * @param red the value of the marker icon color * @param green the value of the marker icon color * @param blue the value of the marker icon color * @return this builder for chaining options together * @since 3.1.0 */ public Builder color(int red, int green, int blue) { return color(toHexString(red, green, blue)); } /** * Represents where the marker should be shown on the map. * * @param lnglat a GeoJSON Point which denotes where the marker will be placed on the static * map image. Altitude value, if given, will be ignored * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder lnglat(Point lnglat); /** * a percent-encoded URL for the marker image. Can be of type PNG or JPG. * * @param url an encoded URL for the marker image * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder iconUrl(@Nullable String url); abstract StaticMarkerAnnotation autoBuild(); /** * Build a new marker instance and pass it into * {@link com.nbmap.api.staticmap.v1.NbmapStaticMap} in order to use it during your Static Map * API request. * * @return a new instance of {@link StaticMarkerAnnotation} * @since 2.1.0 */ public StaticMarkerAnnotation build() { StaticMarkerAnnotation marker = autoBuild(); if (marker.lnglat() == null) { throw new ServicesException("A Static map marker requires a defined longitude and latitude" + " coordinate."); } return marker; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1/models/StaticPolylineAnnotation.java
package com.nbmap.api.staticmap.v1.models; import static androidx.annotation.RestrictTo.Scope.LIBRARY; import static com.nbmap.core.utils.ColorUtils.toHexString; import androidx.annotation.FloatRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import com.google.auto.value.AutoValue; import com.nbmap.api.staticmap.v1.NbmapStaticMap; import com.nbmap.geojson.utils.PolylineUtils; import java.util.List; /** * Nbmap Static Image API polyline overlay. Building this object allows you to place a line or * object on top or within your static map image. The polyline must be encoded with a precision of 5 * decimal places and can be created using the * {@link PolylineUtils#encode(List, int)}. * * @since 2.1.0 */ @AutoValue public abstract class StaticPolylineAnnotation { /** * Build a new {@link StaticPolylineAnnotation} object. * * @return a {@link StaticPolylineAnnotation.Builder} object for creating this object * @since 3.0.0 */ public static Builder builder() { return new AutoValue_StaticPolylineAnnotation.Builder(); } /** * <em>Used Internally.</em> * * @return a String representing the marker part of the URL. * @since 2.1.0 */ @RestrictTo(LIBRARY) public String url() { StringBuilder sb = new StringBuilder(); sb.append("path"); if (strokeWidth() != null) { sb.append("-").append(strokeWidth()); } if (strokeColor() != null) { sb.append("+").append(strokeColor()); } if (strokeOpacity() != null) { sb.append("-").append(strokeOpacity()); } if (fillColor() != null) { sb.append("+").append(fillColor()); } if (fillOpacity() != null) { sb.append("-").append(fillOpacity()); } sb.append("(").append(polyline()).append(")"); return sb.toString(); } @Nullable abstract Double strokeWidth(); @Nullable abstract String strokeColor(); @Nullable abstract Float strokeOpacity(); @Nullable abstract String fillColor(); @Nullable abstract Float fillOpacity(); @NonNull abstract String polyline(); /** * Convert the current {@link StaticPolylineAnnotation} to its builder holding the currently * assigned values. This allows you to modify a single variable and then rebuild * the object resulting in an updated and modified {@link StaticPolylineAnnotation}. * * @return a {@link StaticPolylineAnnotation.Builder} with the same values set to match the ones * defined in this {@link StaticPolylineAnnotation} * @since 3.1.0 */ public abstract Builder toBuilder(); /** * Builder used for passing in custom parameters. * * @since 2.1.0 */ @AutoValue.Builder public abstract static class Builder { /** * Defines the line stroke width for the path. * * @param strokeWidth a double value defining the stroke width * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder strokeWidth(@Nullable @FloatRange(from = 0) Double strokeWidth); /** * Set the line outer stroke color. * * @param strokeColor string representing hex color for the stroke color * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder strokeColor(@Nullable String strokeColor); /** * Set the line outer stroke color. * * @param red the value of the stroke color * @param green the value of the stroke color * @param blue the value of the stroke color * @return this builder for chaining options together * @since 3.1.0 */ public Builder strokeColor(int red, int green, int blue) { return strokeColor(toHexString(red, green, blue)); } /** * Value between 0, completely transparent, and 1, opaque for the line stroke. * * @param strokeOpacity value between 0 and 1 representing the stroke opacity * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder strokeOpacity( @Nullable @FloatRange(from = 0, to = 1) Float strokeOpacity); /** * Set the inner line fill color. * * @param color string representing hex color for the fill color * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder fillColor(@Nullable String color); /** * Set the inner line fill color. * * @param red the value of the fill color * @param green the value of the fill color * @param blue the value of the fill color * @return this builder for chaining options together * @since 3.1.0 */ public Builder fillColor(int red, int green, int blue) { return fillColor(toHexString(red, green, blue)); } /** * Value between 0, completely transparent, and 1, opaque for the line fill. * * @param fillOpacity value between 0 and 1 representing the fill opacity * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder fillOpacity(@Nullable @FloatRange(from = 0, to = 1) Float fillOpacity); /** * The current polyline string being used for the paths geometry. You can use * {@link PolylineUtils#decode(String, int)} to decode the string using * precision 5. * * @param polyline a String containing the paths geometry information * @return this builder for chaining options together * @since 2.1.0 */ public abstract Builder polyline(@NonNull String polyline); /** * This uses the provided parameters set using the {@link Builder} and creates a new * {@link StaticMarkerAnnotation} object which can be passed into the {@link NbmapStaticMap} * request. * * @return a new instance of {@link StaticPolylineAnnotation} * @since 2.1.0 */ public abstract StaticPolylineAnnotation build(); } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/staticmap/v1/models/package-info.java
/** * Package containing all the Static Map annotations avaliable. * * @since 3.0.0 */ package com.nbmap.api.staticmap.v1.models;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/tilequery/NbmapTilequery.java
package com.nbmap.api.tilequery; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.GsonBuilder; import com.nbmap.core.NbmapService; import com.nbmap.core.constants.Constants; import com.nbmap.core.exceptions.ServicesException; import com.nbmap.core.utils.NbmapUtils; import com.nbmap.core.utils.TextUtils; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.GeometryAdapterFactory; import com.nbmap.geojson.Point; import com.nbmap.geojson.gson.GeoJsonAdapterFactory; import java.io.IOException; import java.util.List; import java.util.Locale; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * The Nbmap Tilequery API allows you to retrieve data about specific features from a * vector tileset, based on a given latitude and longitude. * * @see <a href="https://www.nbmap.com/api-documentation/maps/#tilequery">Tilequery API * documentation</a> * * @since 3.5.0 */ @AutoValue public abstract class NbmapTilequery extends NbmapService<FeatureCollection, TilequeryService> { private Call<List<FeatureCollection>> batchCall; protected NbmapTilequery() { super(TilequeryService.class); } @Override protected GsonBuilder getGsonBuilder() { return new GsonBuilder() .registerTypeAdapterFactory(GeoJsonAdapterFactory.create()) .registerTypeAdapterFactory(GeometryAdapterFactory.create()); } @Override protected Call<FeatureCollection> initializeCall() { return getService().getCall( tilesetIds(), query(), accessToken(), radius(), limit(), dedupe(), geometry(), layers()); } private Call<List<FeatureCollection>> getBatchCall() { // No need to recreate it if (batchCall != null) { return batchCall; } batchCall = getService().getBatchCall( tilesetIds(), query(), accessToken(), radius(), limit(), dedupe(), geometry(), layers()); return batchCall; } /** * Wrapper method for Retrofit's {@link Call#execute()} call returning a batch response * specific to the Tilequery API. * * @return the Tilequery batch response once the call completes successfully * @throws IOException Signals that an I/O exception of some sort has occurred. * @since 3.5.0 */ public Response<List<FeatureCollection>> executeBatchCall() throws IOException { return getBatchCall().execute(); } /** * Wrapper method for Retrofit's {@link Call#enqueue(Callback)} call returning a batch response * specific to the Tilequery batch API. Use this method to make a tilequery request on the Main * Thread. * * @param callback a {@link Callback} which is used once the {@link FeatureCollection} is created. * @since 3.5.0 */ public void enqueueBatchCall(Callback<List<FeatureCollection>> callback) { getBatchCall().enqueue(callback); } /** * Wrapper method for Retrofit's {@link Call#cancel()} call, important to manually cancel call if * the user dismisses the calling activity or no longer needs the returned results. * * @since 3.5.0 */ public void cancelBatchCall() { getBatchCall().cancel(); } /** * Wrapper method for Retrofit's {@link Call#clone()} call, useful for getting call information. * * @return cloned call * @since 3.5.0 */ public Call<List<FeatureCollection>> cloneBatchCall() { return getBatchCall().clone(); } /** * Build a new {@link NbmapTilequery} object with the initial value set for * {@link #baseUrl()}. * * @return a {@link NbmapTilequery.Builder} object for creating this object * @since 3.5.0 */ public static Builder builder() { return new AutoValue_NbmapTilequery.Builder() .baseUrl(Constants.BASE_API_URL); } @NonNull @Override protected abstract String baseUrl(); @NonNull abstract String accessToken(); @NonNull abstract String tilesetIds(); @NonNull abstract String query(); @Nullable abstract Integer radius(); @Nullable abstract Integer limit(); @Nullable abstract Boolean dedupe(); @Nullable abstract @TilequeryCriteria.TilequeryGeometry String geometry(); @Nullable abstract String layers(); /** * This builder is used to create a new request to the Nbmap Tilequery API. At a bare minimum, * your request must include an access token, a tileset ID, and a query of some kind. All other * fields can be left alone in order to use the default behaviour of the API. * <p> * Note to contributors: All optional booleans in this builder use the object {@code Boolean} * rather than the primitive to allow for unset (null) values. * </p> * * @since 3.5.0 */ @AutoValue.Builder public abstract static class Builder { /** * Optionally change the APIs base URL to something other then the default Nbmap one. * @param baseUrl base url used as end point * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder baseUrl(@NonNull String baseUrl); /** * Required to call when this is being built. If no access token provided, * {@link ServicesException} will be thrown. * * @param accessToken Nbmap access token * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder accessToken(@NonNull String accessToken); /** * The ID of the tileset being queried. If you need to composite multiple layers, the Tilequery * API endpoint can also support a comma-separated list of tileset IDs. * * @param tilesetIds tile set ID(s) * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder tilesetIds(String tilesetIds); /** * The longitude and latitude to be queried. * * @param point query point * @return this builder for chaining options together * @since 3.5.0 */ public Builder query(@NonNull Point point) { query(String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(point.longitude()), TextUtils.formatCoordinate(point.latitude()))); String str = String.format(Locale.US, "%s,%s", TextUtils.formatCoordinate(point.longitude()), TextUtils.formatCoordinate(point.latitude())); return this; } /** * The longitude and latitude to be queried. * * @param query query point * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder query(@NonNull String query); /** * The approximate distance in meters to query for features. Defaults to 0. Has no upper * bound. Required for queries against point and line data. Due to the nature of tile * buffering, a query with a large radius made against equally large point or line data may * not include all possible features in the results. Queries will use tiles from the * maximum zoom of the tileset, and will only include the intersecting tile plus 8 * surrounding tiles when searching for nearby features. * * @param radius distance in meters to query for features * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder radius(@Nullable Integer radius); /** * The number of features between 1 - 50 to return. Defaults to 5. * * @param limit the number of features * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder limit(@Nullable Integer limit); /** * Determines whether results will be deduplicated or not. Defaults to true. * * @param dedupe whether results will be deduplicated * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder dedupe(@Nullable Boolean dedupe); /** * Queries for a specific geometry type. Options are polygon, linestring, or point. * * @param geometry polygon, linestring, or point * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder geometry( @Nullable @TilequeryCriteria.TilequeryGeometry String geometry); /** * A comma-separated list of layers to query, rather than querying all layers. If a * specified layer does not exist, it is skipped. If no layers exist, returns an * empty FeatureCollection. * * @param layers list of layers to query * @return this builder for chaining options together * @since 3.5.0 */ public abstract Builder layers(@Nullable String layers); /** * * @return this builder for chaining options together * @since 3.5.0 */ abstract NbmapTilequery autoBuild(); /** * Build a new {@link NbmapTilequery} object. * * @return this builder for chaining options together * @since 3.5.0 */ public NbmapTilequery build() { NbmapTilequery tilequery = autoBuild(); if (!NbmapUtils.isAccessTokenValid(tilequery.accessToken())) { throw new ServicesException("Using Nbmap Services requires setting a valid access token."); } if (tilequery.query().isEmpty()) { throw new ServicesException("A query with latitude and longitude values is required."); } return tilequery; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/tilequery/TilequeryCriteria.java
package com.nbmap.api.tilequery; import androidx.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Constants that should be used when using the Tilequery API. * * @since 3.5.0 */ public class TilequeryCriteria { /** * Queries for a specific geometry type (polygon). * * @since 3.5.0 */ public static final String TILEQUERY_GEOMETRY_POLYGON = "polygon"; /** * Queries for a specific geometry type (linestring). * * @since 3.5.0 */ public static final String TILEQUERY_GEOMETRY_LINESTRING = "linestring"; /** * Queries for a specific geometry type (point). * * @since 3.5.0 */ public static final String TILEQUERY_GEOMETRY_POINT = "point"; /** * Queries for a specific geometry type selector. * * @since 3.5.0 */ @Retention(RetentionPolicy.CLASS) @StringDef( { TILEQUERY_GEOMETRY_POLYGON, TILEQUERY_GEOMETRY_LINESTRING, TILEQUERY_GEOMETRY_POINT }) public @interface TilequeryGeometry { } }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/tilequery/TilequeryService.java
package com.nbmap.api.tilequery; import com.nbmap.geojson.FeatureCollection; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; /** * Interface that defines the tilequery service. * * @since 3.5.0 */ public interface TilequeryService { /** * Constructs the HTTP request for the specified parameters. * * @param tilesetIds tile set ID(s) * @param query query point * @param accessToken Nbmap access token * @param radius distance in meters to query for features * @param limit the number of features * @param dedupe whether results will be deduplicated * @param geometry polygon, linestring, or point * @param layers list of layers to query * @return A retrofit Call object * @since 3.5.0 */ @GET("/v4/{tilesetIds}/tilequery/{query}.json") Call<FeatureCollection> getCall( @Path("tilesetIds") String tilesetIds, @Path("query") String query, @Query("key") String accessToken, @Query("radius") Integer radius, @Query("limit") Integer limit, @Query("dedupe") Boolean dedupe, @Query("geometry") String geometry, @Query("layers") String layers); /** * Constructs the HTTP request for the specified parameters. * * @param tilesetIds tile set ID(s) * @param query query point * @param accessToken Nbmap access token * @param radius distance in meters to query for features * @param limit the number of features * @param dedupe whether results will be deduplicated * @param geometry polygon, linestring, or point * @param layers list of layers to query * @return A retrofit Call object * @since 3.5.0 */ @GET("/v4/{tilesetIds}/tilequery/{query}.json") Call<List<FeatureCollection>> getBatchCall( @Path("tilesetIds") String tilesetIds, @Path("query") String query, @Query("key") String accessToken, @Query("radius") Integer radius, @Query("limit") Integer limit, @Query("dedupe") Boolean dedupe, @Query("geometry") String geometry, @Query("layers") String layers); }
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/tilequery/package-info.java
/** * Contains the Nbmap Java Services classes related to the Nbmap Tilequery API. */ package com.nbmap.api.tilequery;
0
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/tilequery
java-sources/ai/nextbillion/nbmap-sdk-services/0.1.2/com/nbmap/api/tilequery/models/package-info.java
/** * Contains the Nbmap Java Services model classes related to the Nbmap Tilequery API. */ package com.nbmap.api.tilequery.models;
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfAssertions.java
package com.nbmap.turf; import com.nbmap.geojson.Feature; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.GeoJson; import com.nbmap.geojson.Point; /** * Also called Assertions, these methods enforce expectations of a certain type or calculate various * shapes from given points. * * @see <a href="http://turfjs.org/docs/">Turf documentation</a> * @since 1.2.0 */ public final class TurfAssertions { private TurfAssertions() { // Private constructor preventing initialization of this class } /** * Unwrap a coordinate {@link Point} from a Feature with a Point geometry. * * @param obj any value * @return a coordinate * @see <a href="http://turfjs.org/docs/#getcoord">Turf getCoord documentation</a> * @since 1.2.0 * @deprecated use {@link TurfMeta#getCoord(Feature)} */ @Deprecated public static Point getCoord(Feature obj) { return TurfMeta.getCoord(obj); } /** * Enforce expectations about types of GeoJson objects for Turf. * * @param value any GeoJson object * @param type expected GeoJson type * @param name name of calling function * @see <a href="http://turfjs.org/docs/#geojsontype">Turf geojsonType documentation</a> * @since 1.2.0 */ public static void geojsonType(GeoJson value, String type, String name) { if (type == null || type.length() == 0 || name == null || name.length() == 0) { throw new TurfException("Type and name required"); } if (value == null || !value.type().equals(type)) { throw new TurfException("Invalid input to " + name + ": must be a " + type + ", given " + (value != null ? value.type() : " null")); } } /** * Enforce expectations about types of {@link Feature} inputs for Turf. Internally this uses * {@link Feature#type()} to judge geometry types. * * @param feature with an expected geometry type * @param type type expected GeoJson type * @param name name of calling function * @see <a href="http://turfjs.org/docs/#featureof">Turf featureOf documentation</a> * @since 1.2.0 */ public static void featureOf(Feature feature, String type, String name) { if (name == null || name.length() == 0) { throw new TurfException(".featureOf() requires a name"); } if (feature == null || !feature.type().equals("Feature") || feature.geometry() == null) { throw new TurfException(String.format( "Invalid input to %s, Feature with geometry required", name)); } if (feature.geometry() == null || !feature.geometry().type().equals(type)) { throw new TurfException(String.format( "Invalid input to %s: must be a %s, given %s", name, type, feature.geometry().type())); } } /** * Enforce expectations about types of {@link FeatureCollection} inputs for Turf. Internally * this uses {@link Feature#type()}} to judge geometry types. * * @param featureCollection for which features will be judged * @param type expected GeoJson type * @param name name of calling function * @see <a href="http://turfjs.org/docs/#collectionof">Turf collectionOf documentation</a> * @since 1.2.0 */ public static void collectionOf(FeatureCollection featureCollection, String type, String name) { if (name == null || name.length() == 0) { throw new TurfException("collectionOf() requires a name"); } if (featureCollection == null || !featureCollection.type().equals("FeatureCollection") || featureCollection.features() == null) { throw new TurfException(String.format( "Invalid input to %s, FeatureCollection required", name)); } for (Feature feature : featureCollection.features()) { if (feature == null || !feature.type().equals("Feature") || feature.geometry() == null) { throw new TurfException(String.format( "Invalid input to %s, Feature with geometry required", name)); } if (feature.geometry() == null || !feature.geometry().type().equals(type)) { throw new TurfException(String.format( "Invalid input to %s: must be a %s, given %s", name, type, feature.geometry().type())); } } } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfClassification.java
package com.nbmap.turf; import androidx.annotation.NonNull; import com.nbmap.geojson.Point; import java.util.List; /** * Methods found in this class are meant to consume a set of information and classify it according * to a shared quality or characteristic. * * @since 3.0.0 */ public class TurfClassification { private TurfClassification() { // Private constructor preventing initialization of this class } /** * Takes a reference point and a list of {@link Point} geometries and returns the point from the * set point list closest to the reference. This calculation is geodesic. * * @param targetPoint the reference point * @param points set list of points to run against the input point * @return the closest point in the set to the reference point * @since 3.0.0 */ @NonNull public static Point nearestPoint(@NonNull Point targetPoint, @NonNull List<Point> points) { if (points.isEmpty()) { return targetPoint; } Point nearestPoint = points.get(0); double minDist = Double.POSITIVE_INFINITY; for (Point point : points) { double distanceToPoint = TurfMeasurement.distance(targetPoint, point); if (distanceToPoint < minDist) { nearestPoint = point; minDist = distanceToPoint; } } return nearestPoint; } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfConstants.java
package com.nbmap.turf; import androidx.annotation.StringDef; import com.nbmap.geojson.Point; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * This class holds the Turf constants which are useful when specifying additional information such * as units prior to executing the Turf function. For example, if I intend to get the distance * between two GeoJson Points using {@link TurfMeasurement#distance(Point, Point, String)} the third * optional parameter can define the output units. * <p> * Note that {@link TurfConversion#convertLength(double, String, String)} can be used to transform * one unit to another, such as miles to feet. * </p> * * @see <a href="http://turfjs.org/docs/">Turfjs documentation</a> * @since 1.2.0 */ public class TurfConstants { private TurfConstants() { // Private constructor preventing initialization of this class } /** * The mile is an English unit of length of linear measure equal to 5,280 feet, or 1,760 yards, * and standardised as exactly 1,609.344 meters by international agreement in 1959. * * @since 1.2.0 */ public static final String UNIT_MILES = "miles"; /** * The nautical mile per hour is known as the knot. Nautical miles and knots are almost * universally used for aeronautical and maritime navigation, because of their relationship with * degrees and minutes of latitude and the convenience of using the latitude scale on a map for * distance measuring. * * @since 1.2.0 */ public static final String UNIT_NAUTICAL_MILES = "nauticalmiles"; /** * The kilometer (American spelling) is a unit of length in the metric system, equal to one * thousand meters. It is now the measurement unit used officially for expressing distances * between geographical places on land in most of the world; notable exceptions are the United * States and the road network of the United Kingdom where the statute mile is the official unit * used. * <p> * In many Turf calculations, if a unit is not provided, the output value will fallback onto using * this unit. See {@link #UNIT_DEFAULT} for more information. * </p> * * @since 1.2.0 */ public static final String UNIT_KILOMETERS = "kilometers"; /** * The radian is the standard unit of angular measure, used in many areas of mathematics. * * @since 1.2.0 */ public static final String UNIT_RADIANS = "radians"; /** * A degree, is a measurement of a plane angle, defined so that a full rotation is 360 degrees. * * @since 1.2.0 */ public static final String UNIT_DEGREES = "degrees"; /** * The inch (abbreviation: in or &quot;) is a unit of length in the (British) imperial and United * States customary systems of measurement now formally equal to 1/36th yard but usually * understood as 1/12th of a foot. * * @since 1.2.0 */ public static final String UNIT_INCHES = "inches"; /** * The yard (abbreviation: yd) is an English unit of length, in both the British imperial and US * customary systems of measurement, that comprises 3 feet or 36 inches. * * @since 1.2.0 */ public static final String UNIT_YARDS = "yards"; /** * The metre (international spelling) or meter (American spelling) is the base unit of length in * the International System of Units (SI). * * @since 1.2.0 */ public static final String UNIT_METERS = "meters"; /** * A centimeter (American spelling) is a unit of length in the metric system, equal to one * hundredth of a meter. * * @since 1.2.0 */ public static final String UNIT_CENTIMETERS = "centimeters"; /** * The foot is a unit of length in the imperial and US customary systems of measurement. * * @since 1.2.0 */ public static final String UNIT_FEET = "feet"; /** * A centimetre (international spelling) is a unit of length in the metric system, equal to one * hundredth of a meter. * * @since 3.0.0 */ public static final String UNIT_CENTIMETRES = "centimetres"; /** * The metre (international spelling) is the base unit of length in * the International System of Units (SI). * * @since 3.0.0 */ public static final String UNIT_METRES = "metres"; /** * The kilometre (international spelling) is a unit of length in the metric system, equal to one * thousand metres. It is now the measurement unit used officially for expressing distances * between geographical places on land in most of the world; notable exceptions are the United * States and the road network of the United Kingdom where the statute mile is the official unit * used. * * @since 3.0.0 */ public static final String UNIT_KILOMETRES = "kilometres"; /** * Retention policy for the various Turf units. * * @since 3.0.0 */ @Retention(RetentionPolicy.CLASS) @StringDef( { UNIT_KILOMETRES, UNIT_METRES, UNIT_CENTIMETRES, UNIT_FEET, UNIT_CENTIMETERS, UNIT_METERS, UNIT_YARDS, UNIT_INCHES, UNIT_DEGREES, UNIT_RADIANS, UNIT_KILOMETERS, UNIT_MILES, UNIT_NAUTICAL_MILES }) public @interface TurfUnitCriteria { } /** * The default unit used in most Turf methods when no other unit is specified is kilometers. * * @since 1.2.0 */ public static final String UNIT_DEFAULT = UNIT_KILOMETERS; }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfConversion.java
package com.nbmap.turf; import androidx.annotation.FloatRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.JsonObject; import com.nbmap.geojson.Feature; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.Geometry; import com.nbmap.geojson.LineString; import com.nbmap.geojson.MultiLineString; import com.nbmap.geojson.MultiPoint; import com.nbmap.geojson.MultiPolygon; import com.nbmap.geojson.Point; import com.nbmap.geojson.Polygon; import com.nbmap.turf.TurfConstants.TurfUnitCriteria; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class is made up of methods that take in an object, convert it, and then return the object * in the desired units or object. * * @see <a href="http://turfjs.org/docs/">Turfjs documentation</a> * @since 1.2.0 */ public final class TurfConversion { private static final Map<String, Double> FACTORS; static { FACTORS = new HashMap<>(); FACTORS.put(TurfConstants.UNIT_MILES, 3960d); FACTORS.put(TurfConstants.UNIT_NAUTICAL_MILES, 3441.145d); FACTORS.put(TurfConstants.UNIT_DEGREES, 57.2957795d); FACTORS.put(TurfConstants.UNIT_RADIANS, 1d); FACTORS.put(TurfConstants.UNIT_INCHES, 250905600d); FACTORS.put(TurfConstants.UNIT_YARDS, 6969600d); FACTORS.put(TurfConstants.UNIT_METERS, 6373000d); FACTORS.put(TurfConstants.UNIT_CENTIMETERS, 6.373e+8d); FACTORS.put(TurfConstants.UNIT_KILOMETERS, 6373d); FACTORS.put(TurfConstants.UNIT_FEET, 20908792.65d); FACTORS.put(TurfConstants.UNIT_CENTIMETRES, 6.373e+8d); FACTORS.put(TurfConstants.UNIT_METRES, 6373000d); FACTORS.put(TurfConstants.UNIT_KILOMETRES, 6373d); } private TurfConversion() { // Private constructor preventing initialization of this class } /** * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, * feet. * * @param distance in real units * @param units can be degrees, radians, miles, or kilometers inches, yards, metres, meters, * kilometres, kilometers. * @return a double value representing the distance in degrees * @since 3.0.0 */ public static double lengthToDegrees(double distance, @TurfUnitCriteria String units) { return radiansToDegrees(lengthToRadians(distance, units)); } /** * Converts an angle in degrees to radians. * * @param degrees angle between 0 and 360 degrees * @return angle in radians * @since 3.1.0 */ public static double degreesToRadians(double degrees) { double radians = degrees % 360; return radians * Math.PI / 180; } /** * Converts an angle in radians to degrees. * * @param radians angle in radians * @return degrees between 0 and 360 degrees * @since 3.0.0 */ public static double radiansToDegrees(double radians) { double degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly * unit. The units used here equals the default. * * @param radians a double using unit radian * @return converted radian to distance value * @since 1.2.0 */ public static double radiansToLength(double radians) { return radiansToLength(radians, TurfConstants.UNIT_DEFAULT); } /** * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly * unit. * * @param radians a double using unit radian * @param units pass in one of the units defined in {@link TurfUnitCriteria} * @return converted radian to distance value * @since 1.2.0 */ public static double radiansToLength(double radians, @NonNull @TurfUnitCriteria String units) { return radians * FACTORS.get(units); } /** * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into * radians. * * @param distance double representing a distance value assuming the distance units is in * kilometers * @return converted distance to radians value * @since 1.2.0 */ public static double lengthToRadians(double distance) { return lengthToRadians(distance, TurfConstants.UNIT_DEFAULT); } /** * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into * radians. * * @param distance double representing a distance value * @param units pass in one of the units defined in {@link TurfUnitCriteria} * @return converted distance to radians value * @since 1.2.0 */ public static double lengthToRadians(double distance, @NonNull @TurfUnitCriteria String units) { return distance / FACTORS.get(units); } /** * Converts a distance to the default units. Use * {@link TurfConversion#convertLength(double, String, String)} to specify a unit to convert to. * * @param distance double representing a distance value * @param originalUnit of the distance, must be one of the units defined in * {@link TurfUnitCriteria} * @return converted distance in the default unit * @since 2.2.0 */ public static double convertLength(@FloatRange(from = 0) double distance, @NonNull @TurfUnitCriteria String originalUnit) { return convertLength(distance, originalUnit, TurfConstants.UNIT_DEFAULT); } /** * Converts a distance to a different unit specified. * * @param distance the distance to be converted * @param originalUnit of the distance, must be one of the units defined in * {@link TurfUnitCriteria} * @param finalUnit returned unit, {@link TurfConstants#UNIT_DEFAULT} if not specified * @return the converted distance * @since 2.2.0 */ public static double convertLength(@FloatRange(from = 0) double distance, @NonNull @TurfUnitCriteria String originalUnit, @Nullable @TurfUnitCriteria String finalUnit) { if (finalUnit == null) { finalUnit = TurfConstants.UNIT_DEFAULT; } return radiansToLength(lengthToRadians(distance, originalUnit), finalUnit); } /** * Takes a {@link FeatureCollection} and * returns all positions as {@link Point} objects. * * @param featureCollection a {@link FeatureCollection} object * @return a new {@link FeatureCollection} object with {@link Point} objects * @since 4.8.0 */ public static FeatureCollection explode(@NonNull FeatureCollection featureCollection) { List<Feature> finalFeatureList = new ArrayList<>(); for (Point singlePoint : TurfMeta.coordAll(featureCollection, true)) { finalFeatureList.add(Feature.fromGeometry(singlePoint)); } return FeatureCollection.fromFeatures(finalFeatureList); } /** * Takes a {@link Feature} and * returns its position as a {@link Point} objects. * * @param feature a {@link Feature} object * @return a new {@link FeatureCollection} object with {@link Point} objects * @since 4.8.0 */ public static FeatureCollection explode(@NonNull Feature feature) { List<Feature> finalFeatureList = new ArrayList<>(); for (Point singlePoint : TurfMeta.coordAll(feature, true)) { finalFeatureList.add(Feature.fromGeometry(singlePoint)); } return FeatureCollection.fromFeatures(finalFeatureList); } /** * Takes a {@link Feature} that contains {@link Polygon} and * covert it to a {@link Feature} that contains {@link LineString} or {@link MultiLineString}. * * @param feature a {@link Feature} object that contains {@link Polygon} * @return a {@link Feature} object that contains {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static Feature polygonToLine(@NonNull Feature feature) { return polygonToLine(feature, null); } /** * Takes a {@link Feature} that contains {@link Polygon} and a properties {@link JsonObject} and * covert it to a {@link Feature} that contains {@link LineString} or {@link MultiLineString}. * * @param feature a {@link Feature} object that contains {@link Polygon} * @param properties a {@link JsonObject} that represents a feature's properties * @return a {@link Feature} object that contains {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static Feature polygonToLine(@NonNull Feature feature, @Nullable JsonObject properties) { Geometry geometry = feature.geometry(); if (geometry instanceof Polygon) { return polygonToLine((Polygon) geometry,properties != null ? properties : feature.type().equals("Feature") ? feature.properties() : new JsonObject()); } throw new TurfException("Feature's geometry must be Polygon"); } /** * Takes a {@link Polygon} and * covert it to a {@link Feature} that contains {@link LineString} or {@link MultiLineString}. * * @param polygon a {@link Polygon} object * @return a {@link Feature} object that contains {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static Feature polygonToLine(@NonNull Polygon polygon) { return polygonToLine(polygon, null); } /** * Takes a {@link MultiPolygon} and * covert it to a {@link FeatureCollection} that contains list * of {@link Feature} of {@link LineString} or {@link MultiLineString}. * * @param multiPolygon a {@link MultiPolygon} object * @return a {@link FeatureCollection} object that contains * list of {@link Feature} of {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static FeatureCollection polygonToLine(@NonNull MultiPolygon multiPolygon) { return polygonToLine(multiPolygon, null); } /** * Takes a {@link Polygon} and a properties {@link JsonObject} and * covert it to a {@link Feature} that contains {@link LineString} or {@link MultiLineString}. * * @param polygon a {@link Polygon} object * @param properties a {@link JsonObject} that represents a feature's properties * @return a {@link Feature} object that contains {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static Feature polygonToLine(@NonNull Polygon polygon, @Nullable JsonObject properties) { return coordsToLine(polygon.coordinates(), properties); } /** * Takes a {@link MultiPolygon} and a properties {@link JsonObject} and * covert it to a {@link FeatureCollection} that contains list * of {@link Feature} of {@link LineString} or {@link MultiLineString}. * * @param multiPolygon a {@link MultiPolygon} object * @param properties a {@link JsonObject} that represents a feature's properties * @return a {@link FeatureCollection} object that contains * list of {@link Feature} of {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static FeatureCollection polygonToLine(@NonNull MultiPolygon multiPolygon, @Nullable JsonObject properties) { List<List<List<Point>>> coordinates = multiPolygon.coordinates(); List<Feature> finalFeatureList = new ArrayList<>(); for (List<List<Point>> polygonCoordinates : coordinates) { finalFeatureList.add(coordsToLine(polygonCoordinates, properties)); } return FeatureCollection.fromFeatures(finalFeatureList); } /** * Takes a {@link Feature} that contains {@link MultiPolygon} and * covert it to a {@link FeatureCollection} that contains list of {@link Feature} * of {@link LineString} or {@link MultiLineString}. * * @param feature a {@link Feature} object that contains {@link Polygon} * @return a {@link FeatureCollection} object that contains list of {@link Feature} * of {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static FeatureCollection multiPolygonToLine(@NonNull Feature feature) { return multiPolygonToLine(feature, null); } /** * Takes a {@link Feature} that contains {@link MultiPolygon} and a * properties {@link JsonObject} and * covert it to a {@link FeatureCollection} that contains * list of {@link Feature} of {@link LineString} or {@link MultiLineString}. * * @param feature a {@link Feature} object that contains {@link MultiPolygon} * @param properties a {@link JsonObject} that represents a feature's properties * @return a {@link FeatureCollection} object that contains * list of {@link Feature} of {@link LineString} or {@link MultiLineString} * @since 4.9.0 */ public static FeatureCollection multiPolygonToLine(@NonNull Feature feature, @Nullable JsonObject properties) { Geometry geometry = feature.geometry(); if (geometry instanceof MultiPolygon) { return polygonToLine((MultiPolygon) geometry, properties != null ? properties : feature.type().equals("Feature") ? feature.properties() : new JsonObject()); } throw new TurfException("Feature's geometry must be MultiPolygon"); } @Nullable private static Feature coordsToLine(@NonNull List<List<Point>> coordinates, @Nullable JsonObject properties) { if (coordinates.size() > 1) { return Feature.fromGeometry(MultiLineString.fromLngLats(coordinates), properties); } else if (coordinates.size() == 1) { LineString lineString = LineString.fromLngLats(coordinates.get(0)); return Feature.fromGeometry(lineString, properties); } return null; } /** * Combines a FeatureCollection of geometries and returns * a {@link FeatureCollection} with "Multi-" geometries in it. * If the original FeatureCollection parameter has {@link Point}(s) * and/or {@link MultiPoint}s), the returned * FeatureCollection will include a {@link MultiPoint} object. * * If the original FeatureCollection parameter has * {@link LineString}(s) and/or {@link MultiLineString}s), the returned * FeatureCollection will include a {@link MultiLineString} object. * * If the original FeatureCollection parameter has * {@link Polygon}(s) and/or {@link MultiPolygon}s), the returned * FeatureCollection will include a {@link MultiPolygon} object. * * @param originalFeatureCollection a {@link FeatureCollection} * * @return a {@link FeatureCollection} with a "Multi-" geometry * or "Multi-" geometries. * * @since 4.10.0 **/ public static FeatureCollection combine(@NonNull FeatureCollection originalFeatureCollection) { if (originalFeatureCollection.features() == null) { throw new TurfException("Your FeatureCollection is null."); } else if (originalFeatureCollection.features().size() == 0) { throw new TurfException("Your FeatureCollection doesn't have any Feature objects in it."); } List<Point> pointList = new ArrayList<>(0); List<LineString> lineStringList = new ArrayList<>(0); List<Polygon> polygonList = new ArrayList<>(0); for (Feature singleFeature : originalFeatureCollection.features()) { Geometry singleFeatureGeometry = singleFeature.geometry(); if (singleFeatureGeometry instanceof Point || singleFeatureGeometry instanceof MultiPoint) { if (singleFeatureGeometry instanceof Point) { pointList.add((Point) singleFeatureGeometry); } else { pointList.addAll(((MultiPoint) singleFeatureGeometry).coordinates()); } } else if (singleFeatureGeometry instanceof LineString || singleFeatureGeometry instanceof MultiLineString) { if (singleFeatureGeometry instanceof LineString) { lineStringList.add((LineString) singleFeatureGeometry); } else { lineStringList.addAll(((MultiLineString) singleFeatureGeometry).lineStrings()); } } else if (singleFeatureGeometry instanceof Polygon || singleFeatureGeometry instanceof MultiPolygon) { if (singleFeatureGeometry instanceof Polygon) { polygonList.add((Polygon) singleFeatureGeometry); } else { polygonList.addAll(((MultiPolygon) singleFeatureGeometry).polygons()); } } } List<Feature> finalFeatureList = new ArrayList<>(0); if (!pointList.isEmpty()) { finalFeatureList.add(Feature.fromGeometry(MultiPoint.fromLngLats(pointList))); } if (!lineStringList.isEmpty()) { finalFeatureList.add(Feature.fromGeometry(MultiLineString.fromLineStrings(lineStringList))); } if (!polygonList.isEmpty()) { finalFeatureList.add(Feature.fromGeometry(MultiPolygon.fromPolygons(polygonList))); } return finalFeatureList.isEmpty() ? originalFeatureCollection : FeatureCollection.fromFeatures(finalFeatureList); } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfException.java
package com.nbmap.turf; /** * This indicates conditions that a reasonable application might want to catch. * <p> * A {@link RuntimeException} specific to Turf calculation errors and is thrown whenever either an * unintended event occurs or the data passed into the method isn't sufficient enough to perform the * calculation. * </p> * * @see <a href="http://turfjs.org/docs/">Turfjs documentation</a> * @since 1.2.0 */ public class TurfException extends RuntimeException { /** * A form of {@link RuntimeException} that indicates conditions that a reasonable application * might want to catch. * * @param message the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @since 1.2.0 */ public TurfException(String message) { super(message); } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfJoins.java
package com.nbmap.turf; import com.nbmap.geojson.Feature; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.Point; import com.nbmap.geojson.Polygon; import com.nbmap.geojson.MultiPolygon; import java.util.ArrayList; import java.util.List; /** * Class contains methods that can determine if points lie within a polygon or not. * * @see <a href="http://turfjs.org/docs/">Turf documentation</a> * @since 1.3.0 */ public final class TurfJoins { private TurfJoins() { // Private constructor preventing initialization of this class } /** * Takes a {@link Point} and a {@link Polygon} and determines if the point resides inside the * polygon. The polygon can be convex or concave. The function accounts for holes. * * @param point which you'd like to check if inside the polygon * @param polygon which you'd like to check if the points inside * @return true if the Point is inside the Polygon; false if the Point is not inside the Polygon * @see <a href="http://turfjs.org/docs/#inside">Turf Inside documentation</a> * @since 1.3.0 */ public static boolean inside(Point point, Polygon polygon) { // This API needs to get better List<List<Point>> coordinates = polygon.coordinates(); List<List<List<Point>>> multiCoordinates = new ArrayList<>(); multiCoordinates.add(coordinates); return inside(point, MultiPolygon.fromLngLats(multiCoordinates)); } /** * Takes a {@link Point} and a {@link MultiPolygon} and determines if the point resides inside * the polygon. The polygon can be convex or concave. The function accounts for holes. * * @param point which you'd like to check if inside the polygon * @param multiPolygon which you'd like to check if the points inside * @return true if the Point is inside the MultiPolygon; false if the Point is not inside the * MultiPolygon * @see <a href="http://turfjs.org/docs/#inside">Turf Inside documentation</a> * @since 1.3.0 */ public static boolean inside(Point point, MultiPolygon multiPolygon) { List<List<List<Point>>> polys = multiPolygon.coordinates(); boolean insidePoly = false; for (int i = 0; i < polys.size() && !insidePoly; i++) { // check if it is in the outer ring first if (inRing(point, polys.get(i).get(0))) { boolean inHole = false; int temp = 1; // check for the point in any of the holes while (temp < polys.get(i).size() && !inHole) { if (inRing(point, polys.get(i).get(temp))) { inHole = true; } temp++; } if (!inHole) { insidePoly = true; } } } return insidePoly; } /** * Takes a {@link FeatureCollection} of {@link Point} and a {@link FeatureCollection} of * {@link Polygon} and returns the points that fall within the polygons. * * @param points input points. * @param polygons input polygons. * @return points that land within at least one polygon. * @since 1.3.0 */ public static FeatureCollection pointsWithinPolygon(FeatureCollection points, FeatureCollection polygons) { ArrayList<Feature> features = new ArrayList<>(); for (int i = 0; i < polygons.features().size(); i++) { for (int j = 0; j < points.features().size(); j++) { Point point = (Point) points.features().get(j).geometry(); boolean isInside = TurfJoins.inside(point, (Polygon) polygons.features().get(i).geometry()); if (isInside) { features.add(Feature.fromGeometry(point)); } } } return FeatureCollection.fromFeatures(features); } // pt is [x,y] and ring is [[x,y], [x,y],..] private static boolean inRing(Point pt, List<Point> ring) { boolean isInside = false; for (int i = 0, j = ring.size() - 1; i < ring.size(); j = i++) { double xi = ring.get(i).longitude(); double yi = ring.get(i).latitude(); double xj = ring.get(j).longitude(); double yj = ring.get(j).latitude(); boolean intersect = ( (yi > pt.latitude()) != (yj > pt.latitude())) && (pt.longitude() < (xj - xi) * (pt.latitude() - yi) / (yj - yi) + xi); if (intersect) { isInside = !isInside; } } return isInside; } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfMeasurement.java
package com.nbmap.turf; import static com.nbmap.turf.TurfConversion.degreesToRadians; import static com.nbmap.turf.TurfConversion.radiansToDegrees; import androidx.annotation.FloatRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.JsonObject; import com.nbmap.geojson.BoundingBox; import com.nbmap.geojson.Feature; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.GeoJson; import com.nbmap.geojson.Geometry; import com.nbmap.geojson.GeometryCollection; import com.nbmap.geojson.LineString; import com.nbmap.geojson.MultiLineString; import com.nbmap.geojson.MultiPoint; import com.nbmap.geojson.MultiPolygon; import com.nbmap.geojson.Point; import com.nbmap.geojson.Polygon; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Class contains an assortment of methods used to calculate measurements such as bearing, * destination, midpoint, etc. * * @see <a href="http://turfjs.org/docs/">Turf documentation</a> * @since 1.2.0 */ public final class TurfMeasurement { private TurfMeasurement() { throw new AssertionError("No Instances."); } /** * Earth's radius in meters. */ public static double EARTH_RADIUS = 6378137; /** * Takes two {@link Point}s and finds the geographic bearing between them. * * @param point1 first point used for calculating the bearing * @param point2 second point used for calculating the bearing * @return bearing in decimal degrees * @see <a href="http://turfjs.org/docs/#bearing">Turf Bearing documentation</a> * @since 1.3.0 */ public static double bearing(@NonNull Point point1, @NonNull Point point2) { double lon1 = degreesToRadians(point1.longitude()); double lon2 = degreesToRadians(point2.longitude()); double lat1 = degreesToRadians(point1.latitude()); double lat2 = degreesToRadians(point2.latitude()); double value1 = Math.sin(lon2 - lon1) * Math.cos(lat2); double value2 = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1); return radiansToDegrees(Math.atan2(value1, value2)); } /** * Takes a Point and calculates the location of a destination point given a distance in * degrees, radians, miles, or kilometers; and bearing in degrees. This uses the Haversine * formula to account for global curvature. * * @param point starting point used for calculating the destination * @param distance distance from the starting point * @param bearing ranging from -180 to 180 in decimal degrees * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return destination {@link Point} result where you specified * @see <a href="http://turfjs.org/docs/#destination">Turf Destination documetation</a> * @since 1.2.0 */ @NonNull public static Point destination(@NonNull Point point, @FloatRange(from = 0) double distance, @FloatRange(from = -180, to = 180) double bearing, @NonNull @TurfConstants.TurfUnitCriteria String units) { double longitude1 = degreesToRadians(point.longitude()); double latitude1 = degreesToRadians(point.latitude()); double bearingRad = degreesToRadians(bearing); double radians = TurfConversion.lengthToRadians(distance, units); double latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) + Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearingRad)); double longitude2 = longitude1 + Math.atan2(Math.sin(bearingRad) * Math.sin(radians) * Math.cos(latitude1), Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2)); return Point.fromLngLat( radiansToDegrees(longitude2), radiansToDegrees(latitude2)); } /** * Calculates the distance between two points in kilometers. This uses the Haversine formula to * account for global curvature. * * @param point1 first point used for calculating the bearing * @param point2 second point used for calculating the bearing * @return distance between the two points in kilometers * @see <a href="http://turfjs.org/docs/#distance">Turf distance documentation</a> * @since 1.2.0 */ public static double distance(@NonNull Point point1, @NonNull Point point2) { return distance(point1, point2, TurfConstants.UNIT_DEFAULT); } /** * Calculates the distance between two points in degress, radians, miles, or kilometers. This * uses the Haversine formula to account for global curvature. * * @param point1 first point used for calculating the bearing * @param point2 second point used for calculating the bearing * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return distance between the two points in kilometers * @see <a href="http://turfjs.org/docs/#distance">Turf distance documentation</a> * @since 1.2.0 */ public static double distance(@NonNull Point point1, @NonNull Point point2, @NonNull @TurfConstants.TurfUnitCriteria String units) { double difLat = degreesToRadians((point2.latitude() - point1.latitude())); double difLon = degreesToRadians((point2.longitude() - point1.longitude())); double lat1 = degreesToRadians(point1.latitude()); double lat2 = degreesToRadians(point2.latitude()); double value = Math.pow(Math.sin(difLat / 2), 2) + Math.pow(Math.sin(difLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); return TurfConversion.radiansToLength( 2 * Math.atan2(Math.sqrt(value), Math.sqrt(1 - value)), units); } /** * Takes a {@link LineString} and measures its length in the specified units. * * @param lineString geometry to measure * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return length of the input line in the units specified * @see <a href="http://turfjs.org/docs/#linedistance">Turf Line Distance documentation</a> * @since 1.2.0 */ public static double length(@NonNull LineString lineString, @NonNull @TurfConstants.TurfUnitCriteria String units) { List<Point> coordinates = lineString.coordinates(); return length(coordinates, units); } /** * Takes a {@link MultiLineString} and measures its length in the specified units. * * @param multiLineString geometry to measure * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return length of the input lines combined, in the units specified * @see <a href="http://turfjs.org/docs/#linedistance">Turf Line Distance documentation</a> * @since 1.2.0 */ public static double length(@NonNull MultiLineString multiLineString, @NonNull @TurfConstants.TurfUnitCriteria String units) { double len = 0; for (List<Point> points : multiLineString.coordinates()) { len += length(points, units); } return len; } /** * Takes a {@link Polygon} and measures its perimeter in the specified units. if the polygon * contains holes, the perimeter will also be included. * * @param polygon geometry to measure * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return total perimeter of the input polygon in the units specified * @see <a href="http://turfjs.org/docs/#linedistance">Turf Line Distance documentation</a> * @since 1.2.0 */ public static double length(@NonNull Polygon polygon, @NonNull @TurfConstants.TurfUnitCriteria String units) { double len = 0; for (List<Point> points : polygon.coordinates()) { len += length(points, units); } return len; } /** * Takes a {@link MultiPolygon} and measures each polygons perimeter in the specified units. if * one of the polygons contains holes, the perimeter will also be included. * * @param multiPolygon geometry to measure * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return total perimeter of the input polygons combined, in the units specified * @see <a href="http://turfjs.org/docs/#linedistance">Turf Line Distance documentation</a> * @since 1.2.0 */ public static double length(@NonNull MultiPolygon multiPolygon, @NonNull @TurfConstants.TurfUnitCriteria String units) { double len = 0; List<List<List<Point>>> coordinates = multiPolygon.coordinates(); for (List<List<Point>> coordinate : coordinates) { for (List<Point> theCoordinate : coordinate) { len += length(theCoordinate, units); } } return len; } /** * Takes a {@link List} of {@link Point} and measures its length in the specified units. * * @param coords geometry to measure * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return length of the input line in the units specified * @see <a href="http://turfjs.org/docs/#linedistance">Turf Line Distance documentation</a> * @since 5.2.0 */ public static double length(List<Point> coords, String units) { double travelled = 0; Point prevCoords = coords.get(0); Point curCoords; for (int i = 1; i < coords.size(); i++) { curCoords = coords.get(i); travelled += distance(prevCoords, curCoords, units); prevCoords = curCoords; } return travelled; } /** * Takes two {@link Point}s and returns a point midway between them. The midpoint is calculated * geodesically, meaning the curvature of the earth is taken into account. * * @param from first point used for calculating the midpoint * @param to second point used for calculating the midpoint * @return a {@link Point} midway between point1 and point2 * @see <a href="http://turfjs.org/docs/#midpoint">Turf Midpoint documentation</a> * @since 1.3.0 */ public static Point midpoint(@NonNull Point from, @NonNull Point to) { double dist = distance(from, to, TurfConstants.UNIT_MILES); double heading = bearing(from, to); return destination(from, dist / 2, heading, TurfConstants.UNIT_MILES); } /** * Takes a line and returns a point at a specified distance along the line. * * @param line that the point should be placed upon * @param distance along the linestring geometry which the point should be placed on * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return a {@link Point} which is on the linestring provided and at the distance from * the origin of that line to the end of the distance * @since 1.3.0 */ public static Point along(@NonNull LineString line, @FloatRange(from = 0) double distance, @NonNull @TurfConstants.TurfUnitCriteria String units) { return along(line.coordinates(), distance, units); } /** * Takes a list of points and returns a point at a specified distance along the line. * * @param coords that the point should be placed upon * @param distance along the linestring geometry which the point should be placed on * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return a {@link Point} which is on the linestring provided and at the distance from * the origin of that line to the end of the distance * @since 5.2.0 */ public static Point along(@NonNull List<Point> coords, @FloatRange(from = 0) double distance, @NonNull @TurfConstants.TurfUnitCriteria String units) { double travelled = 0; for (int i = 0; i < coords.size(); i++) { if (distance >= travelled && i == coords.size() - 1) { break; } else if (travelled >= distance) { double overshot = distance - travelled; if (overshot == 0) { return coords.get(i); } else { double direction = bearing(coords.get(i), coords.get(i - 1)) - 180; return destination(coords.get(i), overshot, direction, units); } } else { travelled += distance(coords.get(i), coords.get(i + 1), units); } } return coords.get(coords.size() - 1); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param point a {@link Point} object * @return A double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 2.0.0 */ public static double[] bbox(@NonNull Point point) { List<Point> resultCoords = TurfMeta.coordAll(point); return bboxCalculator(resultCoords); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param lineString a {@link LineString} object * @return A double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 2.0.0 */ public static double[] bbox(@NonNull LineString lineString) { List<Point> resultCoords = TurfMeta.coordAll(lineString); return bboxCalculator(resultCoords); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param multiPoint a {@link MultiPoint} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 2.0.0 */ public static double[] bbox(@NonNull MultiPoint multiPoint) { List<Point> resultCoords = TurfMeta.coordAll(multiPoint); return bboxCalculator(resultCoords); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param polygon a {@link Polygon} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 2.0.0 */ public static double[] bbox(@NonNull Polygon polygon) { List<Point> resultCoords = TurfMeta.coordAll(polygon, false); return bboxCalculator(resultCoords); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param multiLineString a {@link MultiLineString} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 2.0.0 */ public static double[] bbox(@NonNull MultiLineString multiLineString) { List<Point> resultCoords = TurfMeta.coordAll(multiLineString); return bboxCalculator(resultCoords); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param multiPolygon a {@link MultiPolygon} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 2.0.0 */ public static double[] bbox(MultiPolygon multiPolygon) { List<Point> resultCoords = TurfMeta.coordAll(multiPolygon, false); return bboxCalculator(resultCoords); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param geoJson a {@link GeoJson} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 4.8.0 */ public static double[] bbox(GeoJson geoJson) { BoundingBox boundingBox = geoJson.bbox(); if (boundingBox != null) { return new double[] { boundingBox.west(), boundingBox.south(), boundingBox.east(), boundingBox.north() }; } if (geoJson instanceof Geometry) { return bbox((Geometry) geoJson); } else if (geoJson instanceof FeatureCollection) { return bbox((FeatureCollection) geoJson); } else if (geoJson instanceof Feature) { return bbox((Feature) geoJson); } else { throw new UnsupportedOperationException("bbox type not supported for GeoJson instance"); } } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param featureCollection a {@link FeatureCollection} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 4.8.0 */ public static double[] bbox(FeatureCollection featureCollection) { return bboxCalculator(TurfMeta.coordAll(featureCollection, false)); } /** * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. * * @param feature a {@link Feature} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 4.8.0 */ public static double[] bbox(Feature feature) { return bboxCalculator(TurfMeta.coordAll(feature, false)); } /** * Takes an arbitrary {@link Geometry} and calculates a bounding box. * * @param geometry a {@link Geometry} object * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]} * @since 2.0.0 */ public static double[] bbox(Geometry geometry) { if (geometry instanceof Point) { return bbox((Point) geometry); } else if (geometry instanceof MultiPoint) { return bbox((MultiPoint) geometry); } else if (geometry instanceof LineString) { return bbox((LineString) geometry); } else if (geometry instanceof MultiLineString) { return bbox((MultiLineString) geometry); } else if (geometry instanceof Polygon) { return bbox((Polygon) geometry); } else if (geometry instanceof MultiPolygon) { return bbox((MultiPolygon) geometry); } else if (geometry instanceof GeometryCollection) { List<Point> points = new ArrayList<>(); for (Geometry geo : ((GeometryCollection) geometry).geometries()) { // recursive double[] bbox = bbox(geo); points.add(Point.fromLngLat(bbox[0], bbox[1])); points.add(Point.fromLngLat(bbox[2], bbox[1])); points.add(Point.fromLngLat(bbox[2], bbox[3])); points.add(Point.fromLngLat(bbox[0], bbox[3])); } return TurfMeasurement.bbox(MultiPoint.fromLngLats(points)); } else { throw new RuntimeException(("Unknown geometry class: " + geometry.getClass())); } } private static double[] bboxCalculator(List<Point> resultCoords) { double[] bbox = new double[4]; bbox[0] = Double.POSITIVE_INFINITY; bbox[1] = Double.POSITIVE_INFINITY; bbox[2] = Double.NEGATIVE_INFINITY; bbox[3] = Double.NEGATIVE_INFINITY; for (Point point : resultCoords) { if (bbox[0] > point.longitude()) { bbox[0] = point.longitude(); } if (bbox[1] > point.latitude()) { bbox[1] = point.latitude(); } if (bbox[2] < point.longitude()) { bbox[2] = point.longitude(); } if (bbox[3] < point.latitude()) { bbox[3] = point.latitude(); } } return bbox; } /** * Takes a {@link BoundingBox} and uses its coordinates to create a {@link Polygon} * geometry. * * @param boundingBox a {@link BoundingBox} object to calculate with * @return a {@link Feature} object * @see <a href="http://turfjs.org/docs/#bboxPolygon">Turf BoundingBox Polygon documentation</a> * @since 4.9.0 */ public static Feature bboxPolygon(@NonNull BoundingBox boundingBox) { return bboxPolygon(boundingBox, null, null); } /** * Takes a {@link BoundingBox} and uses its coordinates to create a {@link Polygon} * geometry. * * @param boundingBox a {@link BoundingBox} object to calculate with * @param properties a {@link JsonObject} containing the feature properties * @param id common identifier of this feature * @return a {@link Feature} object * @see <a href="http://turfjs.org/docs/#bboxPolygon">Turf BoundingBox Polygon documentation</a> * @since 4.9.0 */ public static Feature bboxPolygon(@NonNull BoundingBox boundingBox, @Nullable JsonObject properties, @Nullable String id) { return Feature.fromGeometry(Polygon.fromLngLats( Collections.singletonList( Arrays.asList( Point.fromLngLat(boundingBox.west(), boundingBox.south()), Point.fromLngLat(boundingBox.east(), boundingBox.south()), Point.fromLngLat(boundingBox.east(), boundingBox.north()), Point.fromLngLat(boundingBox.west(), boundingBox.north()), Point.fromLngLat(boundingBox.west(), boundingBox.south())))), properties, id); } /** * Takes a bbox and uses its coordinates to create a {@link Polygon} geometry. * * @param bbox a double[] object to calculate with * @return a {@link Feature} object * @see <a href="http://turfjs.org/docs/#bboxPolygon">Turf BoundingBox Polygon documentation</a> * @since 4.9.0 */ public static Feature bboxPolygon(@NonNull double[] bbox) { return bboxPolygon(bbox, null, null); } /** * Takes a bbox and uses its coordinates to create a {@link Polygon} geometry. * * @param bbox a double[] object to calculate with * @param properties a {@link JsonObject} containing the feature properties * @param id common identifier of this feature * @return a {@link Feature} object * @see <a href="http://turfjs.org/docs/#bboxPolygon">Turf BoundingBox Polygon documentation</a> * @since 4.9.0 */ public static Feature bboxPolygon(@NonNull double[] bbox, @Nullable JsonObject properties, @Nullable String id) { return Feature.fromGeometry(Polygon.fromLngLats( Collections.singletonList( Arrays.asList( Point.fromLngLat(bbox[0], bbox[1]), Point.fromLngLat(bbox[2], bbox[1]), Point.fromLngLat(bbox[2], bbox[3]), Point.fromLngLat(bbox[0], bbox[3]), Point.fromLngLat(bbox[0], bbox[1])))), properties, id); } /** * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. * * @param geoJson input features * @return a rectangular Polygon feature that encompasses all vertices * @since 4.9.0 */ public static Polygon envelope(GeoJson geoJson) { return (Polygon) bboxPolygon(bbox(geoJson)).geometry(); } /** * Takes a bounding box and calculates the minimum square bounding box * that would contain the input. * * @param boundingBox extent in west, south, east, north order * @return a square surrounding bbox * @since 4.9.0 */ public static BoundingBox square(@NonNull BoundingBox boundingBox) { double horizontalDistance = distance(boundingBox.southwest(), Point.fromLngLat(boundingBox.east(), boundingBox.south()) ); double verticalDistance = distance( Point.fromLngLat(boundingBox.west(), boundingBox.south()), Point.fromLngLat(boundingBox.west(), boundingBox.north()) ); if (horizontalDistance >= verticalDistance) { double verticalMidpoint = (boundingBox.south() + boundingBox.north()) / 2; return BoundingBox.fromLngLats( boundingBox.west(), verticalMidpoint - ((boundingBox.east() - boundingBox.west()) / 2), boundingBox.east(), verticalMidpoint + ((boundingBox.east() - boundingBox.west()) / 2) ); } else { double horizontalMidpoint = (boundingBox.west() + boundingBox.east()) / 2; return BoundingBox.fromLngLats( horizontalMidpoint - ((boundingBox.north() - boundingBox.south()) / 2), boundingBox.south(), horizontalMidpoint + ((boundingBox.north() - boundingBox.south()) / 2), boundingBox.north() ); } } /** * Takes one {@link Feature} and returns it's area in square meters. * * @param feature input {@link Feature} * @return area in square meters * @since 4.10.0 */ public static double area(@NonNull Feature feature) { return feature.geometry() != null ? area(feature.geometry()) : 0.0f; } /** * Takes one {@link FeatureCollection} and returns it's area in square meters. * * @param featureCollection input {@link FeatureCollection} * @return area in square meters * @since 4.10.0 */ public static double area(@NonNull FeatureCollection featureCollection) { List<Feature> features = featureCollection.features(); double total = 0.0f; if (features != null) { for (Feature feature : features) { total += area(feature); } } return total; } /** * Takes one {@link Geometry} and returns its area in square meters. * * @param geometry input {@link Geometry} * @return area in square meters * @since 4.10.0 */ public static double area(@NonNull Geometry geometry) { return calculateArea(geometry); } private static double calculateArea(@NonNull Geometry geometry) { double total = 0.0f; if (geometry instanceof Polygon) { return polygonArea(((Polygon) geometry).coordinates()); } else if (geometry instanceof MultiPolygon) { List<List<List<Point>>> coordinates = ((MultiPolygon) geometry).coordinates(); for (int i = 0; i < coordinates.size(); i++) { total += polygonArea(coordinates.get(i)); } return total; } else { // Area should be 0 for case Point, MultiPoint, LineString and MultiLineString return 0.0f; } } private static double polygonArea(@NonNull List<List<Point>> coordinates) { double total = 0.0f; if (coordinates.size() > 0) { total += Math.abs(ringArea(coordinates.get(0))); for (int i = 1; i < coordinates.size(); i++) { total -= Math.abs(ringArea(coordinates.get(i))); } } return total; } /** * Calculate the approximate area of the polygon were it projected onto the earth. * Note that this area will be positive if ring is oriented clockwise, otherwise * it will be negative. * * Reference: * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for Polygons on a Sphere", * JPL Publication 07-03, Jet Propulsion * Laboratory, Pasadena, CA, June 2007 https://trs.jpl.nasa.gov/handle/2014/41271 * * @param coordinates A list of {@link Point} of Ring Coordinates * @return The approximate signed geodesic area of the polygon in square meters. */ private static double ringArea(@NonNull List<Point> coordinates) { Point p1; Point p2; Point p3; int lowerIndex; int middleIndex; int upperIndex; double total = 0.0f; final int coordsLength = coordinates.size(); if (coordsLength > 2) { for (int i = 0; i < coordsLength; i++) { if (i == coordsLength - 2) { // i = N-2 lowerIndex = coordsLength - 2; middleIndex = coordsLength - 1; upperIndex = 0; } else if (i == coordsLength - 1) { // i = N-1 lowerIndex = coordsLength - 1; middleIndex = 0; upperIndex = 1; } else { // i = 0 to N-3 lowerIndex = i; middleIndex = i + 1; upperIndex = i + 2; } p1 = coordinates.get(lowerIndex); p2 = coordinates.get(middleIndex); p3 = coordinates.get(upperIndex); total += (rad(p3.longitude()) - rad(p1.longitude())) * Math.sin(rad(p2.latitude())); } total = total * EARTH_RADIUS * EARTH_RADIUS / 2; } return total; } private static double rad(double num) { return num * Math.PI / 180; } /** * Takes a {@link Feature} and returns the absolute center of the {@link Feature}. * * @param feature the single {@link Feature} to find the center of. * @param properties a optional {@link JsonObject} containing the properties that should be * placed in the returned {@link Feature}. * @param id an optional common identifier that should be placed in the returned {@link Feature}. * @return a {@link Feature} with a {@link Point} geometry type. * @since 5.3.0 */ public static Feature center(Feature feature, @Nullable JsonObject properties, @Nullable String id) { return center(FeatureCollection.fromFeature(feature), properties, id); } /** * Takes a {@link Feature} and returns the absolute center of the {@link Feature}. * * @param feature the single {@link Feature} to find the center of. * @return a {@link Feature} with a {@link Point} geometry type. * @since 5.3.0 */ public static Feature center(Feature feature) { return center(FeatureCollection.fromFeature(feature), null, null); } /** * Takes {@link FeatureCollection} and returns the absolute center * of the {@link Feature}s in the {@link FeatureCollection}. * * @param featureCollection the single {@link FeatureCollection} to find the center of. * @param properties a optional {@link JsonObject} containing the properties that should be * placed in the returned {@link Feature}. * @param id an optional common identifier that should be placed in the returned {@link Feature}. * @return a {@link Feature} with a {@link Point} geometry type. * @since 5.3.0 */ public static Feature center(FeatureCollection featureCollection, @Nullable JsonObject properties, @Nullable String id) { double[] ext = bbox(featureCollection); double finalCenterLongitude = (ext[0] + ext[2]) / 2; double finalCenterLatitude = (ext[1] + ext[3]) / 2; return Feature.fromGeometry(Point.fromLngLat(finalCenterLongitude, finalCenterLatitude), properties, id); } /** * Takes {@link FeatureCollection} and returns the absolute center * of the {@link Feature}s in the {@link FeatureCollection}. * * @param featureCollection the single {@link FeatureCollection} to find the center of. * @return a {@link Feature} with a {@link Point} geometry type. * @since 5.3.0 */ public static Feature center(FeatureCollection featureCollection) { return center(featureCollection, null, null); } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfMeta.java
package com.nbmap.turf; import androidx.annotation.NonNull; import com.nbmap.geojson.Feature; import com.nbmap.geojson.FeatureCollection; import com.nbmap.geojson.Geometry; import com.nbmap.geojson.GeometryCollection; import com.nbmap.geojson.LineString; import com.nbmap.geojson.MultiLineString; import com.nbmap.geojson.MultiPoint; import com.nbmap.geojson.MultiPolygon; import com.nbmap.geojson.Point; import com.nbmap.geojson.Polygon; import java.util.ArrayList; import java.util.List; /** * Class contains methods that are useful for getting all coordinates from a specific GeoJson * geometry. * * @see <a href="http://turfjs.org/docs/">Turf documentation</a> * @since 2.0.0 */ public final class TurfMeta { private TurfMeta() { // Private constructor preventing initialization of this class } /** * Get all coordinates from a {@link Point} object, returning a {@code List} of Point objects. * If you have a geometry collection, you need to break it down to individual geometry objects * before using {@link #coordAll}. * * @param point any {@link Point} object * @return a {@code List} made up of {@link Point}s * @since 2.0.0 */ @NonNull public static List<Point> coordAll(@NonNull Point point) { return coordAll(new ArrayList<Point>(), point); } /** * Private helper method to go with {@link TurfMeta#coordAll(Point)}. * * @param coords the {@code List} of {@link Point}s. * @param point any {@link Point} object * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull Point point) { coords.add(point); return coords; } /** * Get all coordinates from a {@link MultiPoint} object, returning a {@code List} of Point * objects. If you have a geometry collection, you need to break it down to individual geometry * objects before using {@link #coordAll}. * * @param multiPoint any {@link MultiPoint} object * @return a {@code List} made up of {@link Point}s * @since 2.0.0 */ @NonNull public static List<Point> coordAll(@NonNull MultiPoint multiPoint) { return coordAll(new ArrayList<Point>(), multiPoint); } /** * Private helper method to go with {@link TurfMeta#coordAll(MultiPoint)}. * * @param coords the {@code List} of {@link Point}s. * @param multiPoint any {@link MultiPoint} object * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull MultiPoint multiPoint) { coords.addAll(multiPoint.coordinates()); return coords; } /** * Get all coordinates from a {@link LineString} object, returning a {@code List} of Point * objects. If you have a geometry collection, you need to break it down to individual geometry * objects before using {@link #coordAll}. * * @param lineString any {@link LineString} object * @return a {@code List} made up of {@link Point}s * @since 2.0.0 */ @NonNull public static List<Point> coordAll(@NonNull LineString lineString) { return coordAll(new ArrayList<Point>(), lineString); } /** * Private helper method to go with {@link TurfMeta#coordAll(LineString)}. * * @param coords the {@code List} of {@link Point}s. * @param lineString any {@link LineString} object * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull LineString lineString) { coords.addAll(lineString.coordinates()); return coords; } /** * Get all coordinates from a {@link Polygon} object, returning a {@code List} of Point objects. * If you have a geometry collection, you need to break it down to individual geometry objects * before using {@link #coordAll}. * * @param polygon any {@link Polygon} object * @param excludeWrapCoord whether or not to include the final coordinate of LinearRings that * wraps the ring in its iteration * @return a {@code List} made up of {@link Point}s * @since 2.0.0 */ @NonNull public static List<Point> coordAll(@NonNull Polygon polygon, @NonNull boolean excludeWrapCoord) { return coordAll(new ArrayList<Point>(), polygon, excludeWrapCoord); } /** * Private helper method to go with {@link TurfMeta#coordAll(Polygon, boolean)}. * * @param coords the {@code List} of {@link Point}s. * @param polygon any {@link Polygon} object * @param excludeWrapCoord whether or not to include the final * coordinate of LinearRings that * wraps the ring in its iteration * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull Polygon polygon, @NonNull boolean excludeWrapCoord) { int wrapShrink = excludeWrapCoord ? 1 : 0; for (int i = 0; i < polygon.coordinates().size(); i++) { for (int j = 0; j < polygon.coordinates().get(i).size() - wrapShrink; j++) { coords.add(polygon.coordinates().get(i).get(j)); } } return coords; } /** * Get all coordinates from a {@link MultiLineString} object, returning * a {@code List} of Point objects. If you have a geometry collection, you * need to break it down to individual geometry objects before using * {@link #coordAll}. * * @param multiLineString any {@link MultiLineString} object * @return a {@code List} made up of {@link Point}s * @since 2.0.0 */ @NonNull public static List<Point> coordAll(@NonNull MultiLineString multiLineString) { return coordAll(new ArrayList<Point>(), multiLineString); } /** * Private helper method to go with {@link TurfMeta#coordAll(MultiLineString)}. * * @param coords the {@code List} of {@link Point}s. * @param multiLineString any {@link MultiLineString} object * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull MultiLineString multiLineString) { for (int i = 0; i < multiLineString.coordinates().size(); i++) { coords.addAll(multiLineString.coordinates().get(i)); } return coords; } /** * Get all coordinates from a {@link MultiPolygon} object, returning a {@code List} of Point * objects. If you have a geometry collection, you need to break it down to individual geometry * objects before using {@link #coordAll}. * * @param multiPolygon any {@link MultiPolygon} object * @param excludeWrapCoord whether or not to include the final coordinate of LinearRings that * wraps the ring in its iteration. Used to handle {@link Polygon} and * {@link MultiPolygon} geometries. * @return a {@code List} made up of {@link Point}s * @since 2.0.0 */ @NonNull public static List<Point> coordAll(@NonNull MultiPolygon multiPolygon, @NonNull boolean excludeWrapCoord) { return coordAll(new ArrayList<Point>(), multiPolygon, excludeWrapCoord); } /** * Private helper method to go with {@link TurfMeta#coordAll(MultiPolygon, boolean)}. * * @param coords the {@code List} of {@link Point}s. * @param multiPolygon any {@link MultiPolygon} object * @param excludeWrapCoord whether or not to include the final coordinate of LinearRings that * wraps the ring in its iteration. Used to handle {@link Polygon} and * {@link MultiPolygon} geometries. * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull MultiPolygon multiPolygon, @NonNull boolean excludeWrapCoord) { int wrapShrink = excludeWrapCoord ? 1 : 0; for (int i = 0; i < multiPolygon.coordinates().size(); i++) { for (int j = 0; j < multiPolygon.coordinates().get(i).size(); j++) { for (int k = 0; k < multiPolygon.coordinates().get(i).get(j).size() - wrapShrink; k++) { coords.add(multiPolygon.coordinates().get(i).get(j).get(k)); } } } return coords; } /** * Get all coordinates from a {@link Feature} object, returning a {@code List} of {@link Point} * objects. * * @param feature the {@link Feature} that you'd like to extract the Points from. * @param excludeWrapCoord whether or not to include the final coordinate of LinearRings that * wraps the ring in its iteration. Used if the {@link Feature} * passed through the method is a {@link Polygon} or {@link MultiPolygon} * geometry. * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull public static List<Point> coordAll(@NonNull Feature feature, @NonNull boolean excludeWrapCoord) { return addCoordAll(new ArrayList<Point>(), feature, excludeWrapCoord); } /** * Get all coordinates from a {@link FeatureCollection} object, returning a * {@code List} of {@link Point} objects. * * @param featureCollection the {@link FeatureCollection} that you'd like * to extract the Points from. * @param excludeWrapCoord whether or not to include the final coordinate of LinearRings that * wraps the ring in its iteration. Used if a {@link Feature} in the * {@link FeatureCollection} that's passed through this method, is a * {@link Polygon} or {@link MultiPolygon} geometry. * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull public static List<Point> coordAll(@NonNull FeatureCollection featureCollection, @NonNull boolean excludeWrapCoord) { List<Point> finalCoordsList = new ArrayList<>(); for (Feature singleFeature : featureCollection.features()) { addCoordAll(finalCoordsList, singleFeature, excludeWrapCoord); } return finalCoordsList; } /** * Private helper method to be used with other methods in this class. * * @param pointList the {@code List} of {@link Point}s. * @param feature the {@link Feature} that you'd like * to extract the Points from. * @param excludeWrapCoord whether or not to include the final * coordinate of LinearRings that wraps the ring * in its iteration. Used if a {@link Feature} in the * {@link FeatureCollection} that's passed through * this method, is a {@link Polygon} or {@link MultiPolygon} * geometry. * @return a {@code List} made up of {@link Point}s. * @since 4.8.0 */ @NonNull private static List<Point> addCoordAll(@NonNull List<Point> pointList, @NonNull Feature feature, @NonNull boolean excludeWrapCoord) { return coordAllFromSingleGeometry(pointList, feature.geometry(), excludeWrapCoord); } /** * Get all coordinates from a {@link FeatureCollection} object, returning a * {@code List} of {@link Point} objects. * * @param pointList the {@code List} of {@link Point}s. * @param geometry the {@link Geometry} object to extract the {@link Point}s from * @param excludeWrapCoord whether or not to include the final coordinate of LinearRings that * wraps the ring in its iteration. Used if the {@link Feature} * passed through the method is a {@link Polygon} or {@link MultiPolygon} * geometry. * @return a {@code List} made up of {@link Point}s * @since 4.8.0 */ @NonNull private static List<Point> coordAllFromSingleGeometry(@NonNull List<Point> pointList, @NonNull Geometry geometry, @NonNull boolean excludeWrapCoord) { if (geometry instanceof Point) { pointList.add((Point) geometry); } else if (geometry instanceof MultiPoint) { pointList.addAll(((MultiPoint) geometry).coordinates()); } else if (geometry instanceof LineString) { pointList.addAll(((LineString) geometry).coordinates()); } else if (geometry instanceof MultiLineString) { coordAll(pointList, (MultiLineString) geometry); } else if (geometry instanceof Polygon) { coordAll(pointList, (Polygon) geometry, excludeWrapCoord); } else if (geometry instanceof MultiPolygon) { coordAll(pointList, (MultiPolygon) geometry, excludeWrapCoord); } else if (geometry instanceof GeometryCollection) { // recursive for (Geometry singleGeometry : ((GeometryCollection) geometry).geometries()) { coordAllFromSingleGeometry(pointList, singleGeometry, excludeWrapCoord); } } return pointList; } /** * Unwrap a coordinate {@link Point} from a {@link Feature} with a {@link Point} geometry. * * @param obj any value * @return a coordinate * @see <a href="http://turfjs.org/docs/#getcoord">Turf getCoord documentation</a> * @since 3.2.0 */ public static Point getCoord(Feature obj) { if (obj.geometry() instanceof Point) { return (Point) obj.geometry(); } throw new TurfException("A Feature with a Point geometry is required."); } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfMisc.java
package com.nbmap.turf; import androidx.annotation.FloatRange; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.nbmap.geojson.Feature; import com.nbmap.geojson.LineString; import com.nbmap.geojson.Point; import com.nbmap.turf.models.LineIntersectsResult; import java.util.ArrayList; import java.util.List; /** * Class contains all the miscellaneous methods that Turf can perform. * * @see <a href="http://turfjs.org/docs/">Turf documentation</a> * @since 1.2.0 */ public final class TurfMisc { private static final String INDEX_KEY = "index"; private TurfMisc() { throw new AssertionError("No Instances."); } /** * Takes a line, a start {@link Point}, and a stop point and returns the line in between those * points. * * @param startPt Starting point. * @param stopPt Stopping point. * @param line Line to slice. * @return Sliced line. * @throws TurfException signals that a Turf exception of some sort has occurred. * @see <a href="http://turfjs.org/docs/#lineslice">Turf Line slice documentation</a> * @since 1.2.0 */ @NonNull public static LineString lineSlice(@NonNull Point startPt, @NonNull Point stopPt, @NonNull Feature line) { if (line.geometry() == null) { throw new NullPointerException("Feature.geometry() == null"); } if (!line.geometry().type().equals("LineString")) { throw new TurfException("input must be a LineString Feature or Geometry"); } return lineSlice(startPt, stopPt, (LineString) line.geometry()); } /** * Takes a line, a start {@link Point}, and a stop point and returns the line in between those * points. * * @param startPt used for calculating the lineSlice * @param stopPt used for calculating the lineSlice * @param line geometry that should be sliced * @return a sliced {@link LineString} * @see <a href="http://turfjs.org/docs/#lineslice">Turf Line slice documentation</a> * @since 1.2.0 */ @NonNull public static LineString lineSlice(@NonNull Point startPt, @NonNull Point stopPt, @NonNull LineString line) { List<Point> coords = line.coordinates(); if (coords.size() < 2) { throw new TurfException("Turf lineSlice requires a LineString made up of at least 2 " + "coordinates."); } else if (startPt.equals(stopPt)) { throw new TurfException("Start and stop points in Turf lineSlice cannot equal each other."); } Feature startVertex = nearestPointOnLine(startPt, coords); Feature stopVertex = nearestPointOnLine(stopPt, coords); List<Feature> ends = new ArrayList<>(); if ((int) startVertex.getNumberProperty(INDEX_KEY) <= (int) stopVertex.getNumberProperty(INDEX_KEY)) { ends.add(startVertex); ends.add(stopVertex); } else { ends.add(stopVertex); ends.add(startVertex); } List<Point> points = new ArrayList<>(); points.add((Point) ends.get(0).geometry()); for (int i = (int) ends.get(0).getNumberProperty(INDEX_KEY) + 1; i < (int) ends.get(1).getNumberProperty(INDEX_KEY) + 1; i++) { points.add(coords.get(i)); } points.add((Point) ends.get(1).geometry()); return LineString.fromLngLats(points); } /** * Takes a {@link LineString}, a specified distance along the line to a start {@link Point}, * and a specified distance along the line to a stop point * and returns a subsection of the line in-between those points. * * This can be useful for extracting only the part of a route between two distances. * * @param line input line * @param startDist distance along the line to starting point * @param stopDist distance along the line to ending point * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * can be degrees, radians, miles, or kilometers * @return sliced line * @throws TurfException signals that a Turf exception of some sort has occurred. * @see <a href="http://turfjs.org/docs/#lineslicealong">Turf Line slice documentation</a> * @since 3.1.0 */ @NonNull public static LineString lineSliceAlong(@NonNull Feature line, @FloatRange(from = 0) double startDist, @FloatRange(from = 0) double stopDist, @NonNull @TurfConstants.TurfUnitCriteria String units) { if (line.geometry() == null) { throw new NullPointerException("Feature.geometry() == null"); } if (!line.geometry().type().equals("LineString")) { throw new TurfException("input must be a LineString Feature or Geometry"); } return lineSliceAlong((LineString)line.geometry(), startDist, stopDist, units); } /** * Takes a {@link LineString}, a specified distance along the line to a start {@link Point}, * and a specified distance along the line to a stop point, * returns a subsection of the line in-between those points. * * This can be useful for extracting only the part of a route between two distances. * * @param line input line * @param startDist distance along the line to starting point * @param stopDist distance along the line to ending point * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * can be degrees, radians, miles, or kilometers * @return sliced line * @throws TurfException signals that a Turf exception of some sort has occurred. * @see <a href="http://turfjs.org/docs/#lineslicealong">Turf Line slice documentation</a> * @since 3.1.0 */ @NonNull public static LineString lineSliceAlong(@NonNull LineString line, @FloatRange(from = 0) double startDist, @FloatRange(from = 0) double stopDist, @NonNull @TurfConstants.TurfUnitCriteria String units) { List<Point> coords = line.coordinates(); if (coords.size() < 2) { throw new TurfException("Turf lineSlice requires a LineString Geometry made up of " + "at least 2 coordinates. The LineString passed in only contains " + coords.size() + "."); } else if (startDist == stopDist) { throw new TurfException("Start and stop distance in Turf lineSliceAlong " + "cannot equal each other."); } List<Point> slice = new ArrayList<>(2); double travelled = 0; for (int i = 0; i < coords.size(); i++) { if (startDist >= travelled && i == coords.size() - 1) { break; } else if (travelled > startDist && slice.size() == 0) { double overshot = startDist - travelled; if (overshot == 0) { slice.add(coords.get(i)); return LineString.fromLngLats(slice); } double direction = TurfMeasurement.bearing(coords.get(i), coords.get(i - 1)) - 180; Point interpolated = TurfMeasurement.destination(coords.get(i), overshot, direction, units); slice.add(interpolated); } if (travelled >= stopDist) { double overshot = stopDist - travelled; if (overshot == 0) { slice.add(coords.get(i)); return LineString.fromLngLats(slice); } double direction = TurfMeasurement.bearing(coords.get(i), coords.get(i - 1)) - 180; Point interpolated = TurfMeasurement.destination(coords.get(i), overshot, direction, units); slice.add(interpolated); return LineString.fromLngLats(slice); } if (travelled >= startDist) { slice.add(coords.get(i)); } if (i == coords.size() - 1) { return LineString.fromLngLats(slice); } travelled += TurfMeasurement.distance(coords.get(i), coords.get(i + 1), units); } if (travelled < startDist) { throw new TurfException("Start position is beyond line"); } return LineString.fromLngLats(slice); } /** * Takes a {@link Point} and a {@link LineString} and calculates the closest Point on the * LineString. * * @param pt point to snap from * @param coords line to snap to * @return closest point on the line to point * @since 1.3.0 */ @NonNull public static Feature nearestPointOnLine(@NonNull Point pt, @NonNull List<Point> coords) { return nearestPointOnLine(pt, coords, null); } /** * Takes a {@link Point} and a {@link LineString} and calculates the closest Point on the * LineString. * * @param pt point to snap from * @param coords line to snap to * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * can be degrees, radians, miles, or kilometers * @return closest point on the line to point * @since 4.9.0 */ @NonNull public static Feature nearestPointOnLine(@NonNull Point pt, @NonNull List<Point> coords, @Nullable @TurfConstants.TurfUnitCriteria String units) { if (coords.size() < 2) { throw new TurfException("Turf nearestPointOnLine requires a List of Points " + "made up of at least 2 coordinates."); } if (units == null) { units = TurfConstants.UNIT_KILOMETERS; } Feature closestPt = Feature.fromGeometry( Point.fromLngLat(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); closestPt.addNumberProperty("dist", Double.POSITIVE_INFINITY); for (int i = 0; i < coords.size() - 1; i++) { Feature start = Feature.fromGeometry(coords.get(i)); Feature stop = Feature.fromGeometry(coords.get(i + 1)); //start start.addNumberProperty("dist", TurfMeasurement.distance( pt, (Point) start.geometry(), units)); //stop stop.addNumberProperty("dist", TurfMeasurement.distance( pt, (Point) stop.geometry(), units)); //perpendicular double heightDistance = Math.max( start.properties().get("dist").getAsDouble(), stop.properties().get("dist").getAsDouble() ); double direction = TurfMeasurement.bearing((Point) start.geometry(), (Point) stop.geometry()); Feature perpendicularPt1 = Feature.fromGeometry( TurfMeasurement.destination(pt, heightDistance, direction + 90, units)); Feature perpendicularPt2 = Feature.fromGeometry( TurfMeasurement.destination(pt, heightDistance, direction - 90, units)); LineIntersectsResult intersect = lineIntersects( ((Point) perpendicularPt1.geometry()).longitude(), ((Point) perpendicularPt1.geometry()).latitude(), ((Point) perpendicularPt2.geometry()).longitude(), ((Point) perpendicularPt2.geometry()).latitude(), ((Point) start.geometry()).longitude(), ((Point) start.geometry()).latitude(), ((Point) stop.geometry()).longitude(), ((Point) stop.geometry()).latitude() ); Feature intersectPt = null; if (intersect != null) { intersectPt = Feature.fromGeometry( Point.fromLngLat(intersect.horizontalIntersection(), intersect.verticalIntersection())); intersectPt.addNumberProperty("dist", TurfMeasurement.distance(pt, (Point) intersectPt.geometry(), units)); } if ((double) start.getNumberProperty("dist") < (double) closestPt.getNumberProperty("dist")) { closestPt = start; closestPt.addNumberProperty(INDEX_KEY, i); } if ((double) stop.getNumberProperty("dist") < (double) closestPt.getNumberProperty("dist")) { closestPt = stop; closestPt.addNumberProperty(INDEX_KEY, i); } if (intersectPt != null && (double) intersectPt.getNumberProperty("dist") < (double) closestPt.getNumberProperty("dist")) { closestPt = intersectPt; closestPt.addNumberProperty(INDEX_KEY, i); } } return closestPt; } private static LineIntersectsResult lineIntersects(double line1StartX, double line1StartY, double line1EndX, double line1EndY, double line2StartX, double line2StartY, double line2EndX, double line2EndY) { // If the lines intersect, the result contains the x and y of the intersection // (treating the lines as infinite) and booleans for whether line segment 1 or line // segment 2 contain the point LineIntersectsResult result = LineIntersectsResult.builder() .onLine1(false) .onLine2(false) .build(); double denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY)); if (denominator == 0) { if (result.horizontalIntersection() != null && result.verticalIntersection() != null) { return result; } else { return null; } } double varA = line1StartY - line2StartY; double varB = line1StartX - line2StartX; double numerator1 = ((line2EndX - line2StartX) * varA) - ((line2EndY - line2StartY) * varB); double numerator2 = ((line1EndX - line1StartX) * varA) - ((line1EndY - line1StartY) * varB); varA = numerator1 / denominator; varB = numerator2 / denominator; // if we cast these lines infinitely in both directions, they intersect here: result = result.toBuilder().horizontalIntersection(line1StartX + (varA * (line1EndX - line1StartX))).build(); result = result.toBuilder().verticalIntersection(line1StartY + (varA * (line1EndY - line1StartY))).build(); // if line1 is a segment and line2 is infinite, they intersect if: if (varA > 0 && varA < 1) { result = result.toBuilder().onLine1(true).build(); } // if line2 is a segment and line1 is infinite, they intersect if: if (varB > 0 && varB < 1) { result = result.toBuilder().onLine2(true).build(); } // if line1 and line2 are segments, they intersect if both of the above are true if (result.onLine1() && result.onLine2()) { return result; } else { return null; } } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/TurfTransformation.java
package com.nbmap.turf; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import com.nbmap.geojson.Polygon; import com.nbmap.geojson.Point; import java.util.ArrayList; import java.util.List; /** * Methods in this class consume one GeoJSON object and output a new object with the defined * parameters provided. * * @since 3.0.0 */ public final class TurfTransformation { private static final int DEFAULT_STEPS = 64; private TurfTransformation() { // Empty constructor to prevent class initialization } /** * Takes a {@link Point} and calculates the circle polygon given a radius in degrees, radians, * miles, or kilometers; and steps for precision. This uses the {@link #DEFAULT_STEPS} and * {@link TurfConstants#UNIT_DEFAULT} values. * * @param center a {@link Point} which the circle will center around * @param radius the radius of the circle * @return a {@link Polygon} which represents the newly created circle * @since 3.0.0 */ public static Polygon circle(@NonNull Point center, double radius) { return circle(center, radius, 64, TurfConstants.UNIT_DEFAULT); } /** * Takes a {@link Point} and calculates the circle polygon given a radius in the * provided {@link TurfConstants.TurfUnitCriteria}; and steps for precision. This * method uses the {@link #DEFAULT_STEPS}. * * @param center a {@link Point} which the circle will center around * @param radius the radius of the circle * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return a {@link Polygon} which represents the newly created circle * @since 3.0.0 */ public static Polygon circle(@NonNull Point center, double radius, @TurfConstants.TurfUnitCriteria String units) { return circle(center, radius, DEFAULT_STEPS, units); } /** * Takes a {@link Point} and calculates the circle polygon given a radius in the * provided {@link TurfConstants.TurfUnitCriteria}; and steps for precision. * * @param center a {@link Point} which the circle will center around * @param radius the radius of the circle * @param steps number of steps which make up the circle parameter * @param units one of the units found inside {@link TurfConstants.TurfUnitCriteria} * @return a {@link Polygon} which represents the newly created circle * @since 3.0.0 */ public static Polygon circle(@NonNull Point center, double radius, @IntRange(from = 1) int steps, @TurfConstants.TurfUnitCriteria String units) { List<Point> coordinates = new ArrayList<>(); for (int i = 0; i < steps; i++) { coordinates.add(TurfMeasurement.destination(center, radius, i * 360d / steps, units)); } if (coordinates.size() > 0) { coordinates.add(coordinates.get(0)); } List<List<Point>> coordinate = new ArrayList<>(); coordinate.add(coordinates); return Polygon.fromLngLats(coordinate); } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/package-info.java
/** * Contains the Nbmap Java Services Turf methods. * * @since 1.2.0 */ package com.nbmap.turf;
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/models/LineIntersectsResult.java
package com.nbmap.turf.models; import androidx.annotation.Nullable; /** * if the lines intersect, the result contains the x and y of the intersection (treating the lines * as infinite) and booleans for whether line segment 1 or line segment 2 contain the point. * * @see <a href="http://jsfiddle.net/justin_c_rounds/Gd2S2/light/">Good example of how this class works written in JavaScript</a> * @since 1.2.0 */ public class LineIntersectsResult { private final Double horizontalIntersection; private final Double verticalIntersection; private final boolean onLine1; private final boolean onLine2; private LineIntersectsResult( @Nullable Double horizontalIntersection, @Nullable Double verticalIntersection, boolean onLine1, boolean onLine2) { this.horizontalIntersection = horizontalIntersection; this.verticalIntersection = verticalIntersection; this.onLine1 = onLine1; this.onLine2 = onLine2; } /** * Builds a new instance of a lineIntersection. This class is mainly used internally for other * turf objects to recall memory when performing calculations. * * @return {@link LineIntersectsResult.Builder} for creating a new instance * @since 3.0.0 */ public static Builder builder() { return new Builder(); } /** * If the lines intersect, use this method to get the intersecting point {@code X} value. * * @return the {@code X} value where the lines intersect * @since 1.2.0 */ @Nullable public Double horizontalIntersection() { return horizontalIntersection; } /** * If the lines intersect, use this method to get the intersecting point {@code Y} value. * * @return the {@code Y} value where the lines intersect * @since 1.2.0 */ @Nullable public Double verticalIntersection() { return verticalIntersection; } /** * Determine if the intersecting point lands on line 1 or not. * * @return true if the intersecting point is located on line 1, otherwise false * @since 1.2.0 */ public boolean onLine1() { return onLine1; } /** * Determine if the intersecting point lands on line 2 or not. * * @return true if the intersecting point is located on line 2, otherwise false * @since 1.2.0 */ public boolean onLine2() { return onLine2; } @Override public String toString() { return "LineIntersectsResult{" + "horizontalIntersection=" + horizontalIntersection + ", " + "verticalIntersection=" + verticalIntersection + ", " + "onLine1=" + onLine1 + ", " + "onLine2=" + onLine2 + "}"; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof LineIntersectsResult) { LineIntersectsResult that = (LineIntersectsResult) obj; return ((this.horizontalIntersection == null) ? (that.horizontalIntersection() == null) : this.horizontalIntersection.equals(that.horizontalIntersection())) && ((this.verticalIntersection == null) ? (that.verticalIntersection() == null) : this.verticalIntersection.equals(that.verticalIntersection())) && (this.onLine1 == that.onLine1()) && (this.onLine2 == that.onLine2()); } return false; } @Override public int hashCode() { int hashCode = 1; hashCode *= 1000003; hashCode ^= (horizontalIntersection == null) ? 0 : horizontalIntersection.hashCode(); hashCode *= 1000003; hashCode ^= (verticalIntersection == null) ? 0 : verticalIntersection.hashCode(); hashCode *= 1000003; hashCode ^= onLine1 ? 1231 : 1237; hashCode *= 1000003; hashCode ^= onLine2 ? 1231 : 1237; return hashCode; } /** * Convert current instance values into another Builder to quickly change one or more values. * * @return a new instance of {@link LineIntersectsResult} using the newly defined values * @since 3.0.0 */ public Builder toBuilder() { return new Builder(this); } /** * Build a new {@link LineIntersectsResult} instance and define its features by passing in * information through the offered methods. * * @since 3.0.0 */ public static class Builder { private Double horizontalIntersection; private Double verticalIntersection; private Boolean onLine1 = false; private Boolean onLine2 = false; Builder() { } private Builder(LineIntersectsResult source) { this.horizontalIntersection = source.horizontalIntersection(); this.verticalIntersection = source.verticalIntersection(); this.onLine1 = source.onLine1(); this.onLine2 = source.onLine2(); } /** * If the lines intersect, use this method to get the intersecting point {@code X} value. * * @param horizontalIntersection the x coordinates intersection point * @return the {@code X} value where the lines intersect * @since 3.0.0 */ public Builder horizontalIntersection(@Nullable Double horizontalIntersection) { this.horizontalIntersection = horizontalIntersection; return this; } /** * If the lines intersect, use this method to get the intersecting point {@code Y} value. * * @param verticalIntersection the y coordinates intersection point * @return the {@code Y} value where the lines intersect * @since 3.0.0 */ public Builder verticalIntersection(@Nullable Double verticalIntersection) { this.verticalIntersection = verticalIntersection; return this; } /** * Determine if the intersecting point lands on line 1 or not. * * @param onLine1 true if the points land on line one, else false * @return true if the intersecting point is located on line 1, otherwise false * @since 3.0.0 */ public Builder onLine1(boolean onLine1) { this.onLine1 = onLine1; return this; } /** * Determine if the intersecting point lands on line 2 or not. * * @param onLine2 true if the points land on line two, else false * @return true if the intersecting point is located on line 2, otherwise false * @since 3.0.0 */ public Builder onLine2(boolean onLine2) { this.onLine2 = onLine2; return this; } /** * Builds a new instance of a {@link LineIntersectsResult} class. * * @return a new instance of {@link LineIntersectsResult} * @since 3.0.0 */ public LineIntersectsResult build() { String missing = ""; if (this.onLine1 == null) { missing += " onLine1"; } if (this.onLine2 == null) { missing += " onLine2"; } if (!missing.isEmpty()) { throw new IllegalStateException("Missing required properties:" + missing); } return new LineIntersectsResult( this.horizontalIntersection, this.verticalIntersection, this.onLine1, this.onLine2); } } }
0
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf
java-sources/ai/nextbillion/nbmap-sdk-turf/0.1.2/com/nbmap/turf/models/package-info.java
/** * Contains the Nbmap Java Services classes. */ package com.nbmap.turf.models;
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/examples/FileScannerExample.java
package ai.nightfall.examples; import ai.nightfall.scan.NightfallClient; import ai.nightfall.scan.model.Confidence; import ai.nightfall.scan.model.DetectionRule; import ai.nightfall.scan.model.Detector; import ai.nightfall.scan.model.LogicalOp; import ai.nightfall.scan.model.ScanFileRequest; import ai.nightfall.scan.model.ScanFileResponse; import ai.nightfall.scan.model.ScanPolicy; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * FileScannerExample provides a simple example of a program that sends text to Nightfall's file detection API. * NIGHTFALL_API_KEY must be set as an environment variable, and webhookURL must be a running webhook endpoint * that is ready to receive a response. * * <p>For an example webhook server, see https://docs.nightfall.ai/docs/creating-a-webhook-server */ public class FileScannerExample { public static final String usage = "Usage: scanner <webhookURL> <filename>"; /** * Submit the provided files for scanning and print the result. */ public static void main(String[] args) { if (args.length != 2) { throw new RuntimeException(usage); } // File scans are conducted asynchronously, so provide a webhook route to an HTTPS server to send results to. String webhookResponseListenerURL = args[0]; String file = args[1]; try (NightfallClient client = NightfallClient.Builder.defaultClient()) { // Define some detectors to use to scan your data Detector creditCard = new Detector("CREDIT_CARD_NUMBER"); creditCard.setMinConfidence(Confidence.LIKELY); creditCard.setMinNumFindings(1); Detector ssn = new Detector("US_SOCIAL_SECURITY_NUMBER"); ssn.setMinConfidence(Confidence.POSSIBLE); ssn.setMinNumFindings(1); // A rule contains a set of detectors to scan with DetectionRule rule = new DetectionRule(Arrays.asList(creditCard, ssn), LogicalOp.ANY); ScanPolicy policy = ScanPolicy.fromDetectionRules(Arrays.asList(rule), webhookResponseListenerURL); ScanFileRequest req = new ScanFileRequest(policy, "my request metadata"); // Upload the data to the API, then trigger the async scan File file1 = new File(file); try (InputStream stream = new FileInputStream(file1)) { ScanFileResponse response = client.scanFile(req, stream, file1.length()); System.out.println("started scan: " + response.toString()); } catch (IOException e) { e.printStackTrace(); } } } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/examples/TextScannerExample.java
package ai.nightfall.examples; import ai.nightfall.scan.NightfallClient; import ai.nightfall.scan.model.Confidence; import ai.nightfall.scan.model.DetectionRule; import ai.nightfall.scan.model.Detector; import ai.nightfall.scan.model.LogicalOp; import ai.nightfall.scan.model.ScanTextConfig; import ai.nightfall.scan.model.ScanTextRequest; import ai.nightfall.scan.model.ScanTextResponse; import java.util.Arrays; import java.util.List; /** * TextScannerExample provides a simple example of a program that sends text to Nightfall's detection API. * NIGHTFALL_API_KEY must be set as an environment variable. */ public class TextScannerExample { public static final String usage = "Usage: scanner <string> ..."; /** * Submit the provided args for scanning and print the result. */ public static void main(String[] args) { if (args.length == 0) { throw new RuntimeException(usage); } try (NightfallClient client = NightfallClient.Builder.defaultClient()) { Detector creditCard = new Detector("CREDIT_CARD_NUMBER"); creditCard.setMinConfidence(Confidence.LIKELY); creditCard.setMinNumFindings(1); Detector ssn = new Detector("US_SOCIAL_SECURITY_NUMBER"); ssn.setMinConfidence(Confidence.POSSIBLE); ssn.setMinNumFindings(1); // A rule contains a set of detectors to scan with DetectionRule rule = new DetectionRule(Arrays.asList(creditCard, ssn), LogicalOp.ANY); List<String> payload = Arrays.asList(args).subList(1, args.length); // Define some detectors to use to scan your data ScanTextConfig config = ScanTextConfig.fromDetectionRules(Arrays.asList(rule), 20); ScanTextRequest req = new ScanTextRequest(payload, config); ScanTextResponse response = client.scanText(req); System.out.println("findings: " + response.getFindings()); } } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/NightfallClient.java
package ai.nightfall.scan; import ai.nightfall.scan.model.BaseNightfallException; import ai.nightfall.scan.model.CompleteFileUploadRequest; import ai.nightfall.scan.model.FileUpload; import ai.nightfall.scan.model.InitializeFileUploadRequest; import ai.nightfall.scan.model.NightfallAPIException; import ai.nightfall.scan.model.NightfallClientException; import ai.nightfall.scan.model.NightfallErrorResponse; import ai.nightfall.scan.model.NightfallRequestTimeoutException; import ai.nightfall.scan.model.ScanFileRequest; import ai.nightfall.scan.model.ScanFileResponse; import ai.nightfall.scan.model.ScanTextRequest; import ai.nightfall.scan.model.ScanTextResponse; import ai.nightfall.scan.model.UploadFileChunkRequest; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.Call; import okhttp3.ConnectionPool; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * Provides a client for accessing the Nightfall Developer Platform. */ public class NightfallClient implements Closeable { private static final ObjectMapper objectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); private static final long wakeupDurationMillis = Duration.ofSeconds(15).toMillis(); private static final int DEFAULT_RETRY_COUNT = 5; private static final String API_HOST = "https://api.nightfall.ai"; private final String implVersion = loadImplVersion(); private final String apiHost; private final String apiKey; private final int fileUploadConcurrency; private final int retryCount; private final ExecutorService executor; private final OkHttpClient httpClient; // package-visible for testing NightfallClient(String apiHost, String apiKey, int fileUploadConcurrency, OkHttpClient httpClient) { this.apiHost = apiHost; this.apiKey = apiKey; this.fileUploadConcurrency = fileUploadConcurrency; this.retryCount = DEFAULT_RETRY_COUNT; this.executor = Executors.newFixedThreadPool(this.fileUploadConcurrency); this.httpClient = httpClient; } private String loadImplVersion() { Package pkg = this.getClass().getPackage(); if (pkg == null) { return ""; } return pkg.getImplementationVersion(); } /** * Closes this client and releases underlying system resources. */ @Override public void close() { this.executor.shutdown(); this.httpClient.dispatcher().executorService().shutdown(); } /** * Scans the provided plaintext against the provided detectors, and returns all findings. The response object will * contain a list of lists representing the findings. Each index <code>i</code> in the findings array will * correspond one-to-one with the input request payload list, so all findings stored in a given sub-list refer to * matches that occurred in the <code>i</code>th index of the request payload. * * @param request the data to scan, along with the configuration describing how to scan the data. The * request payload may not exceed 500KB. * @return an object containing the findings from each item in the request payload * @throws NightfallAPIException thrown if a non-2xx status code is returned by the API. * @throws NightfallClientException thrown if a I/O error occurs while processing the request * @throws IllegalArgumentException thrown if <code>request</code> is null * @throws NightfallRequestTimeoutException thrown if the request is aborted because the timeout is exceeded */ public ScanTextResponse scanText(ScanTextRequest request) { if (request == null) { throw new IllegalArgumentException("request must be non-null"); } byte[] jsonBody; try { jsonBody = objectMapper.writeValueAsBytes(request); } catch (JsonProcessingException e) { throw new NightfallClientException("processing scan request: " + e.getMessage()); } MediaType json = MediaType.parse("application/json"); return this.issueRequest("/v3/scan", "POST", json, jsonBody, null, ScanTextResponse.class); } /** * A convenience method that abstracts the details of the multi-step file upload and scan process. In other words, * calling this method for a given file is equivalent to (1) manually initializing a file upload session, * (2) uploading all chunks of the file, (3) completing the upload, and (4) triggering a scan of the file. * * <p>The maximum allowed <code>contentSizeBytes</code> is dependent on the terms of your current * Nightfall usage plan agreement; check the Nightfall dashboard for more details. * * <p>This method consumes the provided <code>InputStream</code>, but it *does not* close it; closing remains * the caller's responsibility. * * @param request contains configuration describing which detectors to use to scan the file, as well as a webhook * URL for delivering the results of the scan. * @param content a stream of the bytes representing the file to upload * @param contentSizeBytes the size of the input stream * @return an acknowledgment that the asynchronous scan has been initiated. * @throws NightfallAPIException thrown if a non-2xx status code is returned by the API. * @throws NightfallClientException thrown if a I/O error occurs while processing the request * @throws NightfallRequestTimeoutException thrown if the request is aborted because read/write timeout is exceeded */ public ScanFileResponse scanFile(ScanFileRequest request, InputStream content, long contentSizeBytes) { return scanFile(request, content, contentSizeBytes, null); } /** * A convenience method that abstracts the details of the multi-step file upload and scan process. In other words, * calling this method for a given file is equivalent to (1) manually initializing a file upload session, * (2) uploading all chunks of the file, (3) completing the upload, and (4) triggering a scan of the file. * * <p>The maximum allowed <code>contentSizeBytes</code> is dependent on the terms of your current * Nightfall usage plan agreement; check the Nightfall dashboard for more details. * * <p>This method consumes the provided <code>InputStream</code>, but it *does not* close it; closing remains * the caller's responsibility. * * @param request contains configuration describing which detectors to use to scan the file, as well as a webhook * URL for delivering the results of the scan. * @param content a stream of the bytes representing the file to upload * @param contentSizeBytes the size of the input stream * @param timeout the allowed duration for the request; if the execution time exceeds this duration, the request * will be aborted. * @return an acknowledgment that the asynchronous scan has been initiated. * @throws NightfallAPIException thrown if a non-2xx status code is returned by the API. * @throws NightfallClientException thrown if a I/O error occurs while processing the request * @throws NightfallRequestTimeoutException thrown if execution time exceeds the provided <code>timeout</code>, * or if an HTTP request is terminated by the client for exceeding read/write timeouts. */ public ScanFileResponse scanFile( ScanFileRequest request, InputStream content, long contentSizeBytes, Duration timeout) { if (request == null) { throw new IllegalArgumentException("request must be non-null"); } else if (content == null) { throw new IllegalArgumentException("content must be non-null"); } Instant deadline = null; if (timeout != null) { if (timeout.isNegative()) { throw new IllegalArgumentException("timeout must be positive"); } deadline = Instant.now().plus(timeout); } InitializeFileUploadRequest initRequest = new InitializeFileUploadRequest(contentSizeBytes); FileUpload upload = this.initializeFileUpload(initRequest); AtomicReference<BaseNightfallException> uploadException = new AtomicReference<>(); boolean uploadSuccess = doChunkedUpload(upload, content, deadline, uploadException); if (!uploadSuccess) { BaseNightfallException except = uploadException.get(); if (except != null) { throw except; } throw new NightfallClientException("internal error: failed to upload all chunks of file"); } CompleteFileUploadRequest completeReq = new CompleteFileUploadRequest(upload.getFileID()); upload = this.completeFileUpload(completeReq); return this.scanUploadedFile(request, upload.getFileID()); } private boolean doChunkedUpload( FileUpload upload, InputStream content, Instant deadline, AtomicReference<BaseNightfallException> uploadException) { // Use a semaphore to avoid loading the entire stream into memory int numPermits = this.fileUploadConcurrency; Semaphore semaphore = new Semaphore(numPermits); AtomicBoolean allChunksSucceed = new AtomicBoolean(true); for (int offset = 0; offset < upload.getFileSizeBytes(); offset += upload.getChunkSize()) { semaphore.acquireUninterruptibly(); checkFileUploadDeadline(deadline); if (!allChunksSucceed.get()) { return false; } UploadFileChunkRequest chunkReq = new UploadFileChunkRequest(upload.getFileID(), offset); byte[] data = new byte[(int) upload.getChunkSize()]; try { int bytesRead = content.read(data); boolean notLastChunk = offset + upload.getChunkSize() < upload.getFileSizeBytes(); if (bytesRead < data.length && notLastChunk) { semaphore.release(); throw new NightfallClientException("failed to read data from input stream"); } else if (bytesRead < data.length) { data = Arrays.copyOfRange(data, 0, bytesRead); } } catch (IOException e) { semaphore.release(); throw new NightfallClientException("reading content to upload: " + e.getMessage()); } chunkReq.setContent(data); this.executor.execute(() -> { try { this.uploadFileChunk(chunkReq); } catch (BaseNightfallException e) { allChunksSucceed.set(false); uploadException.set(e); } catch (Throwable t) { allChunksSucceed.set(false); } finally { semaphore.release(); } }); } while (true) { try { // Attempt to acquire all permits; this is only possible when all chunks have been uploaded. // Allow spurious wake-ups in case the caller puts a deadline on the operation. boolean success = semaphore.tryAcquire(numPermits, wakeupDurationMillis, TimeUnit.MILLISECONDS); if (success) { return allChunksSucceed.get(); } checkFileUploadDeadline(deadline); } catch (InterruptedException e) { throw new NightfallClientException("interrupted while waiting for upload to complete"); } } } private void checkFileUploadDeadline(Instant deadline) { if (deadline != null && Instant.now().isAfter(deadline)) { throw new NightfallRequestTimeoutException("timed out while uploading file"); } } /** * Creates a file upload session. If this operation returns successfully, the ID returned as part of the * response object shall be used to refer to the file in all subsequent upload and scanning operations. * * @param request contains metadata describing the requested file upload, such as the file size in bytes. * @return an object representing the file upload. * @throws NightfallAPIException thrown if a non-2xx status code is returned by the API. * @throws NightfallClientException thrown if a I/O error occurs while processing the request * @throws NightfallRequestTimeoutException thrown if the request is aborted because read/write timeout is exceeded */ private FileUpload initializeFileUpload(InitializeFileUploadRequest request) { byte[] jsonBody; try { jsonBody = objectMapper.writeValueAsBytes(request); } catch (JsonProcessingException e) { throw new NightfallClientException("processing init-upload request: " + e.getMessage()); } MediaType json = MediaType.parse("application/json"); return this.issueRequest("/v3/upload", "POST", json, jsonBody, null, FileUpload.class); } /** * Uploads the bytes stored at the provided offset of a file. The byte offset provided should be an exact * multiple of the <code>chunkSize</code> returned by the response when the upload session was created. The * number of bytes provided in the request should exactly match <code>chunkSize</code>, except if this chunk is * the last chunk of the file; then it may be less. * * @param request the data to upload, as well as metadata such as the offset at which to upload. * @return true if the chunk was uploaded * @throws NightfallAPIException thrown if a non-2xx status code is returned by the API. * @throws NightfallClientException thrown if a I/O error occurs while processing the request * @throws NightfallRequestTimeoutException thrown if the request is aborted because read/write timeout is exceeded */ private boolean uploadFileChunk(UploadFileChunkRequest request) { Headers headers = Headers.of("X-Upload-Offset", Long.toString(request.getFileOffset())); String path = "/v3/upload/" + request.getFileUploadID().toString(); MediaType octetStream = MediaType.parse("application/octet-stream"); this.issueRequest(path, "PATCH", octetStream, request.getContent(), headers, Void.class); return true; } /** * Marks the file upload as complete, and coalesces all chunks into a single logical file. This method also * validates the uploaded bytes to make sure that they represent a file type for which Nightfall supports scans. * * @param request contains metadata identifying the file upload, namely the upload ID. * @return an object representing the file upload. * @throws NightfallAPIException thrown if a non-2xx status code is returned by the API. * @throws NightfallClientException thrown if a I/O error occurs while processing the request * @throws NightfallRequestTimeoutException thrown if the request is aborted because read/write timeout is exceeded */ private FileUpload completeFileUpload(CompleteFileUploadRequest request) { String path = "/v3/upload/" + request.getFileUploadID().toString() + "/finish"; MediaType json = MediaType.parse("application/json"); return this.issueRequest(path, "POST", json, new byte[0], null, FileUpload.class); } /** * Triggers a scan of the file identified by the provided <code>fileID</code>. As the underlying file might be * arbitrarily large, this scan will be conducted asynchronously. Results from the scan will be delivered to the * webhook URL provided in the <code>request</code> payload. * * @param request contains metadata identifying which file to scan, as well as the configuration that * describes which detectors to use when scanning. * @return an acknowledgment that the asynchronous scan has been initiated. * @throws NightfallAPIException thrown if a non-2xx status code is returned by the API. * @throws NightfallClientException thrown if a I/O error occurs while processing the request * @throws NightfallRequestTimeoutException thrown if the request is aborted because read/write timeout is exceeded */ private ScanFileResponse scanUploadedFile(ScanFileRequest request, UUID fileID) { String path = "/v3/upload/" + fileID.toString() + "/scan"; byte[] jsonBody; try { jsonBody = objectMapper.writeValueAsBytes(request); } catch (JsonProcessingException e) { throw new NightfallClientException("processing scan file request: " + e.getMessage()); } MediaType json = MediaType.parse("application/json"); return this.issueRequest(path, "POST", json, jsonBody, null, ScanFileResponse.class); } /** * Issues an HTTP request to the provided resource. If the request is successful, the response body will be * deserialized into an object based on the provided <code>responseClass</code>. If the response indicates a * rate limiting error, the request will be retried after a short sleep. * * @param path the HTTP resource path * @param method the HTTP verb * @param body the HTTP request body * @param headers HTTP headers * @param responseClass the class to deserialize results into * @return an instance of the <code>responseClass</code> * @throws NightfallClientException thrown if an unexpected error occurs while processing the request * @throws NightfallAPIException thrown if the API returns a 4xx or 5xx error code * @throws NightfallRequestTimeoutException thrown if the request is aborted because read/write timeout is exceeded */ private <E> E issueRequest( String path, String method, MediaType mediaType, byte[] body, Headers headers, Class<E> responseClass) { String url = this.apiHost + path; Request.Builder builder = new Request.Builder().url(url); if (headers != null) { builder.headers(headers); } if (this.implVersion != null && !this.implVersion.equals("")) { builder.addHeader("User-Agent", "nightfall-java-sdk/" + this.implVersion); } builder.addHeader("Authorization", "Bearer " + this.apiKey); RequestBody reqBody = null; if (body != null && body.length > 0) { reqBody = RequestBody.create(body, mediaType); } else if (!method.equals("GET") && !method.equals("HEAD")) { reqBody = RequestBody.create(new byte[0]); } builder.method(method, reqBody); Request request = builder.build(); Call call = this.httpClient.newCall(request); NightfallErrorResponse lastError = null; int errorCode = 0; for (int attempt = 0; attempt < this.retryCount; attempt++) { try (Response response = call.execute()) { if (!response.isSuccessful()) { try { lastError = objectMapper.readValue(response.body().bytes(), NightfallErrorResponse.class); } catch (Throwable t) { // best effort to get more info, swallow failure } if (response.code() == 429 && attempt < this.retryCount - 1) { Thread.sleep(1000); call = call.clone(); // cannot re-use the same call object continue; } // cannot directly throw exception here because of Throwable catch branch; need to break errorCode = response.code(); break; } if (Void.class.equals(responseClass)) { return null; } return objectMapper.readValue(response.body().bytes(), responseClass); } catch (IOException e) { // If OkHTTP times out, allow retries if (e.getMessage().equalsIgnoreCase("timeout") || e.getMessage().equalsIgnoreCase("read timed out")) { if (attempt >= this.retryCount - 1) { throw new NightfallRequestTimeoutException("request timed out"); } try { Thread.sleep(1000); } catch (InterruptedException ee) { // swallow } call = call.clone(); // cannot re-use the same call object continue; } throw new NightfallClientException("issuing HTTP request: " + e.getMessage()); } catch (Throwable t) { throw new NightfallClientException("failure executing HTTP request: " + t.getMessage()); } } if (errorCode > 0) { throw new NightfallAPIException("unsuccessful response", lastError, errorCode); } String message = "exceeded max retry count on request: " + path; throw new NightfallAPIException(message, lastError, 429); } /** * A builder class that configures, validates, then creates instances of a Nightfall Client. */ public static class Builder { private String apiKey; private int fileUploadConcurrency = 1; private Duration connectionTimeout = Duration.ofSeconds(10); private Duration readTimeout = Duration.ofSeconds(30); private Duration writeTimeout = Duration.ofSeconds(60); private int maxIdleConnections = 100; private Duration keepAliveDuration = Duration.ofSeconds(30); private List<Interceptor> interceptors = new ArrayList<Interceptor>(); /** * Builds and returns the client with all default values. The API key is loaded from the environment variable * <code>NIGHTFALL_API_KEY</code>. The underlying client manages an HTTP connection pool, so instantiating * more than one Nightfall client is not necessary. * * @return a Nightfall client * @throws IllegalArgumentException if no value is set for the API key */ public static NightfallClient defaultClient() { ConnectionPool cxnPool = new ConnectionPool(100, 30, TimeUnit.SECONDS); OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(Duration.ofSeconds(10)) .readTimeout(Duration.ofSeconds(30)) .writeTimeout(Duration.ofSeconds(60)) .connectionPool(cxnPool) .build(); return new NightfallClient(API_HOST, readAPIKeyFromEnvironment(), 1, httpClient); } /** * Sets the API key for the Nightfall Client. * * @param apiKey a valid Nightfall API key * @return the builder */ public Builder withAPIKey(String apiKey) { this.apiKey = apiKey; return this; } /** * Sets the concurrency for file upload operations. This field represents the number of HTTP requests that * may execute in parallel when uploading file bytes. Be cognizant of your HTTP connection pool settings * when deciding on a value in order to optimize your upload bandwidth. * Valid values are in the range [1, 100], inclusive. Defaults to 1 if unset. * * @param concurrency an integer in the range [1, 100] * @return the builder * @throws IllegalArgumentException if the argument falls outside the allowed range */ public Builder withFileUploadConcurrency(int concurrency) { if (concurrency <= 0 || concurrency > 100) { throw new IllegalArgumentException("fileUploadConcurrency must be in range [1,100]"); } this.fileUploadConcurrency = concurrency; return this; } /** * Sets the connection timeout for the underlying HTTP client. If unset, defaults to 10 seconds. If set * to 0, connections will not time out. * * @param connectionTimeout a non-negative duration less than or equal to 60 seconds * @return the builder * @throws IllegalArgumentException if the argument falls outside the allowed range */ public Builder withConnectionTimeout(Duration connectionTimeout) { if (connectionTimeout == null || connectionTimeout.isNegative() || connectionTimeout.getSeconds() > 60) { throw new IllegalArgumentException("connectionTimeout must be a non-negative duration <= 60 seconds"); } this.connectionTimeout = connectionTimeout; return this; } /** * Sets the read timeout for the underlying HTTP client. If unset, defaults to 30 seconds. If set * to 0, reads will not time out. * * @param readTimeout a non-negative duration less than or equal to 120 seconds * @return the builder * @throws IllegalArgumentException if the argument falls outside the allowed range */ public Builder withReadTimeout(Duration readTimeout) { if (readTimeout == null || readTimeout.isNegative() || readTimeout.getSeconds() > 120) { throw new IllegalArgumentException("readTimeout must be a non-negative duration <= 120 seconds"); } this.readTimeout = readTimeout; return this; } /** * Sets the write timeout for the underlying HTTP client. If unset, defaults to 60 seconds. If set * to 0, writes will not time out. * * @param writeTimeout a non-negative duration less than or equal to 120 seconds * @return the builder * @throws IllegalArgumentException if the argument falls outside the allowed range */ public Builder withWriteTimeout(Duration writeTimeout) { if (writeTimeout == null || writeTimeout.isNegative() || writeTimeout.getSeconds() > 120) { throw new IllegalArgumentException("writeTimeout must be a non-negative duration <= 120 seconds"); } this.writeTimeout = writeTimeout; return this; } /** * Sets the maximum number of idle connections in the underlying HTTP client. Be sure this value cooperates with * the configuration for <code>fileUploadConcurrency</code>. If unset, defaults to 100. * * @param maxIdleConnections an integer in the range [1, 500] * @return the builder * @throws IllegalArgumentException if the argument falls outside the allowed range */ public Builder withMaxIdleConnections(int maxIdleConnections) { if (maxIdleConnections < 1 || maxIdleConnections > 500) { throw new IllegalArgumentException("maxIdleConnections must be in the range [1, 500]"); } this.maxIdleConnections = maxIdleConnections; return this; } /** * Sets the keep-alive duration for a connection in the underlying HTTP connection pool. If unset, * defaults to 30 seconds. * * @param keepAliveDuration a positive duration less than or equal to 120 seconds * @return the builder * @throws IllegalArgumentException if the argument falls outside the allowed range */ public Builder withKeepAliveDuration(Duration keepAliveDuration) { if (keepAliveDuration == null || keepAliveDuration.isNegative() || keepAliveDuration.isZero() || keepAliveDuration.getSeconds() > 120) { throw new IllegalArgumentException("keepAliveDuration must be a positive duration <= 120 seconds"); } this.keepAliveDuration = keepAliveDuration; return this; } /** * Adds an interceptor to the HTTP client used to preform requests. * * @param interceptor a OkHttpClient interceptor * @return the builder */ public Builder withInterceptor(Interceptor interceptor) { this.interceptors.add(interceptor); return this; } /** * Builds the client using the configured values, falling back on defaults if any values * were not explicitly set. * * @return a Nightfall client * @throws IllegalArgumentException if the API key was not set */ public NightfallClient build() { if (this.apiKey == null || this.apiKey.equals("")) { this.apiKey = readAPIKeyFromEnvironment(); } ConnectionPool cxnPool = new ConnectionPool(this.maxIdleConnections, this.keepAliveDuration.toMillis(), TimeUnit.MILLISECONDS); OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder() .connectTimeout(this.connectionTimeout) .readTimeout(this.readTimeout) .writeTimeout(this.writeTimeout) .connectionPool(cxnPool); for (Interceptor interceptor : this.interceptors) { httpClientBuilder = httpClientBuilder.addInterceptor(interceptor); } OkHttpClient httpClient = httpClientBuilder.build(); return new NightfallClient(API_HOST, this.apiKey, this.fileUploadConcurrency, httpClient); } private static String readAPIKeyFromEnvironment() { String apiKey = System.getenv("NIGHTFALL_API_KEY"); if (apiKey == null || apiKey.equals("")) { throw new IllegalArgumentException("Missing value for NIGHTFALL_API_KEY environment variable"); } return apiKey; } } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/WebhookSignatureValidator.java
package ai.nightfall.scan; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.time.temporal.TemporalAmount; /** * A class that implements Nightfall webhook signature validation. This class can be used in a request middleware * to validate the authenticity of a request before processing it. Validation is implemented with an SHA-256 * HMAC signature. */ public class WebhookSignatureValidator { // This constant is documented in https://docs.oracle.com/javase/8/docs/api/javax/crypto/Mac.html private static final String SHA256 = "HmacSHA256"; private static final TemporalAmount DEFAULT_THRESHOLD = Duration.ofMinutes(5); private final TemporalAmount threshold; /** * Instantiates the validator with the default threshold. */ public WebhookSignatureValidator() { this.threshold = DEFAULT_THRESHOLD; } /** * Instantiates the validator with the provided threshold. * * @param threshold the time threshold within which webhook requests should be considered valid. */ public WebhookSignatureValidator(TemporalAmount threshold) { this.threshold = threshold; } /** * Validates that the provided request payload is an authentic request that originated from Nightfall. If this * method returns false, request handlers shall not process the provided body any further. * * @param requestBody the entire, raw request payload, encoded in UTF-8. * @param signingSecret the signing secret used as the key for HMAC. * @param requestSignature the signature provided by Nightfall to compare against the locally-computed value. * @param requestTime the Unix timestamp of when this request was sent, i.e. the number of seconds * since the Unix epoch. * @return true if the signature is valid and the request occurred within the allowed time threshold, * otherwise false. * @throws NumberFormatException if <code>requestTime</code> is not parsable as an integer */ public boolean validate(String requestBody, byte[] signingSecret, String requestSignature, String requestTime) { if (requestBody == null || signingSecret == null || requestSignature == null || requestTime == null) { return false; } Instant now = Instant.now(); Instant reqTime = Instant.ofEpochSecond(Long.parseLong(requestTime)); if (now.minus(this.threshold).isAfter(reqTime) || reqTime.isAfter(now)) { return false; } Mac hmac; try { hmac = Mac.getInstance(SHA256); Key key = new SecretKeySpec(signingSecret, SHA256); hmac.init(key); } catch (NoSuchAlgorithmException e) { // should not happen, all JREs are required to implement HmacSHA256 return false; } catch (InvalidKeyException e) { // e.g. invalid signing secret return false; } String hashPayload = requestTime + ":" + requestBody; byte[] hashed = hmac.doFinal(hashPayload.getBytes(StandardCharsets.UTF_8)); String hexHash = bytesToHex(hashed); return hexHash.equals(requestSignature); } // Java 8-16 does not have a standard Hex converter class... so as long as this SDK supports Java 8 // as a minimum language level, here we are. String bytesToHex(byte[] in) { final StringBuilder builder = new StringBuilder(); for (byte b : in) { builder.append(String.format("%02x", b)); } return builder.toString(); } }
0
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan
java-sources/ai/nightfall/scan-api/1.2.3-beta-1/ai/nightfall/scan/model/BaseNightfallException.java
package ai.nightfall.scan.model; /** * The super class for all exceptions thrown by Nightfall. */ public class BaseNightfallException extends RuntimeException { /** * Create a new exception. * * @param message the error message */ public BaseNightfallException(String message) { super(message); } }