index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/Feature.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.gson.BoundingBoxTypeAdapter;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import java.io.IOException;
/**
* This defines a GeoJson Feature object which represents a spatially bound thing. Every Feature
* object is a GeoJson object no matter where it occurs in a GeoJson text. A Feature object will
* always have a "TYPE" member with the value "Feature".
* <p>
* A Feature object has a member with the name "geometry". The value of the geometry member SHALL be
* either a Geometry object or, in the case that the Feature is unlocated, a JSON null value.
* <p>
* A Feature object has a member with the name "properties". The value of the properties member is
* an object (any JSON object or a JSON null value).
* <p>
* If a Feature has a commonly used identifier, that identifier SHOULD be included as a member of
* the Feature object through the {@link #id()} method, and the value of this member is either a
* JSON string or number.
* <p>
* An example of a serialized feature is given below:
* <pre>
* {
* "TYPE": "Feature",
* "geometry": {
* "TYPE": "Point",
* "coordinates": [102.0, 0.5]
* },
* "properties": {
* "prop0": "value0"
* }
* </pre>
*
*/
@Keep
public final class Feature implements GeoJson {
private static final String TYPE = "Feature";
private final String type;
@JsonAdapter(BoundingBoxTypeAdapter.class)
private final BoundingBox bbox;
private final String id;
private final Geometry geometry;
private final JsonObject properties;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a Feature object from scratch it is better to use one of the other provided static
* factory methods such as {@link #fromGeometry(Geometry)}.
*
* @param json a formatted valid JSON string defining a GeoJson Feature
* @return a new instance of this class defined by the values passed inside this static factory
* method
*/
public static Feature fromJson(@NonNull String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
gson.registerTypeAdapterFactory(GeometryAdapterFactory.create());
Feature feature = gson.create().fromJson(json, Feature.class);
// Even thought properties are Nullable,
// Feature object will be created with properties set to an empty object,
// so that addProperties() would work
if (feature.properties() != null) {
return feature;
}
return new Feature(TYPE, feature.bbox(),
feature.id(), feature.geometry(), new JsonObject());
}
/**
* Create a new instance of this class by giving the feature a {@link Geometry}.
*
* @param geometry a single geometry which makes up this feature object
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Feature fromGeometry(@Nullable Geometry geometry) {
return new Feature(TYPE, null, null, geometry, new JsonObject());
}
/**
* Create a new instance of this class by giving the feature a {@link Geometry}. You can also pass
* in a double array defining a bounding box.
*
* @param geometry a single geometry which makes up this feature object
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Feature fromGeometry(@Nullable Geometry geometry, @Nullable BoundingBox bbox) {
return new Feature(TYPE, bbox, null, geometry, new JsonObject());
}
/**
* Create a new instance of this class by giving the feature a {@link Geometry} and optionally a
* set of properties.
*
* @param geometry a single geometry which makes up this feature object
* @param properties a {@link JsonObject} containing the feature properties
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Feature fromGeometry(@Nullable Geometry geometry, @Nullable JsonObject properties) {
return new Feature(TYPE, null, null, geometry,
properties == null ? new JsonObject() : properties);
}
/**
* Create a new instance of this class by giving the feature a {@link Geometry}, optionally a
* set of properties, and optionally pass in a bbox.
*
* @param geometry a single geometry which makes up this feature object
* @param bbox optionally include a bbox definition as a double array
* @param properties a {@link JsonObject} containing the feature properties
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Feature fromGeometry(@Nullable Geometry geometry, @Nullable JsonObject properties,
@Nullable BoundingBox bbox) {
return new Feature(TYPE, bbox, null, geometry,
properties == null ? new JsonObject() : properties);
}
/**
* Create a new instance of this class by giving the feature a {@link Geometry}, optionally a
* set of properties, and a String which represents the objects id.
*
* @param geometry a single geometry which makes up this feature object
* @param properties a {@link JsonObject} containing the feature properties
* @param id common identifier of this feature
* @return {@link Feature}
*
*/
public static Feature fromGeometry(@Nullable Geometry geometry, @Nullable JsonObject properties,
@Nullable String id) {
return new Feature(TYPE, null, id, geometry,
properties == null ? new JsonObject() : properties);
}
/**
* Create a new instance of this class by giving the feature a {@link Geometry}, optionally a
* set of properties, and a String which represents the objects id.
*
* @param geometry a single geometry which makes up this feature object
* @param properties a {@link JsonObject} containing the feature properties
* @param bbox optionally include a bbox definition as a double array
* @param id common identifier of this feature
* @return {@link Feature}
*
*/
public static Feature fromGeometry(@Nullable Geometry geometry, @NonNull JsonObject properties,
@Nullable String id, @Nullable BoundingBox bbox) {
return new Feature(TYPE, bbox, id, geometry,
properties == null ? new JsonObject() : properties);
}
Feature(String type, @Nullable BoundingBox bbox, @Nullable String id,
@Nullable Geometry geometry, @Nullable JsonObject properties) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
this.id = id;
this.geometry = geometry;
this.properties = properties;
}
/**
* 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}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*/
@Nullable
@Override
public BoundingBox bbox() {
return 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.
*
*/
@Nullable
public String id() {
return 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
*
*/
@Nullable
public Geometry geometry() {
return 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
*
*/
@Nullable
public JsonObject properties() {
return properties;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this Feature
*
*/
@Override
public String toJson() {
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(GeoJsonAdapterFactory.create())
.registerTypeAdapterFactory(GeometryAdapterFactory.create())
.create();
// Empty properties -> should not appear in json string
Feature feature = this;
if (properties().size() == 0) {
feature = new Feature(TYPE, bbox(), id(), geometry(), null);
}
return gson.toJson(feature);
}
/**
* Gson TYPE adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*/
public static TypeAdapter<Feature> typeAdapter(Gson gson) {
return new Feature.GsonTypeAdapter(gson);
}
/**
* Convenience method to add a String member.
*
* @param key name of the member
* @param value the String value associated with the member
*
*/
public void addStringProperty(String key, String value) {
properties().addProperty(key, value);
}
/**
* Convenience method to add a Number member.
*
* @param key name of the member
* @param value the Number value associated with the member
*
*/
public void addNumberProperty(String key, Number value) {
properties().addProperty(key, value);
}
/**
* Convenience method to add a Boolean member.
*
* @param key name of the member
* @param value the Boolean value associated with the member
*
*/
public void addBooleanProperty(String key, Boolean value) {
properties().addProperty(key, value);
}
/**
* Convenience method to add a Character member.
*
* @param key name of the member
* @param value the Character value associated with the member
*
*/
public void addCharacterProperty(String key, Character value) {
properties().addProperty(key, value);
}
/**
* Convenience method to add a JsonElement member.
*
* @param key name of the member
* @param value the JsonElement value associated with the member
*
*/
public void addProperty(String key, JsonElement value) {
properties().add(key, value);
}
/**
* Convenience method to get a String member.
*
* @param key name of the member
* @return the value of the member, null if it doesn't exist
*
*/
public String getStringProperty(String key) {
JsonElement propertyKey = properties().get(key);
return propertyKey == null ? null : propertyKey.getAsString();
}
/**
* Convenience method to get a Number member.
*
* @param key name of the member
* @return the value of the member, null if it doesn't exist
*
*/
public Number getNumberProperty(String key) {
JsonElement propertyKey = properties().get(key);
return propertyKey == null ? null : propertyKey.getAsNumber();
}
/**
* Convenience method to get a Boolean member.
*
* @param key name of the member
* @return the value of the member, null if it doesn't exist
*
*/
public Boolean getBooleanProperty(String key) {
JsonElement propertyKey = properties().get(key);
return propertyKey == null ? null : propertyKey.getAsBoolean();
}
/**
* Convenience method to get a Character member.
*
* @param key name of the member
* @return the value of the member, null if it doesn't exist
*
*/
public Character getCharacterProperty(String key) {
JsonElement propertyKey = properties().get(key);
return propertyKey == null ? null : propertyKey.getAsCharacter();
}
/**
* Convenience method to get a JsonElement member.
*
* @param key name of the member
* @return the value of the member, null if it doesn't exist
*
*/
public JsonElement getProperty(String key) {
return properties().get(key);
}
/**
* Removes the property from the object properties.
*
* @param key name of the member
* @return Removed {@code property} from the key string passed in through the parameter.
*
*/
public JsonElement removeProperty(String key) {
return properties().remove(key);
}
/**
* Convenience method to check if a member with the specified name is present in this object.
*
* @param key name of the member
* @return true if there is the member has the specified name, false otherwise.
*
*/
public boolean hasProperty(String key) {
return properties().has(key);
}
/**
* Convenience method to check for a member by name as well as non-null value.
*
* @param key name of the member
* @return true if member is present with non-null value, false otherwise.
*/
public boolean hasNonNullValueForProperty(String key) {
return hasProperty(key) && !getProperty(key).isJsonNull();
}
@Override
public String toString() {
return "Feature{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "id=" + id + ", "
+ "geometry=" + geometry + ", "
+ "properties=" + properties
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Feature) {
Feature that = (Feature) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& ((this.id == null) ? (that.id() == null) : this.id.equals(that.id()))
&& ((this.geometry == null)
? (that.geometry() == null) : this.geometry.equals(that.geometry()))
&& ((this.properties == null)
? (that.properties() == null) : this.properties.equals(that.properties()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= (id == null) ? 0 : id.hashCode();
hashCode *= 1000003;
hashCode ^= (geometry == null) ? 0 : geometry.hashCode();
hashCode *= 1000003;
hashCode ^= (properties == null) ? 0 : properties.hashCode();
return hashCode;
}
/**
* TypeAdapter to serialize/deserialize Feature objects.
*/
static final class GsonTypeAdapter extends TypeAdapter<Feature> {
private volatile TypeAdapter<String> stringTypeAdapter;
private volatile TypeAdapter<BoundingBox> boundingBoxTypeAdapter;
private volatile TypeAdapter<Geometry> geometryTypeAdapter;
private volatile TypeAdapter<JsonObject> jsonObjectTypeAdapter;
private final Gson gson;
GsonTypeAdapter(Gson gson) {
this.gson = gson;
}
@Override
public void write(JsonWriter jsonWriter, Feature object) throws IOException {
if (object == null) {
jsonWriter.nullValue();
return;
}
jsonWriter.beginObject();
jsonWriter.name("type");
if (object.type() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<String> stringTypeAdapter = this.stringTypeAdapter;
if (stringTypeAdapter == null) {
stringTypeAdapter = gson.getAdapter(String.class);
this.stringTypeAdapter = stringTypeAdapter;
}
stringTypeAdapter.write(jsonWriter, object.type());
}
jsonWriter.name("bbox");
if (object.bbox() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<BoundingBox> boundingBoxTypeAdapter = this.boundingBoxTypeAdapter;
if (boundingBoxTypeAdapter == null) {
boundingBoxTypeAdapter = gson.getAdapter(BoundingBox.class);
this.boundingBoxTypeAdapter = boundingBoxTypeAdapter;
}
boundingBoxTypeAdapter.write(jsonWriter, object.bbox());
}
jsonWriter.name("id");
if (object.id() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<String> stringTypeAdapter = this.stringTypeAdapter;
if (stringTypeAdapter == null) {
stringTypeAdapter = gson.getAdapter(String.class);
this.stringTypeAdapter = stringTypeAdapter;
}
stringTypeAdapter.write(jsonWriter, object.id());
}
jsonWriter.name("geometry");
if (object.geometry() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<Geometry> geometryTypeAdapter = this.geometryTypeAdapter;
if (geometryTypeAdapter == null) {
geometryTypeAdapter = gson.getAdapter(Geometry.class);
this.geometryTypeAdapter = geometryTypeAdapter;
}
geometryTypeAdapter.write(jsonWriter, object.geometry());
}
jsonWriter.name("properties");
if (object.properties() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<JsonObject> jsonObjectTypeAdapter = this.jsonObjectTypeAdapter;
if (jsonObjectTypeAdapter == null) {
jsonObjectTypeAdapter = gson.getAdapter(JsonObject.class);
this.jsonObjectTypeAdapter = jsonObjectTypeAdapter;
}
jsonObjectTypeAdapter.write(jsonWriter, object.properties());
}
jsonWriter.endObject();
}
@Override
public Feature read(JsonReader jsonReader) throws IOException {
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
return null;
}
jsonReader.beginObject();
String type = null;
BoundingBox bbox = null;
String id = null;
Geometry geometry = null;
JsonObject properties = null;
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
continue;
}
switch (name) {
case "type":
TypeAdapter<String> strTypeAdapter = this.stringTypeAdapter;
if (strTypeAdapter == null) {
strTypeAdapter = gson.getAdapter(String.class);
this.stringTypeAdapter = strTypeAdapter;
}
type = strTypeAdapter.read(jsonReader);
break;
case "bbox":
TypeAdapter<BoundingBox> boundingBoxTypeAdapter = this.boundingBoxTypeAdapter;
if (boundingBoxTypeAdapter == null) {
boundingBoxTypeAdapter = gson.getAdapter(BoundingBox.class);
this.boundingBoxTypeAdapter = boundingBoxTypeAdapter;
}
bbox = boundingBoxTypeAdapter.read(jsonReader);
break;
case "id":
strTypeAdapter = this.stringTypeAdapter;
if (strTypeAdapter == null) {
strTypeAdapter = gson.getAdapter(String.class);
this.stringTypeAdapter = strTypeAdapter;
}
id = strTypeAdapter.read(jsonReader);
break;
case "geometry":
TypeAdapter<Geometry> geometryTypeAdapter = this.geometryTypeAdapter;
if (geometryTypeAdapter == null) {
geometryTypeAdapter = gson.getAdapter(Geometry.class);
this.geometryTypeAdapter = geometryTypeAdapter;
}
geometry = geometryTypeAdapter.read(jsonReader);
break;
case "properties":
TypeAdapter<JsonObject> jsonObjectTypeAdapter = this.jsonObjectTypeAdapter;
if (jsonObjectTypeAdapter == null) {
jsonObjectTypeAdapter = gson.getAdapter(JsonObject.class);
this.jsonObjectTypeAdapter = jsonObjectTypeAdapter;
}
properties = jsonObjectTypeAdapter.read(jsonReader);
break;
default:
jsonReader.skipValue();
}
}
jsonReader.endObject();
return new Feature(type, bbox, id, geometry, properties);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/FeatureCollection.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
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 ai.nextbillion.kits.geojson.gson.BoundingBoxTypeAdapter;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* This represents a GeoJson Feature Collection which holds a list of {@link Feature} objects (when
* serialized the feature list becomes a JSON array).
* <p>
* Note that the feature list could potentially be empty. Features within the list must follow the
* specifications defined inside the {@link Feature} class.
* <p>
* An example of a Feature Collections given below:
* <pre>
* {
* "TYPE": "FeatureCollection",
* "bbox": [100.0, 0.0, -100.0, 105.0, 1.0, 0.0],
* "features": [
* //...
* ]
* }
* </pre>
*
*
*/
@Keep
public final class FeatureCollection implements GeoJson {
private static final String TYPE = "FeatureCollection";
private final String type;
@JsonAdapter(BoundingBoxTypeAdapter.class)
private final BoundingBox bbox;
private final List<Feature> features;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a FeatureCollection object from scratch it is better to use one of the other provided
* static factory methods such as {@link #fromFeatures(List)}.
*
* @param json a formatted valid JSON string defining a GeoJson Feature Collection
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static FeatureCollection fromJson(@NonNull String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
gson.registerTypeAdapterFactory(GeometryAdapterFactory.create());
return gson.create().fromJson(json, FeatureCollection.class);
}
/**
* Create a new instance of this class by giving the feature collection an array of
* {@link Feature}s. The array of features itself isn't null but it can be empty and have a length
* of 0.
*
* @param features an array of features
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static FeatureCollection fromFeatures(@NonNull Feature[] features) {
return new FeatureCollection(TYPE, null, Arrays.asList(features));
}
/**
* Create a new instance of this class by giving the feature collection a list of
* {@link Feature}s. The list of features itself isn't null but it can empty and have a size of 0.
*
* @param features a list of features
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static FeatureCollection fromFeatures(@NonNull List<Feature> features) {
return new FeatureCollection(TYPE, null, features);
}
/**
* Create a new instance of this class by giving the feature collection an array of
* {@link Feature}s. The array of features itself isn't null but it can be empty and have a length
* of 0.
*
* @param features an array of features
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static FeatureCollection fromFeatures(@NonNull Feature[] features,
@Nullable BoundingBox bbox) {
return new FeatureCollection(TYPE, bbox, Arrays.asList(features));
}
/**
* Create a new instance of this class by giving the feature collection a list of
* {@link Feature}s. The list of features itself isn't null but it can be empty and have a size of
* 0.
*
* @param features a list of features
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static FeatureCollection fromFeatures(@NonNull List<Feature> features,
@Nullable BoundingBox bbox) {
return new FeatureCollection(TYPE, bbox, features);
}
/**
* Create a new instance of this class by giving the feature collection a single {@link Feature}.
*
* @param feature a single feature
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static FeatureCollection fromFeature(@NonNull Feature feature) {
List<Feature> featureList = Arrays.asList(feature);
return new FeatureCollection(TYPE, null, featureList);
}
/**
* Create a new instance of this class by giving the feature collection a single {@link Feature}.
*
* @param feature a single feature
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static FeatureCollection fromFeature(@NonNull Feature feature,
@Nullable BoundingBox bbox) {
List<Feature> featureList = Arrays.asList(feature);
return new FeatureCollection(TYPE, bbox, featureList);
}
FeatureCollection(String type, @Nullable BoundingBox bbox, @Nullable List<Feature> features) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
this.features = features;
}
/**
* This describes the type of GeoJson this object is, thus this will always return
* {@link FeatureCollection}.
*
* @return a String which describes the TYPE of GeoJson, for this object it will always return
* {@code FeatureCollection}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* This provides the list of feature making up this Feature Collection. Note that if the
* FeatureCollection was created through {@link #fromJson(String)} this list could be null.
* Otherwise, the list can't be null but the size of the list can equal 0.
*
* @return a list of {@link Feature}s which make up this Feature Collection
*
*/
@Nullable
public List<Feature> features() {
return features;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this Feature Collection
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
gson.registerTypeAdapterFactory(GeometryAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Gson type adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<FeatureCollection> typeAdapter(Gson gson) {
return new FeatureCollection.GsonTypeAdapter(gson);
}
@Override
public String toString() {
return "FeatureCollection{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "features=" + features
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof FeatureCollection) {
FeatureCollection that = (FeatureCollection) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& ((this.features == null)
? (that.features() == null) : this.features.equals(that.features()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= (features == null) ? 0 : features.hashCode();
return hashCode;
}
/**
* TypeAdapter to serialize/deserialize FeatureCollection objects.
*/
static final class GsonTypeAdapter extends TypeAdapter<FeatureCollection> {
private volatile TypeAdapter<String> stringAdapter;
private volatile TypeAdapter<BoundingBox> boundingBoxAdapter;
private volatile TypeAdapter<List<Feature>> listFeatureAdapter;
private final Gson gson;
GsonTypeAdapter(Gson gson) {
this.gson = gson;
}
@Override
public void write(JsonWriter jsonWriter, FeatureCollection object) throws IOException {
if (object == null) {
jsonWriter.nullValue();
return;
}
jsonWriter.beginObject();
jsonWriter.name("type");
if (object.type() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<String> stringAdapter = this.stringAdapter;
if (stringAdapter == null) {
stringAdapter = gson.getAdapter(String.class);
this.stringAdapter = stringAdapter;
}
stringAdapter.write(jsonWriter, object.type());
}
jsonWriter.name("bbox");
if (object.bbox() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<BoundingBox> boundingBoxTypeAdapter = this.boundingBoxAdapter;
if (boundingBoxTypeAdapter == null) {
boundingBoxTypeAdapter = gson.getAdapter(BoundingBox.class);
this.boundingBoxAdapter = boundingBoxTypeAdapter;
}
boundingBoxTypeAdapter.write(jsonWriter, object.bbox());
}
jsonWriter.name("features");
if (object.features() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<List<Feature>> listFeatureAdapter = this.listFeatureAdapter;
if (listFeatureAdapter == null) {
TypeToken typeToken = TypeToken.getParameterized(List.class, Feature.class);
listFeatureAdapter =
(TypeAdapter<List<Feature>>) gson.getAdapter(typeToken);
this.listFeatureAdapter = listFeatureAdapter;
}
listFeatureAdapter.write(jsonWriter, object.features());
}
jsonWriter.endObject();
}
@Override
public FeatureCollection read(JsonReader jsonReader) throws IOException {
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
return null;
}
jsonReader.beginObject();
String type = null;
BoundingBox bbox = null;
List<Feature> features = null;
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
continue;
}
switch (name) {
case "type":
TypeAdapter<String> stringAdapter = this.stringAdapter;
if (stringAdapter == null) {
stringAdapter = gson.getAdapter(String.class);
this.stringAdapter = stringAdapter;
}
type = stringAdapter.read(jsonReader);
break;
case "bbox":
TypeAdapter<BoundingBox> boundingBoxAdapter = this.boundingBoxAdapter;
if (boundingBoxAdapter == null) {
boundingBoxAdapter = gson.getAdapter(BoundingBox.class);
this.boundingBoxAdapter = boundingBoxAdapter;
}
bbox = boundingBoxAdapter.read(jsonReader);
break;
case "features":
TypeAdapter<List<Feature>> listFeatureAdapter = this.listFeatureAdapter;
if (listFeatureAdapter == null) {
TypeToken typeToken = TypeToken.getParameterized(List.class, Feature.class);
listFeatureAdapter =
(TypeAdapter<List<Feature>>) gson.getAdapter(typeToken);
this.listFeatureAdapter = listFeatureAdapter;
}
features = listFeatureAdapter.read(jsonReader);
break;
default:
jsonReader.skipValue();
}
}
jsonReader.endObject();
return new FeatureCollection(type, bbox, features);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/GeoJson.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import java.io.Serializable;
/**
* Generic implementation for all GeoJson objects defining common traits that each GeoJson object
* has. This logic is carried over to {@link Geometry} which is an interface which all seven GeoJson
* geometries implement.
*
*/
@Keep
public interface GeoJson extends Serializable {
/**
* This describes the type of GeoJson geometry, Feature, or FeatureCollection this object is.
* Every GeoJson Object will have this defined once an instance is created and will never return
* null.
*
* @return a String which describes the type of geometry, for this object it will always return
* {@code Feature}
*/
String type();
/**
* This takes the currently defined values found inside the GeoJson instance and converts it to a
* GeoJson string.
*
* @return a JSON string which represents this Feature
*/
String toJson();
/**
* A GeoJson object MAY have a member named "bbox" to include information on the coordinate range
* for its Geometries, Features, or FeatureCollections. 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.
*
* @return a double array with the length 2*n where n is the number of dimensions represented in
* the contained geometries
*/
BoundingBox bbox();
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/Geometry.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
/**
* Each of the six geometries and {@link GeometryCollection}
* which make up GeoJson implement this interface.
*/
@Keep
public interface Geometry extends GeoJson {
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/GeometryAdapterFactory.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import com.google.gson.TypeAdapterFactory;
import ai.nextbillion.kits.geojson.typeadapters.RuntimeTypeAdapterFactory;
/**
* A Geometry type adapter factory for convenience for serialization/deserialization.
*/
@Keep
public abstract class GeometryAdapterFactory implements TypeAdapterFactory {
private static TypeAdapterFactory geometryTypeFactory;
/**
* Create a new instance of Geometry type adapter factory, this is passed into the Gson
* Builder.
*
* @return a new GSON TypeAdapterFactory
*/
public static TypeAdapterFactory create() {
if (geometryTypeFactory == null) {
geometryTypeFactory = RuntimeTypeAdapterFactory.of(Geometry.class, "type", true)
.registerSubtype(GeometryCollection.class, "GeometryCollection")
.registerSubtype(Point.class, "Point")
.registerSubtype(MultiPoint.class, "MultiPoint")
.registerSubtype(LineString.class, "LineString")
.registerSubtype(MultiLineString.class, "MultiLineString")
.registerSubtype(Polygon.class, "Polygon")
.registerSubtype(MultiPolygon.class, "MultiPolygon");
}
return geometryTypeFactory;
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/GeometryCollection.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
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 ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* A GeoJson object with TYPE "GeometryCollection" is a Geometry object.
* <p>
* A GeometryCollection has a member with the name "geometries". The value of "geometries" is a List
* Each element of this list is a GeoJson Geometry object. It is possible for this list to be empty.
* <p>
* Unlike the other geometry types, a GeometryCollection can be a heterogeneous composition of
* smaller Geometry objects. For example, a Geometry object in the shape of a lowercase roman "i"
* can be composed of one point and one LineString.
* <p>
* GeometryCollections have a different syntax from single TYPE Geometry objects (Point,
* LineString, and Polygon) and homogeneously typed multipart Geometry objects (MultiPoint,
* MultiLineString, and MultiPolygon) but have no different semantics. Although a
* GeometryCollection object has no "coordinates" member, it does have coordinates: the coordinates
* of all its parts belong to the collection. The "geometries" member of a GeometryCollection
* describes the parts of this composition. Implementations SHOULD NOT apply any additional
* semantics to the "geometries" array.
* <p>
* To maximize interoperability, implementations SHOULD avoid nested GeometryCollections.
* Furthermore, GeometryCollections composed of a single part or a number of parts of a single TYPE
* SHOULD be avoided when that single part or a single object of multipart TYPE (MultiPoint,
* MultiLineString, or MultiPolygon) could be used instead.
* <p>
* An example of a serialized GeometryCollections given below:
* <pre>
* {
* "TYPE": "GeometryCollection",
* "geometries": [{
* "TYPE": "Point",
* "coordinates": [100.0, 0.0]
* }, {
* "TYPE": "LineString",
* "coordinates": [
* [101.0, 0.0],
* [102.0, 1.0]
* ]
* }]
* }
* </pre>
*
*
*/
@Keep
public final class GeometryCollection implements Geometry {
private static final String TYPE = "GeometryCollection";
private final String type;
private final BoundingBox bbox;
private final List<Geometry> geometries;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a GeometryCollection object from scratch it is better to use one of the other provided
* static factory methods such as {@link #fromGeometries(List)}.
*
* @param json a formatted valid JSON string defining a GeoJson Geometry Collection
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static GeometryCollection fromJson(String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
gson.registerTypeAdapterFactory(GeometryAdapterFactory.create());
return gson.create().fromJson(json, GeometryCollection.class);
}
/**
* Create a new instance of this class by giving the collection a list of {@link Geometry}.
*
* @param geometries a non-null list of geometry which makes up this collection
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static GeometryCollection fromGeometries(@NonNull List<Geometry> geometries) {
return new GeometryCollection(TYPE, null, geometries);
}
/**
* Create a new instance of this class by giving the collection a list of {@link Geometry}.
*
* @param geometries a non-null list of geometry which makes up this collection
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static GeometryCollection fromGeometries(@NonNull List<Geometry> geometries,
@Nullable BoundingBox bbox) {
return new GeometryCollection(TYPE, bbox, geometries);
}
/**
* Create a new instance of this class by giving the collection a single GeoJSON {@link Geometry}.
*
* @param geometry a non-null object of type geometry which makes up this collection
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static GeometryCollection fromGeometry(@NonNull Geometry geometry) {
List<Geometry> geometries = Arrays.asList(geometry);
return new GeometryCollection(TYPE, null, geometries);
}
/**
* Create a new instance of this class by giving the collection a single GeoJSON {@link Geometry}.
*
* @param geometry a non-null object of type geometry which makes up this collection
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static GeometryCollection fromGeometry(@NonNull Geometry geometry,
@Nullable BoundingBox bbox) {
List<Geometry> geometries = Arrays.asList(geometry);
return new GeometryCollection(TYPE, bbox, geometries);
}
/**
* Create a new instance of this class by giving the collection a list of {@link Geometry} and
* bounding box.
*
* @param geometries a non-null list of geometry which makes up this collection
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*/
GeometryCollection(String type, @Nullable BoundingBox bbox, List<Geometry> geometries) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
if (geometries == null) {
throw new NullPointerException("Null geometries");
}
this.geometries = geometries;
}
/**
* This describes the TYPE of GeoJson this object is, thus this will always return
* {@link GeometryCollection}.
*
* @return a String which describes the TYPE of geometry, for this object it will always return
* {@code GeometryCollection}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* This provides the list of geometry making up this Geometry Collection. Note that if the
* Geometry Collection was created through {@link #fromJson(String)} this list could be null.
* Otherwise, the list can't be null but the size of the list can equal 0.
*
* @return a list of {@link Geometry} which make up this Geometry Collection
*
*/
@NonNull
public List<Geometry> geometries() {
return geometries;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this GeometryCollection
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
gson.registerTypeAdapterFactory(GeometryAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Gson TYPE adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<GeometryCollection> typeAdapter(Gson gson) {
return new GeometryCollection.GsonTypeAdapter(gson);
}
@Override
public String toString() {
return "GeometryCollection{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "geometries=" + geometries
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof GeometryCollection) {
GeometryCollection that = (GeometryCollection) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& (this.geometries.equals(that.geometries()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= geometries.hashCode();
return hashCode;
}
/**
* TypeAdapter to serialize/deserialize GeometryCollection objects.
*/
static final class GsonTypeAdapter extends TypeAdapter<GeometryCollection> {
private volatile TypeAdapter<String> stringTypeAdapter;
private volatile TypeAdapter<BoundingBox> boundingBoxTypeAdapter;
private volatile TypeAdapter<List<Geometry>> listGeometryAdapter;
private final Gson gson;
GsonTypeAdapter(Gson gson) {
this.gson = gson;
}
@Override
public void write(JsonWriter jsonWriter, GeometryCollection object) throws IOException {
if (object == null) {
jsonWriter.nullValue();
return;
}
jsonWriter.beginObject();
jsonWriter.name("type");
if (object.type() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<String> stringTypeAdapter = this.stringTypeAdapter;
if (stringTypeAdapter == null) {
stringTypeAdapter = gson.getAdapter(String.class);
this.stringTypeAdapter = stringTypeAdapter;
}
stringTypeAdapter.write(jsonWriter, object.type());
}
jsonWriter.name("bbox");
if (object.bbox() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<BoundingBox> boundingBoxTypeAdapter = this.boundingBoxTypeAdapter;
if (boundingBoxTypeAdapter == null) {
boundingBoxTypeAdapter = gson.getAdapter(BoundingBox.class);
this.boundingBoxTypeAdapter = boundingBoxTypeAdapter;
}
boundingBoxTypeAdapter.write(jsonWriter, object.bbox());
}
jsonWriter.name("geometries");
if (object.geometries() == null) {
jsonWriter.nullValue();
} else {
TypeAdapter<List<Geometry>> listGeometryAdapter = this.listGeometryAdapter;
if (listGeometryAdapter == null) {
TypeToken typeToken = TypeToken.getParameterized(List.class, Geometry.class);
listGeometryAdapter =
(TypeAdapter<List<Geometry>>) gson.getAdapter(typeToken);
this.listGeometryAdapter = listGeometryAdapter;
}
listGeometryAdapter.write(jsonWriter, object.geometries());
}
jsonWriter.endObject();
}
@Override
public GeometryCollection read(JsonReader jsonReader) throws IOException {
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
return null;
}
jsonReader.beginObject();
String type = null;
BoundingBox bbox = null;
List<Geometry> geometries = null;
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
continue;
}
switch (name) {
case "type":
TypeAdapter<String> stringTypeAdapter = this.stringTypeAdapter;
if (stringTypeAdapter == null) {
stringTypeAdapter = gson.getAdapter(String.class);
this.stringTypeAdapter = stringTypeAdapter;
}
type = stringTypeAdapter.read(jsonReader);
break;
case "bbox":
TypeAdapter<BoundingBox> boundingBoxTypeAdapter = this.boundingBoxTypeAdapter;
if (boundingBoxTypeAdapter == null) {
boundingBoxTypeAdapter = gson.getAdapter(BoundingBox.class);
this.boundingBoxTypeAdapter = boundingBoxTypeAdapter;
}
bbox = boundingBoxTypeAdapter.read(jsonReader);
break;
case "geometries":
TypeAdapter<List<Geometry>> listGeometryAdapter = this.listGeometryAdapter;
if (listGeometryAdapter == null) {
TypeToken typeToken = TypeToken.getParameterized(List.class, Geometry.class);
listGeometryAdapter =
(TypeAdapter<List<Geometry>>) gson.getAdapter(typeToken);
this.listGeometryAdapter = listGeometryAdapter;
}
geometries = listGeometryAdapter.read(jsonReader);
break;
default:
jsonReader.skipValue();
}
}
jsonReader.endObject();
return new GeometryCollection(type == null ? "GeometryCollection" : type, bbox, geometries);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/LineString.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import ai.nextbillion.kits.geojson.utils.PolylineUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* A linestring represents two or more geographic points that share a relationship and is one of the
* seven geometries found in the GeoJson spec.
* <p>
* This adheres to the RFC 7946 internet standard when serialized into JSON. When deserialized, this
* class becomes an immutable object which should be initiated using its static factory methods.
* </p><p>
* The list of points must be equal to or greater than 2. A LineString has non-zero length and
* zero area. It may approximate a curve and need not be straight. Unlike a LinearRing, a LineString
* is not closed.
* </p><p>
* When representing a LineString that crosses the antimeridian, interoperability is improved by
* modifying their geometry. Any geometry that crosses the antimeridian SHOULD be represented by
* cutting it in two such that neither part's representation crosses the antimeridian.
* </p><p>
* For example, a line extending from 45 degrees N, 170 degrees E across the antimeridian to 45
* degrees N, 170 degrees W should be cut in two and represented as a MultiLineString.
* </p><p>
* A sample GeoJson LineString's provided below (in it's serialized state).
* <pre>
* {
* "TYPE": "LineString",
* "coordinates": [
* [100.0, 0.0],
* [101.0, 1.0]
* ]
* }
* </pre>
* Look over the {@link Point} documentation to get more
* information about formatting your list of point objects correctly.
*
*
*/
@Keep
public final class LineString implements CoordinateContainer<List<Point>> {
private static final String TYPE = "LineString";
private final String type;
private final BoundingBox bbox;
private final List<Point> coordinates;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a LineString object from scratch it is better to use one of the other provided static
* factory methods such as {@link #fromLngLats(List)}. For a valid lineString to exist, it must
* have at least 2 coordinate entries. The LineString should also have non-zero distance and zero
* area.
*
* @param json a formatted valid JSON string defining a GeoJson LineString
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static LineString fromJson(String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().fromJson(json, LineString.class);
}
/**
* Create a new instance of this class by defining a {@link MultiPoint} object and passing. The
* multipoint object should comply with the GeoJson specifications described in the documentation.
*
* @param multiPoint which will make up the LineString geometry
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static LineString fromLngLats(@NonNull MultiPoint multiPoint) {
return new LineString(TYPE, null, multiPoint.coordinates());
}
/**
* Create a new instance of this class by defining a list of {@link Point}s which follow the
* correct specifications described in the Point documentation. Note that there should not be any
* duplicate points inside the list and the points combined should create a LineString with a
* distance greater than 0.
* <p>
* Note that if less than 2 points are passed in, a runtime exception will occur.
* </p>
*
* @param points a list of {@link Point}s which make up the LineString geometry
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static LineString fromLngLats(@NonNull List<Point> points) {
return new LineString(TYPE, null, points);
}
/**
* Create a new instance of this class by defining a list of {@link Point}s which follow the
* correct specifications described in the Point documentation. Note that there should not be any
* duplicate points inside the list and the points combined should create a LineString with a
* distance greater than 0.
* <p>
* Note that if less than 2 points are passed in, a runtime exception will occur.
* </p>
*
* @param points a list of {@link Point}s which make up the LineString geometry
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static LineString fromLngLats(@NonNull List<Point> points, @Nullable BoundingBox bbox) {
return new LineString(TYPE, bbox, points);
}
/**
* Create a new instance of this class by defining a {@link MultiPoint} object and passing. The
* multipoint object should comply with the GeoJson specifications described in the documentation.
*
* @param multiPoint which will make up the LineString geometry
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static LineString fromLngLats(@NonNull MultiPoint multiPoint, @Nullable BoundingBox bbox) {
return new LineString(TYPE, bbox, multiPoint.coordinates());
}
LineString(String type, @Nullable BoundingBox bbox, List<Point> coordinates) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
if (coordinates == null) {
throw new NullPointerException("Null coordinates");
}
this.coordinates = coordinates;
}
static LineString fromLngLats(double[][] coordinates) {
ArrayList<Point> converted = new ArrayList<>(coordinates.length);
for (int i = 0; i < coordinates.length; i++) {
converted.add(Point.fromLngLat(coordinates[i]));
}
return LineString.fromLngLats(converted);
}
/**
* Create a new instance of this class by convert a polyline string into a lineString. This is
* handy when an API provides you with an encoded string representing the line geometry and you'd
* like to convert it to a useful LineString object. Note that the precision that the string
* geometry was encoded with needs to be known and passed into this method using the precision
* parameter.
*
* @param polyline encoded string geometry to decode into a new LineString instance
* @param precision The encoded precision which must match the same precision used when the string
* was first encoded
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static LineString fromPolyline(@NonNull String polyline, int precision) {
return LineString.fromLngLats(PolylineUtils.decode(polyline, precision), null);
}
/**
* This describes the TYPE of GeoJson geometry this object is, thus this will always return
* {@link LineString}.
*
* @return a String which describes the TYPE of geometry, for this object it will always return
* {@code LineString}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* Provides the list of {@link Point}s that make up the LineString geometry.
*
* @return a list of points
*
*/
@NonNull
@Override
public List<Point> coordinates() {
return coordinates;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this LineString geometry
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Encode this LineString into a Polyline string for easier serializing. When passing geometry
* information over a mobile network connection, encoding the geometry first will generally result
* in less bandwidth usage.
*
* @param precision the encoded precision which fits your best use-case
* @return a string describing the geometry of this LineString
*
*/
public String toPolyline(int precision) {
return PolylineUtils.encode(coordinates(), precision);
}
/**
* Gson TYPE adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<LineString> typeAdapter(Gson gson) {
return new LineString.GsonTypeAdapter(gson);
}
@Override
public String toString() {
return "LineString{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "coordinates=" + coordinates
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof LineString) {
LineString that = (LineString) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& (this.coordinates.equals(that.coordinates()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= coordinates.hashCode();
return hashCode;
}
/**
* TypeAdapter for LineString geometry.
*/
static final class GsonTypeAdapter extends BaseGeometryTypeAdapter<LineString, List<Point>> {
GsonTypeAdapter(Gson gson) {
super(gson, new ListOfPointCoordinatesTypeAdapter());
}
@Override
public void write(JsonWriter jsonWriter, LineString object) throws IOException {
writeCoordinateContainer(jsonWriter, object);
}
@Override
public LineString read(JsonReader jsonReader) throws IOException {
return (LineString) readCoordinateContainer(jsonReader);
}
@Override
CoordinateContainer<List<Point>> createCoordinateContainer(String type,
BoundingBox bbox,
List<Point> coordinates) {
return new LineString(type == null ? "LineString" : type, bbox, coordinates);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/ListOfDoublesCoordinatesTypeAdapter.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.List;
/**
* Type Adapter to serialize/deserialize Poinr into/from for double array.
*/
@Keep
class ListOfDoublesCoordinatesTypeAdapter extends BaseCoordinatesTypeAdapter<List<Double>> {
@Override
public void write(JsonWriter out, List<Double> value) throws IOException {
writePointList(out, value);
}
@Override
public List<Double> read(JsonReader in) throws IOException {
return readPointList(in);
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/ListOfListOfPointCoordinatesTypeAdapter.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.exception.GeoJsonException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Type Adapter to serialize/deserialize ist <List<Point>>
* into/from three dimentional double array.
*
*/
@Keep
class ListOfListOfPointCoordinatesTypeAdapter
extends BaseCoordinatesTypeAdapter<List<List<Point>>> {
@Override
public void write(JsonWriter out, List<List<Point>> points) throws IOException {
if (points == null) {
out.nullValue();
return;
}
out.beginArray();
for (List<Point> listOfPoints : points) {
out.beginArray();
for (Point point : listOfPoints) {
writePoint(out, point);
}
out.endArray();
}
out.endArray();
}
@Override
public List<List<Point>> read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
throw new NullPointerException();
}
if (in.peek() == JsonToken.BEGIN_ARRAY) {
in.beginArray();
List<List<Point>> points = new ArrayList<>();
while (in.peek() == JsonToken.BEGIN_ARRAY) {
in.beginArray();
List<Point> listOfPoints = new ArrayList<>();
while (in.peek() == JsonToken.BEGIN_ARRAY) {
listOfPoints.add(readPoint(in));
}
in.endArray();
points.add(listOfPoints);
}
in.endArray();
return points;
}
throw new GeoJsonException("coordinates should be array of array of array of double");
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/ListOfPointCoordinatesTypeAdapter.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.exception.GeoJsonException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Type Adapter to serialize/deserialize List<Point> into/from two dimentional double array.
*/
@Keep
class ListOfPointCoordinatesTypeAdapter extends BaseCoordinatesTypeAdapter<List<Point>> {
@Override
public void write(JsonWriter out, List<Point> points) throws IOException {
if (points == null) {
out.nullValue();
return;
}
out.beginArray();
for (Point point : points) {
writePoint(out, point);
}
out.endArray();
}
@Override
public List<Point> read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
throw new NullPointerException();
}
if (in.peek() == JsonToken.BEGIN_ARRAY) {
List<Point> points = new ArrayList<>();
in.beginArray();
while (in.peek() == JsonToken.BEGIN_ARRAY) {
points.add(readPoint(in));
}
in.endArray();
return points;
}
throw new GeoJsonException("coordinates should be non-null array of array of double");
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/ListofListofListOfPointCoordinatesTypeAdapter.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.exception.GeoJsonException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Type Adapter to serialize/deserialize List<List<List<Point>>> into/from
* four dimentional double array.
*/
@Keep
class ListofListofListOfPointCoordinatesTypeAdapter
extends BaseCoordinatesTypeAdapter<List<List<List<Point>>>> {
@Override
public void write(JsonWriter out, List<List<List<Point>>> points) throws IOException {
if (points == null) {
out.nullValue();
return;
}
out.beginArray();
for (List<List<Point>> listOfListOfPoints : points) {
out.beginArray();
for (List<Point> listOfPoints : listOfListOfPoints) {
out.beginArray();
for (Point point : listOfPoints) {
writePoint(out, point);
}
out.endArray();
}
out.endArray();
}
out.endArray();
}
@Override
public List<List<List<Point>>> read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
throw new NullPointerException();
}
if (in.peek() == JsonToken.BEGIN_ARRAY) {
in.beginArray();
List<List<List<Point>>> listOfListOflistOfPoints = new ArrayList<>();
while (in.peek() == JsonToken.BEGIN_ARRAY) {
in.beginArray();
List<List<Point>> listOfListOfPoints = new ArrayList<>();
while (in.peek() == JsonToken.BEGIN_ARRAY) {
in.beginArray();
List<Point> listOfPoints = new ArrayList<>();
while (in.peek() == JsonToken.BEGIN_ARRAY) {
listOfPoints.add(readPoint(in));
}
in.endArray();
listOfListOfPoints.add(listOfPoints);
}
in.endArray();
listOfListOflistOfPoints.add(listOfListOfPoints);
}
in.endArray();
return listOfListOflistOfPoints;
}
throw new GeoJsonException("coordinates should be array of array of array of double");
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/MultiLineString.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A multilinestring is an array of LineString coordinate arrays.
* <p>
* This adheres to the RFC 7946 internet standard when serialized into JSON. When deserialized, this
* class becomes an immutable object which should be initiated using its static factory methods.
* </p><p>
* When representing a LineString that crosses the antimeridian, interoperability is improved by
* modifying their geometry. Any geometry that crosses the antimeridian SHOULD be represented by
* cutting it in two such that neither part's representation crosses the antimeridian.
* </p><p>
* For example, a line extending from 45 degrees N, 170 degrees E across the antimeridian to 45
* degrees N, 170 degrees W should be cut in two and represented as a MultiLineString.
* </p><p>
* A sample GeoJson MultiLineString's provided below (in it's serialized state).
* <pre>
* {
* "type": "MultiLineString",
* "coordinates": [
* [
* [100.0, 0.0],
* [101.0, 1.0]
* ],
* [
* [102.0, 2.0],
* [103.0, 3.0]
* ]
* ]
* }
* </pre>
* Look over the {@link LineString} documentation to get more information about
* formatting your list of linestring objects correctly.
*
*
*/
@Keep
public final class MultiLineString
implements CoordinateContainer<List<List<Point>>> {
private static final String TYPE = "MultiLineString";
private final String type;
private final BoundingBox bbox;
private final List<List<Point>> coordinates;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a MultiLineString object from scratch it is better to use one of the other provided
* static factory methods such as {@link #fromLineStrings(List)}.
*
* @param json a formatted valid JSON string defining a GeoJson MultiLineString
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiLineString fromJson(@NonNull String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().fromJson(json, MultiLineString.class);
}
/**
* Create a new instance of this class by defining a list of {@link LineString} objects and
* passing that list in as a parameter in this method. The LineStrings should comply with the
* GeoJson specifications described in the documentation.
*
* @param lineStrings a list of LineStrings which make up this MultiLineString
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiLineString fromLineStrings(@NonNull List<LineString> lineStrings) {
List<List<Point>> coordinates = new ArrayList<>(lineStrings.size());
for (LineString lineString : lineStrings) {
coordinates.add(lineString.coordinates());
}
return new MultiLineString(TYPE, null, coordinates);
}
/**
* Create a new instance of this class by defining a list of {@link LineString} objects and
* passing that list in as a parameter in this method. The LineStrings should comply with the
* GeoJson specifications described in the documentation. Optionally, pass in an instance of a
* {@link BoundingBox} which better describes this MultiLineString.
*
* @param lineStrings a list of LineStrings which make up this MultiLineString
* @param bbox optionally include a bbox definition
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiLineString fromLineStrings(@NonNull List<LineString> lineStrings,
@Nullable BoundingBox bbox) {
List<List<Point>> coordinates = new ArrayList<>(lineStrings.size());
for (LineString lineString : lineStrings) {
coordinates.add(lineString.coordinates());
}
return new MultiLineString(TYPE, bbox, coordinates);
}
/**
* Create a new instance of this class by passing in a single {@link LineString} object. The
* LineStrings should comply with the GeoJson specifications described in the documentation.
*
* @param lineString a single LineString which make up this MultiLineString
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiLineString fromLineString(@NonNull LineString lineString) {
List<List<Point>> coordinates = Arrays.asList(lineString.coordinates());
return new MultiLineString(TYPE, null, coordinates);
}
/**
* Create a new instance of this class by passing in a single {@link LineString} object. The
* LineStrings should comply with the GeoJson specifications described in the documentation.
*
* @param lineString a single LineString which make up this MultiLineString
* @param bbox optionally include a bbox definition
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiLineString fromLineString(@NonNull LineString lineString,
@Nullable BoundingBox bbox) {
List<List<Point>> coordinates = Arrays.asList(lineString.coordinates());
return new MultiLineString(TYPE, bbox, coordinates);
}
/**
* Create a new instance of this class by defining a list of a list of {@link Point}s which follow
* the correct specifications described in the Point documentation. Note that there should not be
* any duplicate points inside the list and the points combined should create a LineString with a
* distance greater than 0.
*
* @param points a list of {@link Point}s which make up the MultiLineString geometry
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiLineString fromLngLats(@NonNull List<List<Point>> points) {
return new MultiLineString(TYPE, null, points);
}
/**
* Create a new instance of this class by defining a list of a list of {@link Point}s which follow
* the correct specifications described in the Point documentation. Note that there should not be
* any duplicate points inside the list and the points combined should create a LineString with a
* distance greater than 0.
*
* @param points a list of {@link Point}s which make up the MultiLineString geometry
* @param bbox optionally include a bbox definition
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiLineString fromLngLats(@NonNull List<List<Point>> points,
@Nullable BoundingBox bbox) {
return new MultiLineString(TYPE, bbox, points);
}
static MultiLineString fromLngLats(double[][][] coordinates) {
List<List<Point>> multiLine = new ArrayList<>(coordinates.length);
for (int i = 0; i < coordinates.length; i++) {
List<Point> lineString = new ArrayList<>(coordinates[i].length);
for (int j = 0; j < coordinates[i].length; j++) {
lineString.add(Point.fromLngLat(coordinates[i][j]));
}
multiLine.add(lineString);
}
return new MultiLineString(TYPE, null, multiLine);
}
MultiLineString(String type, @Nullable BoundingBox bbox, List<List<Point>> coordinates) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
if (coordinates == null) {
throw new NullPointerException("Null coordinates");
}
this.coordinates = coordinates;
}
/**
* This describes the TYPE of GeoJson geometry this object is, thus this will always return
* {@link MultiLineString}.
*
* @return a String which describes the TYPE of geometry, for this object it will always return
* {@code MultiLineString}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* Provides the list of list of {@link Point}s that make up the MultiLineString geometry.
*
* @return a list of points
*
*/
@NonNull
@Override
public List<List<Point>> coordinates() {
return coordinates;
}
/**
* Returns a list of LineStrings which are currently making up this MultiLineString.
*
* @return a list of {@link LineString}s
*
*/
public List<LineString> lineStrings() {
List<List<Point>> coordinates = coordinates();
List<LineString> lineStrings = new ArrayList<>(coordinates.size());
for (List<Point> points : coordinates) {
lineStrings.add(LineString.fromLngLats(points));
}
return lineStrings;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this MultiLineString geometry
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Gson type adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<MultiLineString> typeAdapter(Gson gson) {
return new MultiLineString.GsonTypeAdapter(gson);
}
@Override
public String toString() {
return "MultiLineString{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "coordinates=" + coordinates
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof MultiLineString) {
MultiLineString that = (MultiLineString) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& (this.coordinates.equals(that.coordinates()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= coordinates.hashCode();
return hashCode;
}
/**
* TypeAdapter for MultiLineString geometry.
*/
static final class GsonTypeAdapter
extends BaseGeometryTypeAdapter<MultiLineString, List<List<Point>>> {
GsonTypeAdapter(Gson gson) {
super(gson, new ListOfListOfPointCoordinatesTypeAdapter());
}
@Override
public void write(JsonWriter jsonWriter, MultiLineString object) throws IOException {
writeCoordinateContainer(jsonWriter, object);
}
@Override
public MultiLineString read(JsonReader jsonReader) throws IOException {
return (MultiLineString) readCoordinateContainer(jsonReader);
}
@Override
CoordinateContainer<List<List<Point>>> createCoordinateContainer(String type,
BoundingBox bbox,
List<List<Point>> coords) {
return new MultiLineString(type == null ? "MultiLineString" : type, bbox, coords);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/MultiPoint.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* A MultiPoint represents two or more geographic points that share a relationship and is one of the
* seven geometries found in the GeoJson spec. <p> This adheres to the RFC 7946 internet standard
* when serialized into JSON. When deserialized, this class becomes an immutable object which should
* be initiated using its static factory methods. The list of points must be equal to or greater
* than 2. </p><p> A sample GeoJson MultiPoint's provided below (in it's serialized state).
* <pre>
* {
* "TYPE": "MultiPoint",
* "coordinates": [
* [100.0, 0.0],
* [101.0, 1.0]
* ]
* }
* </pre>
* Look over the {@link Point} documentation to get more
* information about formatting your list of point objects correctly.
*
*
*/
@Keep
public final class MultiPoint implements CoordinateContainer<List<Point>> {
private static final String TYPE = "MultiPoint";
private final String type;
private final BoundingBox bbox;
private final List<Point> coordinates;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a MultiPoint object from scratch it is better to use one of the other provided static
* factory methods such as {@link #fromLngLats(List)}. For a valid MultiPoint to exist, it must
* have at least 2 coordinate entries.
*
* @param json a formatted valid JSON string defining a GeoJson MultiPoint
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPoint fromJson(@NonNull String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().fromJson(json, MultiPoint.class);
}
/**
* Create a new instance of this class by defining a list of {@link Point}s which follow the
* correct specifications described in the Point documentation. Note that there should not be any
* duplicate points inside the list. <p> Note that if less than 2 points are passed in, a runtime
* exception will occur. </p>
*
* @param points a list of {@link Point}s which make up the LineString geometry
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPoint fromLngLats(@NonNull List<Point> points) {
return new MultiPoint(TYPE, null, points);
}
/**
* Create a new instance of this class by defining a list of {@link Point}s which follow the
* correct specifications described in the Point documentation. Note that there should not be any
* duplicate points inside the list. <p> Note that if less than 2 points are passed in, a runtime
* exception will occur. </p>
*
* @param points a list of {@link Point}s which make up the LineString geometry
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPoint fromLngLats(@NonNull List<Point> points, @Nullable BoundingBox bbox) {
return new MultiPoint(TYPE, bbox, points);
}
static MultiPoint fromLngLats(@NonNull double[][] coordinates) {
ArrayList<Point> converted = new ArrayList<>(coordinates.length);
for (int i = 0; i < coordinates.length; i++) {
converted.add(Point.fromLngLat(coordinates[i]));
}
return new MultiPoint(TYPE, null, converted);
}
MultiPoint(String type, @Nullable BoundingBox bbox, List<Point> coordinates) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
if (coordinates == null) {
throw new NullPointerException("Null coordinates");
}
this.coordinates = coordinates;
}
/**
* This describes the TYPE of GeoJson this object is, thus this will always return {@link
* MultiPoint}.
*
* @return a String which describes the TYPE of geometry, for this object it will always return
* {@code MultiPoint}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* provides the list of {@link Point}s that make up the MultiPoint geometry.
*
* @return a list of points
*
*/
@NonNull
@Override
public List<Point> coordinates() {
return coordinates;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this MultiPoint geometry
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Gson TYPE adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<MultiPoint> typeAdapter(Gson gson) {
return new MultiPoint.GsonTypeAdapter(gson);
}
@Override
public String toString() {
return "MultiPoint{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "coordinates=" + coordinates
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof MultiPoint) {
MultiPoint that = (MultiPoint) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& (this.coordinates.equals(that.coordinates()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= coordinates.hashCode();
return hashCode;
}
/**
* TypeAdapter for MultiPoint geometry.
*/
static final class GsonTypeAdapter extends BaseGeometryTypeAdapter<MultiPoint, List<Point>> {
GsonTypeAdapter(Gson gson) {
super(gson, new ListOfPointCoordinatesTypeAdapter());
}
@Override
public void write(JsonWriter jsonWriter, MultiPoint object) throws IOException {
writeCoordinateContainer(jsonWriter, object);
}
@Override
public MultiPoint read(JsonReader jsonReader) throws IOException {
return (MultiPoint) readCoordinateContainer(jsonReader);
}
@Override
CoordinateContainer<List<Point>> createCoordinateContainer(String type,
BoundingBox bbox,
List<Point> coordinates) {
return new MultiPoint(type == null ? "MultiPoint" : type, bbox, coordinates);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/MultiPolygon.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A multiPolygon is an array of Polygon coordinate arrays.
* <p>
* This adheres to the RFC 7946 internet standard when serialized into JSON. When deserialized, this
* class becomes an immutable object which should be initiated using its static factory methods.
* </p><p>
* When representing a Polygon that crosses the antimeridian, interoperability is improved by
* modifying their geometry. Any geometry that crosses the antimeridian SHOULD be represented by
* cutting it in two such that neither part's representation crosses the antimeridian.
* </p><p>
* For example, a line extending from 45 degrees N, 170 degrees E across the antimeridian to 45
* degrees N, 170 degrees W should be cut in two and represented as a MultiLineString.
* </p><p>
* A sample GeoJson MultiPolygon's provided below (in it's serialized state).
* <pre>
* {
* "type": "MultiPolygon",
* "coordinates": [
* [
* [
* [102.0, 2.0],
* [103.0, 2.0],
* [103.0, 3.0],
* [102.0, 3.0],
* [102.0, 2.0]
* ]
* ],
* [
* [
* [100.0, 0.0],
* [101.0, 0.0],
* [101.0, 1.0],
* [100.0, 1.0],
* [100.0, 0.0]
* ],
* [
* [100.2, 0.2],
* [100.2, 0.8],
* [100.8, 0.8],
* [100.8, 0.2],
* [100.2, 0.2]
* ]
* ]
* ]
* }
* </pre>
* Look over the {@link Polygon} documentation to get more information about
* formatting your list of Polygon objects correctly.
*
*
*/
@Keep
public final class MultiPolygon
implements CoordinateContainer<List<List<List<Point>>>> {
private static final String TYPE = "MultiPolygon";
private final String type;
private final BoundingBox bbox;
private final List<List<List<Point>>> coordinates;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a MultiPolygon object from scratch it is better to use one of the other provided
* static factory methods such as {@link #fromPolygons(List)}.
*
* @param json a formatted valid JSON string defining a GeoJson MultiPolygon
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPolygon fromJson(String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().fromJson(json, MultiPolygon.class);
}
/**
* Create a new instance of this class by defining a list of {@link Polygon} objects and passing
* that list in as a parameter in this method. The Polygons should comply with the GeoJson
* specifications described in the documentation.
*
* @param polygons a list of Polygons which make up this MultiPolygon
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPolygon fromPolygons(@NonNull List<Polygon> polygons) {
List<List<List<Point>>> coordinates = new ArrayList<>(polygons.size());
for (Polygon polygon : polygons) {
coordinates.add(polygon.coordinates());
}
return new MultiPolygon(TYPE, null, coordinates);
}
/**
* Create a new instance of this class by defining a list of {@link Polygon} objects and passing
* that list in as a parameter in this method. The Polygons should comply with the GeoJson
* specifications described in the documentation. Optionally, pass in an instance of a
* {@link BoundingBox} which better describes this MultiPolygon.
*
* @param polygons a list of Polygons which make up this MultiPolygon
* @param bbox optionally include a bbox definition
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPolygon fromPolygons(@NonNull List<Polygon> polygons,
@Nullable BoundingBox bbox) {
List<List<List<Point>>> coordinates = new ArrayList<>(polygons.size());
for (Polygon polygon : polygons) {
coordinates.add(polygon.coordinates());
}
return new MultiPolygon(TYPE, bbox, coordinates);
}
/**
* Create a new instance of this class by defining a single {@link Polygon} objects and passing
* it in as a parameter in this method. The Polygon should comply with the GeoJson
* specifications described in the documentation.
*
* @param polygon a single Polygon which make up this MultiPolygon
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPolygon fromPolygon(@NonNull Polygon polygon) {
List<List<List<Point>>> coordinates = Arrays.asList(polygon.coordinates());
return new MultiPolygon(TYPE, null, coordinates);
}
/**
* Create a new instance of this class by defining a single {@link Polygon} objects and passing
* it in as a parameter in this method. The Polygon should comply with the GeoJson
* specifications described in the documentation.
*
* @param polygon a single Polygon which make up this MultiPolygon
* @param bbox optionally include a bbox definition
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPolygon fromPolygon(@NonNull Polygon polygon, @Nullable BoundingBox bbox) {
List<List<List<Point>>> coordinates = Arrays.asList(polygon.coordinates());
return new MultiPolygon(TYPE, bbox, coordinates);
}
/**
* Create a new instance of this class by defining a list of a list of a list of {@link Point}s
* which follow the correct specifications described in the Point documentation.
*
* @param points a list of {@link Point}s which make up the MultiPolygon geometry
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPolygon fromLngLats(@NonNull List<List<List<Point>>> points) {
return new MultiPolygon(TYPE, null, points);
}
/**
* Create a new instance of this class by defining a list of a list of a list of {@link Point}s
* which follow the correct specifications described in the Point documentation.
*
* @param points a list of {@link Point}s which make up the MultiPolygon geometry
* @param bbox optionally include a bbox definition
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static MultiPolygon fromLngLats(@NonNull List<List<List<Point>>> points,
@Nullable BoundingBox bbox) {
return new MultiPolygon(TYPE, bbox, points);
}
static MultiPolygon fromLngLats(@NonNull double[][][][] coordinates) {
List<List<List<Point>>> converted = new ArrayList<>(coordinates.length);
for (int i = 0; i < coordinates.length; i++) {
List<List<Point>> innerOneList = new ArrayList<>(coordinates[i].length);
for (int j = 0; j < coordinates[i].length; j++) {
List<Point> innerTwoList = new ArrayList<>(coordinates[i][j].length);
for (int k = 0; k < coordinates[i][j].length; k++) {
innerTwoList.add(Point.fromLngLat(coordinates[i][j][k]));
}
innerOneList.add(innerTwoList);
}
converted.add(innerOneList);
}
return new MultiPolygon(TYPE, null, converted);
}
MultiPolygon(String type, @Nullable BoundingBox bbox, List<List<List<Point>>> coordinates) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
if (coordinates == null) {
throw new NullPointerException("Null coordinates");
}
this.coordinates = coordinates;
}
/**
* Returns a list of polygons which make up this MultiPolygon instance.
*
* @return a list of {@link Polygon}s which make up this MultiPolygon instance
*
*/
public List<Polygon> polygons() {
List<List<List<Point>>> coordinates = coordinates();
List<Polygon> polygons = new ArrayList<>(coordinates.size());
for (List<List<Point>> points : coordinates) {
polygons.add(Polygon.fromLngLats(points));
}
return polygons;
}
/**
* This describes the TYPE of GeoJson geometry this object is, thus this will always return
* {@link MultiPolygon}.
*
* @return a String which describes the TYPE of geometry, for this object it will always return
* {@code MultiPolygon}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* Provides the list of list of list of {@link Point}s that make up the MultiPolygon geometry.
*
* @return a list of points
*
*/
@NonNull
@Override
public List<List<List<Point>>> coordinates() {
return coordinates;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this MultiPolygon geometry
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Gson TYPE adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<MultiPolygon> typeAdapter(Gson gson) {
return new MultiPolygon.GsonTypeAdapter(gson);
}
@Override
public String toString() {
return "Polygon{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "coordinates=" + coordinates
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof MultiPolygon) {
MultiPolygon that = (MultiPolygon) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& (this.coordinates.equals(that.coordinates()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= coordinates.hashCode();
return hashCode;
}
/**
* TypeAdapter for MultiPolygon geometry.
*/
static final class GsonTypeAdapter
extends BaseGeometryTypeAdapter<MultiPolygon, List<List<List<Point>>>> {
GsonTypeAdapter(Gson gson) {
super(gson, new ListofListofListOfPointCoordinatesTypeAdapter());
}
@Override
public void write(JsonWriter jsonWriter, MultiPolygon object) throws IOException {
writeCoordinateContainer(jsonWriter, object);
}
@Override
public MultiPolygon read(JsonReader jsonReader) throws IOException {
return (MultiPolygon) readCoordinateContainer(jsonReader);
}
@Override
CoordinateContainer<List<List<List<Point>>>>
createCoordinateContainer(String type, BoundingBox bbox, List<List<List<Point>>> coords) {
return new MultiPolygon(type == null ? "MultiPolygon" : type, bbox, coords);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/Point.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import ai.nextbillion.kits.geojson.shifter.CoordinateShifterManager;
import java.io.IOException;
import java.util.List;
/**
* A point represents a single geographic position and is one of the seven Geometries found in the
* GeoJson spec.
* <p>
* This adheres to the RFC 7946 internet standard when serialized into JSON. When deserialized, this
* class becomes an immutable object which should be initiated using its static factory methods.
* </p><p>
* Coordinates are in x, y order (easting, northing for projected coordinates), longitude, and
* latitude for geographic coordinates), precisely in that order and using double values. Altitude
* or elevation MAY be included as an optional third parameter while creating this object.
* <p>
* The size of a GeoJson text in bytes is a major interoperability consideration, and precision of
* coordinate values has a large impact on the size of texts when serialized. For geographic
* coordinates with units of degrees, 6 decimal places (a default common in, e.g., sprintf) amounts
* to about 10 centimeters, a precision well within that of current GPS systems. Implementations
* should consider the cost of using a greater precision than necessary.
* <p>
* Furthermore, pertaining to altitude, the WGS 84 datum is a relatively coarse approximation of the
* geoid, with the height varying by up to 5 m (but generally between 2 and 3 meters) higher or
* lower relative to a surface parallel to Earth's mean sea level.
* <p>
* A sample GeoJson Point's provided below (in its serialized state).
* <pre>
* {
* "type": "Point",
* "coordinates": [100.0, 0.0]
* }
* </pre>
*
*
*/
@Keep
public final class Point implements CoordinateContainer<List<Double>> {
private static final String TYPE = "Point";
@NonNull
private final String type;
@Nullable
private final BoundingBox bbox;
@NonNull
private final List<Double> coordinates;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a Point object from scratch it is better to use one of the other provided static
* factory methods such as {@link #fromLngLat(double, double)}. While no limit is placed
* on decimal precision, for performance reasons when serializing and deserializing it is
* suggested to limit decimal precision to within 6 decimal places.
*
* @param json a formatted valid JSON string defining a GeoJson Point
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Point fromJson(@NonNull String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().fromJson(json, Point.class);
}
/**
* Create a new instance of this class defining a longitude and latitude value in that respective
* order. While no limit is placed on decimal precision, for performance reasons
* when serializing and deserializing it is suggested to limit decimal precision to within 6
* decimal places.
*
* @param longitude a double value representing the x position of this point
* @param latitude a double value representing the y position of this point
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Point fromLngLat(double longitude, double latitude) {
List<Double> coordinates =
CoordinateShifterManager.getCoordinateShifter().shiftLonLat(longitude, latitude);
return new Point(TYPE, null, coordinates);
}
/**
* Create a new instance of this class defining a longitude and latitude value in that respective
* order. While no limit is placed on decimal precision, for performance reasons
* when serializing and deserializing it is suggested to limit decimal precision to within 6
* decimal places. An optional altitude value can be passed in and can vary between negative
* infinity and positive infinity.
*
* @param longitude a double value representing the x position of this point
* @param latitude a double value representing the y position of this point
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Point fromLngLat(double longitude, double latitude,
@Nullable BoundingBox bbox) {
List<Double> coordinates =
CoordinateShifterManager.getCoordinateShifter().shiftLonLat(longitude, latitude);
return new Point(TYPE, bbox, coordinates);
}
/**
* Create a new instance of this class defining a longitude and latitude value in that respective
* order. While no limit is placed on decimal precision, for performance reasons
* when serializing and deserializing it is suggested to limit decimal precision to within 6
* decimal places. An optional altitude value can be passed in and can vary between negative
* infinity and positive infinity.
*
* @param longitude a double value representing the x position of this point
* @param latitude a double value representing the y position of this point
* @param altitude a double value which can be negative or positive infinity representing either
* elevation or altitude
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Point fromLngLat(double longitude, double latitude, double altitude) {
List<Double> coordinates =
CoordinateShifterManager.getCoordinateShifter().shiftLonLatAlt(longitude, latitude, altitude);
return new Point(TYPE, null, coordinates);
}
/**
* Create a new instance of this class defining a longitude and latitude value in that respective
* order. While no limit is placed on decimal precision, for performance reasons
* when serializing and deserializing it is suggested to limit decimal precision to within 6
* decimal places. An optional altitude value can be passed in and can vary between negative
* infinity and positive infinity.
*
* @param longitude a double value representing the x position of this point
* @param latitude a double value representing the y position of this point
* @param altitude a double value which can be negative or positive infinity representing either
* elevation or altitude
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Point fromLngLat(double longitude, double latitude,
double altitude, @Nullable BoundingBox bbox) {
List<Double> coordinates =
CoordinateShifterManager.getCoordinateShifter().shiftLonLatAlt(longitude, latitude, altitude);
return new Point(TYPE, bbox, coordinates);
}
static Point fromLngLat(@NonNull double[] coords) {
if (coords.length == 2) {
return Point.fromLngLat(coords[0], coords[1]);
} else if (coords.length > 2) {
return Point.fromLngLat(coords[0], coords[1], coords[2]);
}
return null;
}
Point(String type, @Nullable BoundingBox bbox, List<Double> coordinates) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
if (coordinates == null || coordinates.size() == 0) {
throw new NullPointerException("Null coordinates");
}
this.coordinates = coordinates;
}
/**
* This returns a double value representing the x or easting position of
* this point. ideally, this value would be restricted to 6 decimal places to correctly follow the
* GeoJson spec.
*
* @return a double value representing the x or easting position of this
* point
*
*/
public double longitude() {
return coordinates().get(0);
}
/**
* This returns a double value representing the y or northing position of
* this point. ideally, this value would be restricted to 6 decimal places to correctly follow the
* GeoJson spec.
*
* @return a double value representing the y or northing position of this
* point
*
*/
public double latitude() {
return coordinates().get(1);
}
/**
* Optionally, the coordinate spec in GeoJson allows for altitude values to be placed inside the
* coordinate array. {@link #hasAltitude()} can be used to determine if this value was set during
* initialization of this Point instance. This double value should only be used to represent
* either the elevation or altitude value at this particular point.
*
* @return a double value ranging from negative to positive infinity
*
*/
public double altitude() {
if (coordinates().size() < 3) {
return Double.NaN;
}
return coordinates().get(2);
}
/**
* Optionally, the coordinate spec in GeoJson allows for altitude values to be placed inside the
* coordinate array. If an altitude value was provided while initializing this instance, this will
* return true.
*
* @return true if this instance of point contains an altitude value
*
*/
public boolean hasAltitude() {
return !Double.isNaN(altitude());
}
/**
* This describes the TYPE of GeoJson geometry this object is, thus this will always return
* {@link Point}.
*
* @return a String which describes the TYPE of geometry, for this object it will always return
* {@code Point}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* Provide a single double array containing the longitude, latitude, and optionally an
* altitude/elevation. {@link #longitude()}, {@link #latitude()}, and {@link #altitude()} are all
* avaliable which make getting specific coordinates more direct.
*
* @return a double array which holds this points coordinates
*
*/
@NonNull
@Override
public List<Double> coordinates() {
return coordinates;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this Point geometry
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Gson TYPE adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<Point> typeAdapter(Gson gson) {
return new Point.GsonTypeAdapter(gson);
}
@Override
public String toString() {
return "Point{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "coordinates=" + coordinates
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Point) {
Point that = (Point) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& (this.coordinates.equals(that.coordinates()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= coordinates.hashCode();
return hashCode;
}
/**
* TypeAdapter for Point geometry.
*
*
*/
static final class GsonTypeAdapter extends BaseGeometryTypeAdapter<Point, List<Double>> {
GsonTypeAdapter(Gson gson) {
super(gson, new ListOfDoublesCoordinatesTypeAdapter());
}
@Override
@SuppressWarnings("unchecked")
public void write(JsonWriter jsonWriter, Point object) throws IOException {
writeCoordinateContainer(jsonWriter, object);
}
@Override
@SuppressWarnings("unchecked")
public Point read(JsonReader jsonReader) throws IOException {
return (Point)readCoordinateContainer(jsonReader);
}
@Override
CoordinateContainer<List<Double>> createCoordinateContainer(String type,
BoundingBox bbox,
List<Double> coordinates) {
return new Point(type == null ? "Point" : type, bbox, coordinates);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/PointAsCoordinatesTypeAdapter.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/**
* TypeAdapter to serialize Point as coordinates, i.e array of doubles and
* to deserialize into Point out of array of doubles.
*/
@Keep
public class PointAsCoordinatesTypeAdapter extends BaseCoordinatesTypeAdapter<Point> {
@Override
public void write(JsonWriter out, Point value) throws IOException {
writePoint(out, value);
}
@Override
public Point read(JsonReader in) throws IOException {
return readPoint(in);
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/Polygon.java
|
package ai.nextbillion.kits.geojson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Size;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.exception.GeoJsonException;
import ai.nextbillion.kits.geojson.gson.GeoJsonAdapterFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents a GeoJson Polygon which may or may not include polygon holes.
* <p>
* To specify a constraint specific to Polygons, it is useful to introduce the concept of a linear
* ring:
* <ul>
* <li>A linear ring is a closed LineString with four or more coordinates.</li>
* <li>The first and last coordinates are equivalent, and they MUST contain identical values; their
* representation SHOULD also be identical.</li>
* <li>A linear ring is the boundary of a surface or the boundary of a hole in a surface.</li>
* <li>A linear ring MUST follow the right-hand rule with respect to the area it bounds, i.e.,
* exterior rings are counterclockwise, and holes are clockwise.</li>
* </ul>
* Note that most of the rules listed above are checked when a Polygon instance is created (the
* exception being the last rule). If one of the rules is broken, a {@link RuntimeException} will
* occur.
* <p>
* Though a linear ring is not explicitly represented as a GeoJson geometry TYPE, it leads to a
* canonical formulation of the Polygon geometry TYPE. When initializing a new instance of this
* class, a LineString for the outer and optionally an inner are checked to ensure a valid linear
* ring.
* <p>
* An example of a serialized polygon with no holes is given below:
* <pre>
* {
* "TYPE": "Polygon",
* "coordinates": [
* [[100.0, 0.0],
* [101.0, 0.0],
* [101.0, 1.0],
* [100.0, 1.0],
* [100.0, 0.0]]
* ]
* }
* </pre>
*
*
*/
@Keep
public final class Polygon implements CoordinateContainer<List<List<Point>>> {
private static final String TYPE = "Polygon";
private final String type;
private final BoundingBox bbox;
private final List<List<Point>> coordinates;
/**
* Create a new instance of this class by passing in a formatted valid JSON String. If you are
* creating a Polygon object from scratch it is better to use one of the other provided static
* factory methods such as {@link #fromOuterInner(LineString, LineString...)}. For a valid
* For a valid Polygon to exist, it must follow the linear ring rules and the first list of
* coordinates are considered the outer ring by default.
*
* @param json a formatted valid JSON string defining a GeoJson Polygon
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Polygon fromJson(@NonNull String json) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().fromJson(json, Polygon.class);
}
/**
* Create a new instance of this class by defining a list of {@link Point}s which follow the
* correct specifications described in the Point documentation. Note that the first and last point
* in the list should be the same enclosing the linear ring.
*
* @param coordinates a list of a list of points which represent the polygon geometry
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Polygon fromLngLats(@NonNull List<List<Point>> coordinates) {
return new Polygon(TYPE, null, coordinates);
}
/**
* Create a new instance of this class by defining a list of {@link Point}s which follow the
* correct specifications described in the Point documentation. Note that the first and last point
* in the list should be the same enclosing the linear ring.
*
* @param coordinates a list of a list of points which represent the polygon geometry
* @param bbox optionally include a bbox definition as a double array
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Polygon fromLngLats(@NonNull List<List<Point>> coordinates,
@Nullable BoundingBox bbox) {
return new Polygon(TYPE, bbox, coordinates);
}
/**
* Create a new instance of this class by passing in three dimensional double array which defines
* the geometry of this polygon.
*
* @param coordinates a three dimensional double array defining this polygons geometry
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
static Polygon fromLngLats(@NonNull double[][][] coordinates) {
List<List<Point>> converted = new ArrayList<>(coordinates.length);
for (double[][] coordinate : coordinates) {
List<Point> innerList = new ArrayList<>(coordinate.length);
for (double[] pointCoordinate : coordinate) {
innerList.add(Point.fromLngLat(pointCoordinate));
}
converted.add(innerList);
}
return new Polygon(TYPE, null, converted);
}
/**
* Create a new instance of this class by passing in an outer {@link LineString} and optionally
* one or more inner LineStrings. Each of these LineStrings should follow the linear ring rules.
* <p>
* Note that if a LineString breaks one of the linear ring rules, a {@link RuntimeException} will
* be thrown.
*
* @param outer a LineString which defines the outer perimeter of the polygon
* @param inner one or more LineStrings representing holes inside the outer perimeter
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Polygon fromOuterInner(@NonNull LineString outer, @Nullable LineString... inner) {
isLinearRing(outer);
List<List<Point>> coordinates = new ArrayList<>();
coordinates.add(outer.coordinates());
// If inner rings are set to null, return early.
if (inner == null) {
return new Polygon(TYPE, null, coordinates);
}
for (LineString lineString : inner) {
isLinearRing(lineString);
coordinates.add(lineString.coordinates());
}
return new Polygon(TYPE, null, coordinates);
}
/**
* Create a new instance of this class by passing in an outer {@link LineString} and optionally
* one or more inner LineStrings. Each of these LineStrings should follow the linear ring rules.
* <p>
* Note that if a LineString breaks one of the linear ring rules, a {@link RuntimeException} will
* be thrown.
*
* @param outer a LineString which defines the outer perimeter of the polygon
* @param bbox optionally include a bbox definition as a double array
* @param inner one or more LineStrings representing holes inside the outer perimeter
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Polygon fromOuterInner(@NonNull LineString outer, @Nullable BoundingBox bbox,
@Nullable LineString... inner) {
isLinearRing(outer);
List<List<Point>> coordinates = new ArrayList<>();
coordinates.add(outer.coordinates());
// If inner rings are set to null, return early.
if (inner == null) {
return new Polygon(TYPE, bbox, coordinates);
}
for (LineString lineString : inner) {
isLinearRing(lineString);
coordinates.add(lineString.coordinates());
}
return new Polygon(TYPE, bbox, coordinates);
}
/**
* Create a new instance of this class by passing in an outer {@link LineString} and optionally
* one or more inner LineStrings contained within a list. Each of these LineStrings should follow
* the linear ring rules.
* <p>
* Note that if a LineString breaks one of the linear ring rules, a {@link RuntimeException} will
* be thrown.
*
* @param outer a LineString which defines the outer perimeter of the polygon
* @param inner one or more LineStrings inside a list representing holes inside the outer
* perimeter
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Polygon fromOuterInner(@NonNull LineString outer,
@Nullable @Size(min = 1) List<LineString> inner) {
isLinearRing(outer);
List<List<Point>> coordinates = new ArrayList<>();
coordinates.add(outer.coordinates());
// If inner rings are set to null, return early.
if (inner == null || inner.isEmpty()) {
return new Polygon(TYPE, null, coordinates);
}
for (LineString lineString : inner) {
isLinearRing(lineString);
coordinates.add(lineString.coordinates());
}
return new Polygon(TYPE, null, coordinates);
}
/**
* Create a new instance of this class by passing in an outer {@link LineString} and optionally
* one or more inner LineStrings contained within a list. Each of these LineStrings should follow
* the linear ring rules.
* <p>
* Note that if a LineString breaks one of the linear ring rules, a {@link RuntimeException} will
* be thrown.
*
* @param outer a LineString which defines the outer perimeter of the polygon
* @param bbox optionally include a bbox definition as a double array
* @param inner one or more LineStrings inside a list representing holes inside the outer
* perimeter
* @return a new instance of this class defined by the values passed inside this static factory
* method
*
*/
public static Polygon fromOuterInner(@NonNull LineString outer, @Nullable BoundingBox bbox,
@Nullable @Size(min = 1) List<LineString> inner) {
isLinearRing(outer);
List<List<Point>> coordinates = new ArrayList<>();
coordinates.add(outer.coordinates());
// If inner rings are set to null, return early.
if (inner == null) {
return new Polygon(TYPE, bbox, coordinates);
}
for (LineString lineString : inner) {
isLinearRing(lineString);
coordinates.add(lineString.coordinates());
}
return new Polygon(TYPE, bbox, coordinates);
}
Polygon(String type, @Nullable BoundingBox bbox, List<List<Point>> coordinates) {
if (type == null) {
throw new NullPointerException("Null type");
}
this.type = type;
this.bbox = bbox;
if (coordinates == null) {
throw new NullPointerException("Null coordinates");
}
this.coordinates = coordinates;
}
/**
* Convenience method to get the outer {@link LineString} which defines the outer perimeter of
* the polygon.
*
* @return a {@link LineString} defining the outer perimeter of this polygon
*
*/
@Nullable
public LineString outer() {
return LineString.fromLngLats(coordinates().get(0));
}
/**
* Convenience method to get a list of inner {@link LineString}s defining holes inside the
* polygon. It is not guaranteed that this instance of Polygon contains holes and thus, might
* return a null or empty list.
*
* @return a List of {@link LineString}s defining holes inside the polygon
*
*/
@Nullable
public List<LineString> inner() {
List<List<Point>> coordinates = coordinates();
if (coordinates.size() <= 1) {
return new ArrayList(0);
}
List<LineString> inner = new ArrayList<>(coordinates.size() - 1);
for (List<Point> points : coordinates.subList(1, coordinates.size())) {
inner.add(LineString.fromLngLats(points));
}
return inner;
}
/**
* This describes the TYPE of GeoJson geometry this object is, thus this will always return
* {@link Polygon}.
*
* @return a String which describes the TYPE of geometry, for this object it will always return
* {@code Polygon}
*
*/
@NonNull
@Override
public String type() {
return type;
}
/**
* A Feature Collection 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.
*
* @return a list of double coordinate values describing a bounding box
*
*/
@Nullable
@Override
public BoundingBox bbox() {
return bbox;
}
/**
* Provides the list of {@link Point}s that make up the Polygon geometry. The first list holds the
* different LineStrings, first being the outer ring and the following entries being inner holes
* (if they exist).
*
* @return a list of points
*
*/
@NonNull
@Override
public List<List<Point>> coordinates() {
return coordinates;
}
/**
* This takes the currently defined values found inside this instance and converts it to a GeoJson
* string.
*
* @return a JSON string which represents this Polygon geometry
*
*/
@Override
public String toJson() {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create());
return gson.create().toJson(this);
}
/**
* Gson TYPE adapter for parsing Gson to this class.
*
* @param gson the built {@link Gson} object
* @return the TYPE adapter for this class
*
*/
public static TypeAdapter<Polygon> typeAdapter(Gson gson) {
return new Polygon.GsonTypeAdapter(gson);
}
/**
* Checks to ensure that the LineStrings defining the polygon correctly and adhering to the linear
* ring rules.
*
* @param lineString {@link LineString} the polygon geometry
* @return true if number of coordinates are 4 or more, and first and last coordinates
* are identical, else false
* @throws GeoJsonException if number of coordinates are less than 4,
* or first and last coordinates are not identical
*
*/
private static boolean isLinearRing(LineString lineString) {
if (lineString.coordinates().size() < 4) {
throw new GeoJsonException("LinearRings need to be made up of 4 or more coordinates.");
}
if (!(lineString.coordinates().get(0).equals(
lineString.coordinates().get(lineString.coordinates().size() - 1)))) {
throw new GeoJsonException("LinearRings require first and last coordinate to be identical.");
}
return true;
}
@Override
public String toString() {
return "Polygon{"
+ "type=" + type + ", "
+ "bbox=" + bbox + ", "
+ "coordinates=" + coordinates
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Polygon) {
Polygon that = (Polygon) obj;
return (this.type.equals(that.type()))
&& ((this.bbox == null) ? (that.bbox() == null) : this.bbox.equals(that.bbox()))
&& (this.coordinates.equals(that.coordinates()));
}
return false;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode *= 1000003;
hashCode ^= type.hashCode();
hashCode *= 1000003;
hashCode ^= (bbox == null) ? 0 : bbox.hashCode();
hashCode *= 1000003;
hashCode ^= coordinates.hashCode();
return hashCode;
}
/**
* TypeAdapter for Polygon geometry.
*/
static final class GsonTypeAdapter extends BaseGeometryTypeAdapter<Polygon, List<List<Point>>> {
GsonTypeAdapter(Gson gson) {
super(gson, new ListOfListOfPointCoordinatesTypeAdapter());
}
@Override
public void write(JsonWriter jsonWriter, Polygon object) throws IOException {
writeCoordinateContainer(jsonWriter, object);
}
@Override
public Polygon read(JsonReader jsonReader) throws IOException {
return (Polygon) readCoordinateContainer(jsonReader);
}
@Override
CoordinateContainer<List<List<Point>>> createCoordinateContainer(String type,
BoundingBox bbox,
List<List<Point>> coords) {
return new Polygon(type == null ? "Polygon" : type, bbox, coords);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/package-info.java
|
/**
* Contains the Nbmap Java GeoJson classes.
*/
package ai.nextbillion.kits.geojson;
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/constants/GeoJsonConstants.java
|
package ai.nextbillion.kits.geojson.constants;
/**
* Contains constants used throughout the GeoJson classes.
*/
public final class GeoJsonConstants {
/**
* A Mercator project has a finite longitude values, this constant represents the lowest value
* available to represent a geolocation.
*/
public static final double MIN_LONGITUDE = -180;
/**
* A Mercator project has a finite longitude values, this constant represents the highest value
* available to represent a geolocation.
*/
public static final double MAX_LONGITUDE = 180;
/**
* While on a Mercator projected map the width (longitude) has a finite values, the height
* (latitude) can be infinitely long. This constant restrains the lower latitude value to -90 in
* order to preserve map readability and allows easier logic for tile selection.
*/
public static final double MIN_LATITUDE = -90;
/**
* While on a Mercator projected map the width (longitude) has a finite values, the height
* (latitude) can be infinitely long. This constant restrains the upper latitude value to 90 in
* order to preserve map readability and allows easier logic for tile selection.
*/
public static final double MAX_LATITUDE = 90;
private GeoJsonConstants() {
// Private constructor to prevent initializing of this class.
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/constants/package-info.java
|
/**
* Contains the constants used throughout the GeoJson classes.
*/
package ai.nextbillion.kits.geojson.constants;
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/exception/GeoJsonException.java
|
package ai.nextbillion.kits.geojson.exception;
/**
* A form of {@code Throwable} that indicates an issue occurred during a GeoJSON operation.
*/
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)
*/
public GeoJsonException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/exception/package-info.java
|
/**
* Contains a Runtime Exception specific to GeoJSON issues.
*
*
*/
package ai.nextbillion.kits.geojson.exception;
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/gson/BoundingBoxTypeAdapter.java
|
package ai.nextbillion.kits.geojson.gson;
import androidx.annotation.Keep;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import ai.nextbillion.kits.geojson.BoundingBox;
import ai.nextbillion.kits.geojson.Point;
import ai.nextbillion.kits.geojson.exception.GeoJsonException;
import ai.nextbillion.kits.geojson.shifter.CoordinateShifterManager;
import ai.nextbillion.kits.geojson.utils.GeoJsonUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Adapter to read and write coordinates for BoundingBox class.
*/
@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/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/gson/GeoJsonAdapterFactory.java
|
package ai.nextbillion.kits.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 ai.nextbillion.kits.geojson.BoundingBox;
import ai.nextbillion.kits.geojson.Feature;
import ai.nextbillion.kits.geojson.FeatureCollection;
import ai.nextbillion.kits.geojson.GeometryCollection;
import ai.nextbillion.kits.geojson.LineString;
import ai.nextbillion.kits.geojson.MultiLineString;
import ai.nextbillion.kits.geojson.MultiPoint;
import ai.nextbillion.kits.geojson.MultiPolygon;
import ai.nextbillion.kits.geojson.Point;
import ai.nextbillion.kits.geojson.Polygon;
/**
* A GeoJson type adapter factory for convenience for
* serialization/deserialization.
*/
@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
*/
public static TypeAdapterFactory create() {
return new GeoJsonAdapterFactoryIml();
}
/**
* GeoJsonAdapterFactory implementation.
*
*/
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/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/gson/GeometryGeoJson.java
|
package ai.nextbillion.kits.geojson.gson;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import com.google.gson.GsonBuilder;
import ai.nextbillion.kits.geojson.Geometry;
import ai.nextbillion.kits.geojson.GeometryAdapterFactory;
/**
* This is a utility class that helps create a Geometry instance from a JSON string.
*/
@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
*/
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/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/gson/package-info.java
|
/**
* Contains the Nbmap Java GeoJson GSON helper classes which assist in parsing.
*/
package ai.nextbillion.kits.geojson.gson;
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/shifter/CoordinateShifter.java
|
package ai.nextbillion.kits.geojson.shifter;
import ai.nextbillion.kits.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.
*/
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
*/
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
*/
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
*/
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
*/
List<Double> unshiftPoint(List<Double> shiftedCoordinates);
}
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/shifter/CoordinateShifterManager.java
|
package ai.nextbillion.kits.geojson.shifter;
import ai.nextbillion.kits.geojson.Point;
import java.util.Arrays;
import java.util.List;
/**
* CoordinateShifterManager keeps track of currently set CoordinateShifter.
*/
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
*/
public static CoordinateShifter getCoordinateShifter() {
return coordinateShifter;
}
/**
* Sets CoordinateShifterManager.
*
* @param coordinateShifter CoordinateShifterManager to be set
*/
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/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/shifter/package-info.java
|
/**
* Contains Utility for universally applying a shifting algorithm to all Geometry types.
*/
package ai.nextbillion.kits.geojson.shifter;
|
0
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/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 ai.nextbillion.kits.geojson.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
*/
@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/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/utils/GeoJsonUtils.java
|
package ai.nextbillion.kits.geojson.utils;
/**
* GeoJson utils class contains method that can be used throughout geojson package.
*/
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/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/utils/PolylineUtils.java
|
package ai.nextbillion.kits.geojson.utils;
import androidx.annotation.NonNull;
import ai.nextbillion.kits.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.
*/
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
*/
@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
*/
@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>
*/
@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>
*/
@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>
*/
@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>
*/
@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/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson
|
java-sources/ai/nextbillion/nb-kits-geojson/0.0.2/ai/nextbillion/kits/geojson/utils/package-info.java
|
/**
* Contains Utilities useful for GeoJson translations and formations.
*/
package ai.nextbillion.kits.geojson.utils;
|
0
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfAssertions.java
|
package ai.nextbillion.kits.turf;
import ai.nextbillion.kits.geojson.Feature;
import ai.nextbillion.kits.geojson.FeatureCollection;
import ai.nextbillion.kits.geojson.GeoJson;
import ai.nextbillion.kits.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>
*
*/
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>
*
* @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>
*
*/
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>
*
*/
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>
*
*/
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/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfClassification.java
|
package ai.nextbillion.kits.turf;
import androidx.annotation.NonNull;
import ai.nextbillion.kits.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.
*
*
*/
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
*
*/
@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/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfConstants.java
|
package ai.nextbillion.kits.turf;
import androidx.annotation.StringDef;
import ai.nextbillion.kits.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>
*
*/
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.
*
*
*/
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.
*
*
*/
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>
*
*
*/
public static final String UNIT_KILOMETERS = "kilometers";
/**
* The radian is the standard unit of angular measure, used in many areas of mathematics.
*
*
*/
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.
*
*
*/
public static final String UNIT_DEGREES = "degrees";
/**
* The inch (abbreviation: in or ") 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.
*
*
*/
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.
*
*
*/
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).
*
*
*/
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.
*
*
*/
public static final String UNIT_CENTIMETERS = "centimeters";
/**
* The foot is a unit of length in the imperial and US customary systems of measurement.
*
*
*/
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.
*
*
*/
public static final String UNIT_CENTIMETRES = "centimetres";
/**
* The metre (international spelling) is the base unit of length in
* the International System of Units (SI).
*
*
*/
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.
*
*
*/
public static final String UNIT_KILOMETRES = "kilometres";
/**
* Retention policy for the various Turf units.
*
*
*/
@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.
*
*
*/
public static final String UNIT_DEFAULT = UNIT_KILOMETERS;
}
|
0
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfConversion.java
|
package ai.nextbillion.kits.turf;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.JsonObject;
import ai.nextbillion.kits.geojson.Feature;
import ai.nextbillion.kits.geojson.FeatureCollection;
import ai.nextbillion.kits.geojson.Geometry;
import ai.nextbillion.kits.geojson.LineString;
import ai.nextbillion.kits.geojson.MultiLineString;
import ai.nextbillion.kits.geojson.MultiPoint;
import ai.nextbillion.kits.geojson.MultiPolygon;
import ai.nextbillion.kits.geojson.Point;
import ai.nextbillion.kits.geojson.Polygon;
import ai.nextbillion.kits.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>
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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}
*
*/
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}
*
*/
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}
*
*/
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}
*
*/
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}
*
*/
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}
*
*/
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}
*
*/
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}
*
*/
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.
*
*
**/
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/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfException.java
|
package ai.nextbillion.kits.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>
*
*/
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).
*
*/
public TurfException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfJoins.java
|
package ai.nextbillion.kits.turf;
import ai.nextbillion.kits.geojson.Feature;
import ai.nextbillion.kits.geojson.FeatureCollection;
import ai.nextbillion.kits.geojson.Point;
import ai.nextbillion.kits.geojson.Polygon;
import ai.nextbillion.kits.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>
*
*/
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>
*
*/
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>
*
*/
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.
*
*/
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/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfMeasurement.java
|
package ai.nextbillion.kits.turf;
import static ai.nextbillion.kits.turf.TurfConversion.degreesToRadians;
import static ai.nextbillion.kits.turf.TurfConversion.radiansToDegrees;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.JsonObject;
import ai.nextbillion.kits.geojson.BoundingBox;
import ai.nextbillion.kits.geojson.Feature;
import ai.nextbillion.kits.geojson.FeatureCollection;
import ai.nextbillion.kits.geojson.GeoJson;
import ai.nextbillion.kits.geojson.Geometry;
import ai.nextbillion.kits.geojson.GeometryCollection;
import ai.nextbillion.kits.geojson.LineString;
import ai.nextbillion.kits.geojson.MultiLineString;
import ai.nextbillion.kits.geojson.MultiPoint;
import ai.nextbillion.kits.geojson.MultiPolygon;
import ai.nextbillion.kits.geojson.Point;
import ai.nextbillion.kits.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>
*
*/
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>
*
*/
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>
*
*/
@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>
*
*/
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>
*
*/
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>
*
*/
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>
*
*/
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>
*
*/
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>
*
*/
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>
*
*/
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>
*
*/
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
*
*/
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
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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]}
*
*/
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>
*
*/
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>
*
*/
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>
*
*/
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>
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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.
*
*/
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.
*
*/
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.
*
*/
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.
*
*/
public static Feature center(FeatureCollection featureCollection) {
return center(featureCollection, null, null);
}
}
|
0
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfMeta.java
|
package ai.nextbillion.kits.turf;
import androidx.annotation.NonNull;
import ai.nextbillion.kits.geojson.Feature;
import ai.nextbillion.kits.geojson.FeatureCollection;
import ai.nextbillion.kits.geojson.Geometry;
import ai.nextbillion.kits.geojson.GeometryCollection;
import ai.nextbillion.kits.geojson.LineString;
import ai.nextbillion.kits.geojson.MultiLineString;
import ai.nextbillion.kits.geojson.MultiPoint;
import ai.nextbillion.kits.geojson.MultiPolygon;
import ai.nextbillion.kits.geojson.Point;
import ai.nextbillion.kits.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>
*
*/
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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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
*
*/
@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.
*
*/
@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
*
*/
@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>
*
*/
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/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfMisc.java
|
package ai.nextbillion.kits.turf;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import ai.nextbillion.kits.geojson.Feature;
import ai.nextbillion.kits.geojson.LineString;
import ai.nextbillion.kits.geojson.Point;
import ai.nextbillion.kits.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>
*
*/
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>
*
*/
@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>
*
*/
@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>
*
*/
@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>
*
*/
@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
*
*/
@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
*
*/
@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/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/TurfTransformation.java
|
package ai.nextbillion.kits.turf;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import ai.nextbillion.kits.geojson.Polygon;
import ai.nextbillion.kits.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.
*
*
*/
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
*
*/
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
*
*/
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
*
*/
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/nb-kits-turf/0.0.2/ai/nextbillion/kits
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/package-info.java
|
/**
* Contains the Nbmap Java Services Turf methods.
*
*
*/
package ai.nextbillion.kits.turf;
|
0
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/models/LineIntersectsResult.java
|
package ai.nextbillion.kits.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>
*
*/
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
*
*/
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
*
*/
@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
*
*/
@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
*
*/
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
*
*/
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
*
*/
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.
*
*
*/
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
*
*/
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
*
*/
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
*
*/
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
*
*/
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}
*
*/
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/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf
|
java-sources/ai/nextbillion/nb-kits-turf/0.0.2/ai/nextbillion/kits/turf/models/package-info.java
|
/**
* Contains the Nbmap Java Services classes.
*/
package ai.nextbillion.kits.turf.models;
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/DirectionsApi.java
|
package ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.DirectionsResult;
import ai.nextbillion.maps.model.DirectionsRoute;
import ai.nextbillion.maps.model.LatLng;
public class DirectionsApi {
static final ApiConfig API_CONFIG = new ApiConfig("/directions/json");
private DirectionsApi() {}
public static DirectionsApiRequest newRequest(GeoApiContext context) {
return new DirectionsApiRequest(context);
}
public static DirectionsApiRequest getDirections(
GeoApiContext context, LatLng origin, LatLng destination) {
return new DirectionsApiRequest(context).origin(origin).destination(destination);
}
public static class Response implements ApiResponse<DirectionsResult> {
public String status;
public String errorMessage;
public DirectionsRoute[] routes;
@Override
public boolean successful() {
return "Ok".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public DirectionsResult getResult() {
DirectionsResult result = new DirectionsResult();
result.routes = routes;
return result;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
public enum RouteRestriction implements StringJoin.UrlValue {
/** Indicates that the calculated route should avoid toll roads/bridges. */
TOLLS("tolls"),
/** Indicates that the calculated route should avoid highways. */
HIGHWAYS("highways"),
/** Indicates that the calculated route should avoid ferries. */
FERRIES("ferries");
private final String restriction;
RouteRestriction(String restriction) {
this.restriction = restriction;
}
@Override
public String toString() {
return restriction;
}
@Override
public String toUrlValue() {
return restriction;
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/DirectionsApiRequest.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import static java.util.Objects.requireNonNull;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.DirectionsResult;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.TrafficModel;
import ai.nextbillion.maps.model.TransitMode;
import ai.nextbillion.maps.model.TransitRoutingPreference;
import ai.nextbillion.maps.model.TravelMode;
import ai.nextbillion.maps.model.Unit;
import java.time.Instant;
/** Request for the Directions API. */
public class DirectionsApiRequest
extends PendingResultBase<DirectionsResult, DirectionsApiRequest, DirectionsApi.Response> {
public DirectionsApiRequest(GeoApiContext context) {
super(context, DirectionsApi.API_CONFIG, DirectionsApi.Response.class);
}
protected boolean optimizeWaypoints;
protected Waypoint[] waypoints;
@Override
protected void validateRequest() {
if (!params().containsKey("origin")) {
throw new IllegalArgumentException("Request must contain 'origin'");
}
if (!params().containsKey("destination")) {
throw new IllegalArgumentException("Request must contain 'destination'");
}
if (params().containsKey("arrival_time") && params().containsKey("departure_time")) {
throw new IllegalArgumentException(
"Transit request must not contain both a departureTime and an arrivalTime");
}
if (params().containsKey("traffic_model") && !params().containsKey("departure_time")) {
throw new IllegalArgumentException(
"Specifying a traffic model requires that departure time be provided.");
}
}
/**
* The Place ID value from which you wish to calculate directions.
*
* @param originPlaceId The starting location Place ID for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest originPlaceId(String originPlaceId) {
return param("origin", prefixPlaceId(originPlaceId));
}
/**
* The Place ID value from which you wish to calculate directions.
*
* @param destinationPlaceId The ending location Place ID for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest destinationPlaceId(String destinationPlaceId) {
return param("destination", prefixPlaceId(destinationPlaceId));
}
/**
* The origin, as a latitude/longitude location.
*
* @param origin The starting location for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest origin(LatLng origin) {
return param("origin", origin);
}
/**
* The destination, as a latitude/longitude location.
*
* @param destination The ending location for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest destination(LatLng destination) {
return param("destination", destination);
}
/**
* Specifies the mode of transport to use when calculating directions. The mode defaults to
* driving if left unspecified. If you set the mode to {@code TRANSIT} you must also specify
* either a {@code departureTime} or an {@code arrivalTime}.
*
* @param mode The travel mode to request directions for.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest mode(TravelMode mode) {
return param("mode", mode);
}
/**
* Indicates that the calculated route(s) should avoid the indicated features.
*
* @param restrictions one or more of {@link DirectionsApi.RouteRestriction#TOLLS}, {@link
* DirectionsApi.RouteRestriction#HIGHWAYS}, {@link DirectionsApi.RouteRestriction#FERRIES}
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest avoid(DirectionsApi.RouteRestriction... restrictions) {
return param("avoid", StringJoin.join('|', restrictions));
}
/**
* Specifies the unit system to use when displaying results.
*
* @param units The preferred units for displaying distances.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest units(Unit units) {
return param("units", units);
}
/**
* @param region The region code, specified as a ccTLD ("top-level domain") two-character value.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest region(String region) {
return param("region", region);
}
/**
* Set the arrival time for a Transit directions request.
*
* @param time The arrival time to calculate directions for.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest arrivalTime(Instant time) {
return param("arrival_time", Long.toString(time.toEpochMilli() / 1000L));
}
/**
* Set the departure time for a transit or driving directions request. If both departure time and
* traffic model are not provided, then "now" is assumed. If traffic model is supplied, then
* departure time must be specified. Duration in traffic will only be returned if the departure
* time is specified.
*
* @param time The departure time to calculate directions for.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest departureTime(Instant time) {
return param("departure_time", Long.toString(time.toEpochMilli() / 1000L));
}
/**
* Set the departure time for a transit or driving directions request as the current time. If
* traffic model is supplied, then departure time must be specified. Duration in traffic will only
* be returned if the departure time is specified.
*
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest departureTimeNow() {
return param("departure_time", "now");
}
/**
* Specifies a list of waypoints. Waypoints alter a route by routing it through the specified
* location(s). A waypoint is specified as either a latitude/longitude coordinate or as an address
* which will be geocoded. Waypoints are only supported for driving, walking and bicycling
* directions.
*
* <p>For more information on waypoints, see <a
* href="https://developers.google.com/maps/documentation/directions/intro#Waypoints">Using
* Waypoints in Routes</a>.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest waypoints(Waypoint... waypoints) {
if (waypoints == null || waypoints.length == 0) {
this.waypoints = new Waypoint[0];
param("waypoints", "");
return this;
} else {
this.waypoints = waypoints;
String[] waypointStrs = new String[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
waypointStrs[i] = waypoints[i].toString();
}
param(
"waypoints",
(optimizeWaypoints ? "optimize:true|" : "") + StringJoin.join('|', waypointStrs));
return this;
}
}
/**
* Specifies the list of waypoints as String addresses. If any of the Strings are Place IDs, you
* must prefix them with {@code place_id:}.
*
* <p>See {@link #prefixPlaceId(String)}.
*
* <p>See {@link #waypoints(Waypoint...)}.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest waypoints(String... waypoints) {
Waypoint[] objWaypoints = new Waypoint[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
objWaypoints[i] = new Waypoint(waypoints[i]);
}
return waypoints(objWaypoints);
}
/**
* Specifies the list of waypoints as Plade ID Strings, prefixing them as required by the API.
*
* <p>See {@link #prefixPlaceId(String)}.
*
* <p>See {@link #waypoints(Waypoint...)}.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest waypointsFromPlaceIds(String... waypoints) {
Waypoint[] objWaypoints = new Waypoint[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
objWaypoints[i] = new Waypoint(prefixPlaceId(waypoints[i]));
}
return waypoints(objWaypoints);
}
/**
* The list of waypoints as latitude/longitude locations.
*
* <p>See {@link #waypoints(Waypoint...)}.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest waypoints(LatLng... waypoints) {
Waypoint[] objWaypoints = new Waypoint[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
objWaypoints[i] = new Waypoint(waypoints[i]);
}
return waypoints(objWaypoints);
}
/**
* Allow the Directions service to optimize the provided route by rearranging the waypoints in a
* more efficient order.
*
* @param optimize Whether to optimize waypoints.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest optimizeWaypoints(boolean optimize) {
optimizeWaypoints = optimize;
if (waypoints != null) {
return waypoints(waypoints);
} else {
return this;
}
}
/**
* If set to true, specifies that the Directions service may provide more than one route
* alternative in the response. Note that providing route alternatives may increase the response
* time from the server.
*
* @param alternateRoutes whether to return alternate routes.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsApiRequest alternatives(boolean alternateRoutes) {
if (alternateRoutes) {
return param("alternatives", "true");
} else {
return param("alternatives", "false");
}
}
public DirectionsApiRequest steps(boolean steps) {
return param("steps", steps ? "true" : "false");
}
public DirectionsApiRequest session(String session) {
return param("session", session);
}
public DirectionsApiRequest context(String context) {
return param("context", context);
}
public DirectionsApiRequest transitMode(TransitMode... transitModes) {
return param("transit_mode", StringJoin.join('|', transitModes));
}
public DirectionsApiRequest transitRoutingPreference(TransitRoutingPreference pref) {
return param("transit_routing_preference", pref);
}
public DirectionsApiRequest trafficModel(TrafficModel trafficModel) {
return param("traffic_model", trafficModel);
}
public String prefixPlaceId(String placeId) {
return "place_id:" + placeId;
}
public static class Waypoint {
/** The location of this waypoint, expressed as an API-recognized location. */
private final String location;
/** Whether this waypoint is a stopover waypoint. */
private final boolean isStopover;
/**
* Constructs a stopover Waypoint using a String address.
*
* @param location Any address or location recognized by the Google Maps API.
*/
public Waypoint(String location) {
this(location, true);
}
/**
* Constructs a Waypoint using a String address.
*
* @param location Any address or location recognized by the Google Maps API.
* @param isStopover Whether this waypoint is a stopover waypoint.
*/
public Waypoint(String location, boolean isStopover) {
requireNonNull(location, "address may not be null");
this.location = location;
this.isStopover = isStopover;
}
/**
* Constructs a stopover Waypoint using a Latlng location.
*
* @param location The LatLng coordinates of this waypoint.
*/
public Waypoint(LatLng location) {
this(location, true);
}
/**
* Constructs a Waypoint using a LatLng location.
*
* @param location The LatLng coordinates of this waypoint.
* @param isStopover Whether this waypoint is a stopover waypoint.
*/
public Waypoint(LatLng location, boolean isStopover) {
requireNonNull(location, "location may not be null");
this.location = location.toString();
this.isStopover = isStopover;
}
/**
* Gets the String representation of this Waypoint, as an API request parameter fragment.
*
* @return The HTTP parameter fragment representing this waypoint.
*/
@Override
public String toString() {
if (isStopover) {
return location;
} else {
return "via:" + location;
}
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/DirectionsTableApi.java
|
package ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.DirectionsRoute;
import ai.nextbillion.maps.model.LatLng;
import java.util.HashMap;
import java.util.Map;
public class DirectionsTableApi {
static final ApiConfig API_CONFIG = new ApiConfig("/directions-table/json");
private DirectionsTableApi() {}
public static DirectionsTableApiRequest newRequest(GeoApiContext context) {
return new DirectionsTableApiRequest(context);
}
public static DirectionsTableApiRequest getDirections(
GeoApiContext context, LatLng origin, LatLng destination) {
return new DirectionsTableApiRequest(context).origin(origin).destination(destination);
}
public static class DirectionsTableEntry {
public String status;
public String reason;
public String mode;
public DirectionsRoute[] routes;
}
public static class Response implements ApiResponse<Map<String, DirectionsTableEntry>> {
public String status;
public String errorMessage;
public Map<String, DirectionsTableEntry> results = new HashMap<String, DirectionsTableEntry>();
@Override
public boolean successful() {
return "Ok".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public Map<String, DirectionsTableEntry> getResult() {
return this.results;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/DirectionsTableApiRequest.java
|
package ai.nextbillion.maps;
import static java.util.Objects.requireNonNull;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.*;
import java.time.Instant;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
/** Request for the Directions API. */
public class DirectionsTableApiRequest
extends PendingResultBase<Map<String, DirectionsTableApi.DirectionsTableEntry>, DirectionsTableApiRequest, DirectionsTableApi.Response> {
public DirectionsTableApiRequest(GeoApiContext context) {
super(context, DirectionsTableApi.API_CONFIG, DirectionsTableApi.Response.class);
}
protected boolean optimizeWaypoints;
protected Waypoint[] waypoints;
@Override
protected void validateRequest() {
if (!params().containsKey("origin")) {
throw new IllegalArgumentException("Request must contain 'origin'");
}
if (!params().containsKey("destination")) {
throw new IllegalArgumentException("Request must contain 'destination'");
}
if (params().containsKey("arrival_time") && params().containsKey("departure_time")) {
throw new IllegalArgumentException(
"Transit request must not contain both a departureTime and an arrivalTime");
}
if (params().containsKey("traffic_model") && !params().containsKey("departure_time")) {
throw new IllegalArgumentException(
"Specifying a traffic model requires that departure time be provided.");
}
}
/**
* The Place ID value from which you wish to calculate directions.
*
* @param originPlaceId The starting location Place ID for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest originPlaceId(String originPlaceId) {
return param("origin", prefixPlaceId(originPlaceId));
}
/**
* The Place ID value from which you wish to calculate directions.
*
* @param destinationPlaceId The ending location Place ID for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest destinationPlaceId(String destinationPlaceId) {
return param("destination", prefixPlaceId(destinationPlaceId));
}
/**
* The origin, as a latitude/longitude location.
*
* @param origin The starting location for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest origin(LatLng origin) {
return param("origin", origin);
}
/**
* The destination, as a latitude/longitude location.
*
* @param destination The ending location for the Directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest destination(LatLng destination) {
return param("destination", destination);
}
/**
* Specifies the mode of transport to use when calculating directions. The mode defaults to
* driving if left unspecified. If you set the mode to {@code TRANSIT} you must also specify
* either a {@code departureTime} or an {@code arrivalTime}.
*
* @param mode The travel mode to request directions for.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest mode(String mode) {
return param("mode", mode);
}
/**
* Indicates that the calculated route(s) should avoid the indicated features.
*
* @param restrictions one or more of {@link DirectionsApi.RouteRestriction#TOLLS}, {@link
* DirectionsApi.RouteRestriction#HIGHWAYS}, {@link DirectionsApi.RouteRestriction#FERRIES}
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest avoid(DirectionsApi.RouteRestriction... restrictions) {
return param("avoid", StringJoin.join('|', restrictions));
}
/**
* Specifies the unit system to use when displaying results.
*
* @param units The preferred units for displaying distances.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest units(Unit units) {
return param("units", units);
}
/**
* @param region The region code, specified as a ccTLD ("top-level domain") two-character value.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest region(String region) {
return param("region", region);
}
/**
* Set the arrival time for a Transit directions request.
*
* @param time The arrival time to calculate directions for.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest arrivalTime(Instant time) {
return param("arrival_time", Long.toString(time.toEpochMilli() / 1000L));
}
/**
* Set the departure time for a transit or driving directions request. If both departure time and
* traffic model are not provided, then "now" is assumed. If traffic model is supplied, then
* departure time must be specified. Duration in traffic will only be returned if the departure
* time is specified.
*
* @param time The departure time to calculate directions for.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest departureTime(Instant time) {
return param("departure_time", Long.toString(time.toEpochMilli() / 1000L));
}
/**
* Set the departure time for a transit or driving directions request as the current time. If
* traffic model is supplied, then departure time must be specified. Duration in traffic will only
* be returned if the departure time is specified.
*
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest departureTimeNow() {
return param("departure_time", "now");
}
/**
* Specifies a list of waypoints. Waypoints alter a route by routing it through the specified
* location(s). A waypoint is specified as either a latitude/longitude coordinate or as an address
* which will be geocoded. Waypoints are only supported for driving, walking and bicycling
* directions.
*
* <p>For more information on waypoints, see <a
* href="https://developers.google.com/maps/documentation/directions/intro#Waypoints">Using
* Waypoints in Routes</a>.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest waypoints(Waypoint... waypoints) {
if (waypoints == null || waypoints.length == 0) {
this.waypoints = new Waypoint[0];
param("waypoints", "");
return this;
} else {
this.waypoints = waypoints;
String[] waypointStrs = new String[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
waypointStrs[i] = waypoints[i].toString();
}
param(
"waypoints",
(optimizeWaypoints ? "optimize:true|" : "") + StringJoin.join('|', waypointStrs));
return this;
}
}
/**
* Specifies the list of waypoints as String addresses. If any of the Strings are Place IDs, you
* must prefix them with {@code place_id:}.
*
* <p>See {@link #prefixPlaceId(String)}.
*
* <p>See {@link #waypoints(Waypoint...)}.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest waypoints(String... waypoints) {
Waypoint[] objWaypoints = new Waypoint[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
objWaypoints[i] = new Waypoint(waypoints[i]);
}
return waypoints(objWaypoints);
}
/**
* Specifies the list of waypoints as Plade ID Strings, prefixing them as required by the API.
*
* <p>See {@link #prefixPlaceId(String)}.
*
* <p>See {@link #waypoints(Waypoint...)}.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest waypointsFromPlaceIds(String... waypoints) {
Waypoint[] objWaypoints = new Waypoint[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
objWaypoints[i] = new Waypoint(prefixPlaceId(waypoints[i]));
}
return waypoints(objWaypoints);
}
/**
* The list of waypoints as latitude/longitude locations.
*
* <p>See {@link #waypoints(Waypoint...)}.
*
* @param waypoints The waypoints to add to this directions request.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest waypoints(LatLng... waypoints) {
Waypoint[] objWaypoints = new Waypoint[waypoints.length];
for (int i = 0; i < waypoints.length; i++) {
objWaypoints[i] = new Waypoint(waypoints[i]);
}
return waypoints(objWaypoints);
}
/**
* Allow the Directions service to optimize the provided route by rearranging the waypoints in a
* more efficient order.
*
* @param optimize Whether to optimize waypoints.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest optimizeWaypoints(boolean optimize) {
optimizeWaypoints = optimize;
if (waypoints != null) {
return waypoints(waypoints);
} else {
return this;
}
}
/**
* If set to true, specifies that the Directions service may provide more than one route
* alternative in the response. Note that providing route alternatives may increase the response
* time from the server.
*
* @param alternateRoutes whether to return alternate routes.
* @return Returns this {@code DirectionsApiRequest} for call chaining.
*/
public DirectionsTableApiRequest alternatives(boolean alternateRoutes) {
if (alternateRoutes) {
return param("alternatives", "true");
} else {
return param("alternatives", "false");
}
}
public DirectionsTableApiRequest steps(boolean steps) {
return param("steps", steps ? "true" : "false");
}
public DirectionsTableApiRequest context(String context) {
return param("context", context);
}
public DirectionsTableApiRequest transitMode(TransitMode... transitModes) {
return param("transit_mode", StringJoin.join('|', transitModes));
}
public DirectionsTableApiRequest transitRoutingPreference(TransitRoutingPreference pref) {
return param("transit_routing_preference", pref);
}
public DirectionsTableApiRequest trafficModel(TrafficModel trafficModel) {
return param("traffic_model", trafficModel);
}
public String prefixPlaceId(String placeId) {
return "place_id:" + placeId;
}
public static class Waypoint {
/** The location of this waypoint, expressed as an API-recognized location. */
private final String location;
/** Whether this waypoint is a stopover waypoint. */
private final boolean isStopover;
/**
* Constructs a stopover Waypoint using a String address.
*
* @param location Any address or location recognized by the Google Maps API.
*/
public Waypoint(String location) {
this(location, true);
}
/**
* Constructs a Waypoint using a String address.
*
* @param location Any address or location recognized by the Google Maps API.
* @param isStopover Whether this waypoint is a stopover waypoint.
*/
public Waypoint(String location, boolean isStopover) {
requireNonNull(location, "address may not be null");
this.location = location;
this.isStopover = isStopover;
}
/**
* Constructs a stopover Waypoint using a Latlng location.
*
* @param location The LatLng coordinates of this waypoint.
*/
public Waypoint(LatLng location) {
this(location, true);
}
/**
* Constructs a Waypoint using a LatLng location.
*
* @param location The LatLng coordinates of this waypoint.
* @param isStopover Whether this waypoint is a stopover waypoint.
*/
public Waypoint(LatLng location, boolean isStopover) {
requireNonNull(location, "location may not be null");
this.location = location.toString();
this.isStopover = isStopover;
}
/**
* Gets the String representation of this Waypoint, as an API request parameter fragment.
*
* @return The HTTP parameter fragment representing this waypoint.
*/
@Override
public String toString() {
if (isStopover) {
return location;
} else {
return "via:" + location;
}
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/DistanceMatrixApi.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.model.DistanceMatrix;
import ai.nextbillion.maps.model.DistanceMatrixRow;
import ai.nextbillion.maps.model.LatLng;
/**
* The Google Distance Matrix API is a service that provides travel distance and time for a matrix
* of origins and destinations. The information returned is based on the recommended route between
* start and end points, as calculated by the Google Maps API, and consists of rows containing
* duration and distance values for each pair.
*
* <p>This service does not return detailed route information. Route information can be obtained by
* passing the desired single origin and destination to the Directions API, using {@link
* DirectionsApi}.
*
* <p><strong>Note:</strong> You can display Distance Matrix API results on a Google Map, or without
* a map. If you want to display Distance Matrix API results on a map, then these results must be
* displayed on a Google Map. It is prohibited to use Distance Matrix API data on a map that is not
* a Google map.
*
* @see <a href="https://developers.google.com/maps/documentation/distancematrix/">Distance Matrix
* API Documentation</a>
*/
public class DistanceMatrixApi {
static final ApiConfig API_CONFIG = new ApiConfig("/distancematrix/json");
private DistanceMatrixApi() {}
public static DistanceMatrixApiRequest newRequest(GeoApiContext context) {
return new DistanceMatrixApiRequest(context);
}
public static DistanceMatrixApiRequest getDistanceMatrix(
GeoApiContext context, LatLng[] origins, LatLng[] destinations) {
return newRequest(context).origins(origins).destinations(destinations);
}
public static class Response implements ApiResponse<DistanceMatrix> {
public String status;
public String errorMessage;
public DistanceMatrixRow[] rows;
@Override
public boolean successful() {
return "Ok".equals(status);
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
@Override
public DistanceMatrix getResult() {
return new DistanceMatrix(rows);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/DistanceMatrixApiRequest.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.DirectionsApi.RouteRestriction;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.DistanceMatrix;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.TrafficModel;
import ai.nextbillion.maps.model.TransitMode;
import ai.nextbillion.maps.model.TransitRoutingPreference;
import ai.nextbillion.maps.model.TravelMode;
import ai.nextbillion.maps.model.Unit;
import java.time.Instant;
/** A request to the Distance Matrix API. */
public class DistanceMatrixApiRequest
extends PendingResultBase<
DistanceMatrix, DistanceMatrixApiRequest, DistanceMatrixApi.Response> {
public DistanceMatrixApiRequest(GeoApiContext context) {
super(context, DistanceMatrixApi.API_CONFIG, DistanceMatrixApi.Response.class);
}
@Override
protected void validateRequest() {
if (!params().containsKey("origins")) {
throw new IllegalArgumentException("Request must contain 'origins'");
}
if (!params().containsKey("destinations")) {
throw new IllegalArgumentException("Request must contain 'destinations'");
}
if (params().containsKey("arrival_time") && params().containsKey("departure_time")) {
throw new IllegalArgumentException(
"Transit request must not contain both a departureTime and an arrivalTime");
}
}
/**
* One or more addresses from which to calculate distance and time. The service will geocode the
* strings and convert them to latitude/longitude coordinates to calculate directions.
*
* @param origins Strings to geocode and use as an origin point (e.g. "New York, NY")
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest origins(String... origins) {
return param("origins", StringJoin.join('|', origins));
}
/**
* One or more latitude/longitude values from which to calculate distance and time.
*
* @param points The origin points.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest origins(LatLng... points) {
return param("origins", StringJoin.join('|', points));
}
/**
* One or more addresses to which to calculate distance and time. The service will geocode the
* strings and convert them to latitude/longitude coordinates to calculate directions.
*
* @param destinations Strings to geocode and use as a destination point (e.g. "Jersey City, NJ")
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest destinations(String... destinations) {
return param("destinations", StringJoin.join('|', destinations));
}
/**
* One or more latitude/longitude values to which to calculate distance and time.
*
* @param points The destination points.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest destinations(LatLng... points) {
return param("destinations", StringJoin.join('|', points));
}
/**
* Specifies the mode of transport to use when calculating directions.
*
* <p>Note that Distance Matrix requests only support {@link TravelMode#DRIVING}, {@link
* TravelMode#WALKING} and {@link TravelMode#BICYCLING}.
*
* @param mode One of the travel modes supported by the Distance Matrix API.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest mode(TravelMode mode) {
if (TravelMode.DRIVING.equals(mode)
|| TravelMode.WALKING.equals(mode)
|| TravelMode.BICYCLING.equals(mode)
|| TravelMode.TRANSIT.equals(mode)) {
return param("mode", mode);
}
throw new IllegalArgumentException(
"Distance Matrix API travel modes must be Driving, Transit, Walking or Bicycling");
}
/**
* Introduces restrictions to the route. Only one restriction can be specified.
*
* @param restriction One of {@link RouteRestriction#TOLLS}, {@link RouteRestriction#FERRIES} or
* {@link RouteRestriction#HIGHWAYS}.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest avoid(RouteRestriction restriction) {
return param("avoid", restriction);
}
/**
* Specifies the unit system to use when expressing distance as text. Distance Matrix results
* contain text within distance fields to indicate the distance of the calculated route.
*
* @param unit One of {@link Unit#METRIC} or {@link Unit#IMPERIAL}.
* @see <a
* href="https://developers.google.com/maps/documentation/distance-matrix/intro#unit_systems">
* Unit systems in the Distance Matrix API</a>
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest units(Unit unit) {
return param("units", unit);
}
/**
* Specifies the desired time of departure.
*
* <p>The departure time may be specified in two cases:
*
* <ul>
* <li>For requests where the travel mode is transit: You can optionally specify one of
* departure_time or arrival_time. If neither time is specified, the departure_time defaults
* to now. (That is, the departure time defaults to the current time.)
* <li>For requests where the travel mode is driving: Google Maps API for Work customers can
* specify the departure_time to receive trip duration considering current traffic
* conditions. The departure_time must be set to within a few minutes of the current time.
* </ul>
*
* <p>Setting the parameter to null will remove it from the API request.
*
* @param departureTime The time of departure.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest departureTime(Instant departureTime) {
return param("departure_time", Long.toString(departureTime.toEpochMilli() / 1000L));
}
/**
* Specifies the assumptions to use when calculating time in traffic. This parameter may only be
* specified when the travel mode is driving and the request includes a departure_time.
*
* @param trafficModel The traffic model to use in estimating time in traffic.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest trafficModel(TrafficModel trafficModel) {
return param("traffic_model", trafficModel);
}
/**
* Specifies the desired time of arrival for transit requests. You can specify either
* departure_time or arrival_time, but not both.
*
* @param arrivalTime The preferred arrival time.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest arrivalTime(Instant arrivalTime) {
return param("arrival_time", Long.toString(arrivalTime.toEpochMilli() / 1000L));
}
/**
* Specifies one or more preferred modes of transit. This parameter may only be specified for
* requests where the mode is transit.
*
* @param transitModes The preferred transit modes.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest transitModes(TransitMode... transitModes) {
return param("transit_mode", StringJoin.join('|', transitModes));
}
/**
* Specifies preferences for transit requests. Using this parameter, you can bias the options
* returned, rather than accepting the default best route chosen by the API.
*
* @param pref The transit routing preference for this distance matrix.
* @return Returns this {@code DistanceMatrixApiRequest} for call chaining.
*/
public DistanceMatrixApiRequest transitRoutingPreference(TransitRoutingPreference pref) {
return param("transit_routing_preference", pref);
}
public DistanceMatrixApiRequest context(String context) {
return param("context", context);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/FindPlaceFromTextRequest.java
|
/*
* Copyright 2018 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.FindPlaceFromText;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.PlacesSearchResult;
import com.google.gson.FieldNamingPolicy;
public class FindPlaceFromTextRequest
extends PendingResultBase<
FindPlaceFromText, FindPlaceFromTextRequest, FindPlaceFromTextRequest.Response> {
static final ApiConfig API_CONFIG =
new ApiConfig("/maps/api/place/findplacefromtext/json")
.fieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.supportsClientId(false);
public FindPlaceFromTextRequest(GeoApiContext context) {
super(context, API_CONFIG, Response.class);
}
public enum InputType implements StringJoin.UrlValue {
TEXT_QUERY("textquery"),
PHONE_NUMBER("phonenumber");
private final String inputType;
InputType(final String inputType) {
this.inputType = inputType;
}
@Override
public String toUrlValue() {
return this.inputType;
}
}
/**
* The text input specifying which place to search for (for example, a name, address, or phone
* number).
*
* @param input The text input.
* @return Returns {@code FindPlaceFromTextRequest} for call chaining.
*/
public FindPlaceFromTextRequest input(String input) {
return param("input", input);
}
/**
* The type of input.
*
* @param inputType The input type.
* @return Returns {@code FindPlaceFromTextRequest} for call chaining.
*/
public FindPlaceFromTextRequest inputType(InputType inputType) {
return param("inputtype", inputType);
}
/**
* The fields specifying the types of place data to return.
*
* @param fields The fields to return.
* @return Returns {@code FindPlaceFromTextRequest} for call chaining.
*/
public FindPlaceFromTextRequest fields(FieldMask... fields) {
return param("fields", StringJoin.join(',', fields));
}
/**
* Prefer results in a specified area, by specifying either a radius plus lat/lng, or two lat/lng
* pairs representing the points of a rectangle.
*
* @param locationBias The location bias for this request.
* @return Returns {@code FindPlaceFromTextRequest} for call chaining.
*/
public FindPlaceFromTextRequest locationBias(LocationBias locationBias) {
return param("locationbias", locationBias);
}
@Override
protected void validateRequest() {
if (!params().containsKey("input")) {
throw new IllegalArgumentException("Request must contain 'input'.");
}
if (!params().containsKey("inputtype")) {
throw new IllegalArgumentException("Request must contain 'inputType'.");
}
}
public static class Response implements ApiResponse<FindPlaceFromText> {
public String status;
public PlacesSearchResult[] candidates;
public String errorMessage;
@Override
public boolean successful() {
return "OK".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public FindPlaceFromText getResult() {
FindPlaceFromText result = new FindPlaceFromText();
result.candidates = candidates;
return result;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
public enum FieldMask implements StringJoin.UrlValue {
BUSINESS_STATUS("business_status"),
FORMATTED_ADDRESS("formatted_address"),
GEOMETRY("geometry"),
ICON("icon"),
ID("id"),
NAME("name"),
OPENING_HOURS("opening_hours"),
@Deprecated
PERMANENTLY_CLOSED("permanently_closed"),
PHOTOS("photos"),
PLACE_ID("place_id"),
PRICE_LEVEL("price_level"),
RATING("rating"),
TYPES("types");
private final String field;
FieldMask(final String field) {
this.field = field;
}
@Override
public String toUrlValue() {
return field;
}
}
public interface LocationBias extends StringJoin.UrlValue {}
public static class LocationBiasIP implements LocationBias {
@Override
public String toUrlValue() {
return "ipbias";
}
}
public static class LocationBiasPoint implements LocationBias {
private final LatLng point;
public LocationBiasPoint(LatLng point) {
this.point = point;
}
@Override
public String toUrlValue() {
return "point:" + point.toUrlValue();
}
}
public static class LocationBiasCircular implements LocationBias {
private final LatLng center;
private final int radius;
public LocationBiasCircular(LatLng center, int radius) {
this.center = center;
this.radius = radius;
}
@Override
public String toUrlValue() {
return "circle:" + radius + "@" + center.toUrlValue();
}
}
public static class LocationBiasRectangular implements LocationBias {
private final LatLng southWest;
private final LatLng northEast;
public LocationBiasRectangular(LatLng southWest, LatLng northEast) {
this.southWest = southWest;
this.northEast = northEast;
}
@Override
public String toUrlValue() {
return "rectangle:" + southWest.toUrlValue() + "|" + northEast.toUrlValue();
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/GaeRequestHandler.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import static java.nio.charset.StandardCharsets.UTF_8;
import ai.nextbillion.maps.GeoApiContext.RequestHandler;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.ExceptionsAllowedToRetry;
import ai.nextbillion.maps.internal.GaePendingResult;
import ai.nextbillion.maps.internal.HttpHeaders;
import ai.nextbillion.maps.metrics.RequestMetrics;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.gson.FieldNamingPolicy;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A strategy for handling URL requests using Google App Engine's URL Fetch API.
*
* @see GeoApiContext.RequestHandler
*/
public class GaeRequestHandler implements GeoApiContext.RequestHandler {
private static final Logger LOG = LoggerFactory.getLogger(GaeRequestHandler.class.getName());
private final URLFetchService client = URLFetchServiceFactory.getURLFetchService();
/* package */ GaeRequestHandler() {}
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handle(
String hostName,
String url,
String userAgent,
String experienceIdHeaderValue,
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeout,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics) {
FetchOptions fetchOptions = FetchOptions.Builder.withDeadline(10);
HTTPRequest req;
try {
req = new HTTPRequest(new URL(hostName + url), HTTPMethod.POST, fetchOptions);
if (experienceIdHeaderValue != null) {
req.setHeader(
new HTTPHeader(HttpHeaders.X_GOOG_MAPS_EXPERIENCE_ID, experienceIdHeaderValue));
}
} catch (MalformedURLException e) {
LOG.error("Request: {}{}", hostName, url, e);
throw (new RuntimeException(e));
}
return new GaePendingResult<>(
req,
client,
clazz,
fieldNamingPolicy,
errorTimeout,
maxRetries,
exceptionsAllowedToRetry,
metrics);
}
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handlePost(
String hostName,
String url,
String payload,
String userAgent,
String experienceIdHeaderValue,
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeout,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics) {
FetchOptions fetchOptions = FetchOptions.Builder.withDeadline(10);
HTTPRequest req = null;
try {
req = new HTTPRequest(new URL(hostName + url), HTTPMethod.POST, fetchOptions);
req.setHeader(new HTTPHeader("Content-Type", "application/json; charset=utf-8"));
if (experienceIdHeaderValue != null) {
req.setHeader(
new HTTPHeader(HttpHeaders.X_GOOG_MAPS_EXPERIENCE_ID, experienceIdHeaderValue));
}
req.setPayload(payload.getBytes(UTF_8));
} catch (MalformedURLException e) {
LOG.error("Request: {}{}", hostName, url, e);
throw (new RuntimeException(e));
}
return new GaePendingResult<>(
req,
client,
clazz,
fieldNamingPolicy,
errorTimeout,
maxRetries,
exceptionsAllowedToRetry,
metrics);
}
@Override
public void shutdown() {
// do nothing
}
/** Builder strategy for constructing {@code GaeRequestHandler}. */
public static class Builder implements GeoApiContext.RequestHandler.Builder {
@Override
public Builder connectTimeout(long timeout, TimeUnit unit) {
throw new RuntimeException("connectTimeout not implemented for Google App Engine");
}
@Override
public Builder readTimeout(long timeout, TimeUnit unit) {
throw new RuntimeException("readTimeout not implemented for Google App Engine");
}
@Override
public Builder writeTimeout(long timeout, TimeUnit unit) {
throw new RuntimeException("writeTimeout not implemented for Google App Engine");
}
@Override
public Builder queriesPerSecond(int maxQps) {
throw new RuntimeException("queriesPerSecond not implemented for Google App Engine");
}
@Override
public Builder proxy(Proxy proxy) {
throw new RuntimeException("setProxy not implemented for Google App Engine");
}
@Override
public Builder proxyAuthentication(String proxyUserName, String proxyUserPassword) {
throw new RuntimeException("setProxyAuthentication not implemented for Google App Engine");
}
@Override
public RequestHandler.Builder apiKey(String apiKey) {
return this;
}
@Override
public RequestHandler.Builder apiKeyInQuery(boolean apiKeyInQuery) {
return this;
}
@Override
public RequestHandler build() {
return new GaeRequestHandler();
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/GeoApiContext.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.errors.OverQueryLimitException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.ExceptionsAllowedToRetry;
import ai.nextbillion.maps.internal.HttpHeaders;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.internal.UrlSigner;
import ai.nextbillion.maps.metrics.NoOpRequestMetricsReporter;
import ai.nextbillion.maps.metrics.RequestMetrics;
import ai.nextbillion.maps.metrics.RequestMetricsReporter;
import com.google.gson.FieldNamingPolicy;
import java.net.Proxy;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* The entry point for making requests against the Google Geo APIs.
*
* <p>Construct this object by using the enclosed {@link GeoApiContext.Builder}.
*
* <p>GeoApiContexts should be shared
*
* <p>GeoApiContext works best when you create a single GeoApiContext instance, or one per API key,
* and reuse it for all your Google Geo API queries. This is because each GeoApiContext manages its
* own thread pool, back-end client, and other resources.
*
* <p>When you are finished with a GeoApiContext object, you must call {@link #shutdown()} on it to
* release its resources.
*/
public class GeoApiContext {
private static final String VERSION = "@VERSION@"; // Populated by the build script
private static final String USER_AGENT = "GoogleGeoApiClientJava/" + VERSION;
private static final int DEFAULT_BACKOFF_TIMEOUT_MILLIS = 60 * 1000; // 60s
private final RequestHandler requestHandler;
private final String apiKey;
private boolean apiKeyInQuery = false;
private final String baseUrlOverride;
private final String channel;
private final String clientId;
private final long errorTimeout;
private final ExceptionsAllowedToRetry exceptionsAllowedToRetry;
private final Integer maxRetries;
private final UrlSigner urlSigner;
private String experienceIdHeaderValue;
private final RequestMetricsReporter requestMetricsReporter;
/* package */
GeoApiContext(
RequestHandler requestHandler,
String apiKey,
boolean apiKeyInQuery,
String baseUrlOverride,
String channel,
String clientId,
long errorTimeout,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
Integer maxRetries,
UrlSigner urlSigner,
RequestMetricsReporter requestMetricsReporter,
String... experienceIdHeaderValue) {
this.requestHandler = requestHandler;
this.apiKey = apiKey;
this.apiKeyInQuery = apiKeyInQuery;
this.baseUrlOverride = baseUrlOverride;
this.channel = channel;
this.clientId = clientId;
this.errorTimeout = errorTimeout;
this.exceptionsAllowedToRetry = exceptionsAllowedToRetry;
this.maxRetries = maxRetries;
this.urlSigner = urlSigner;
this.requestMetricsReporter = requestMetricsReporter;
setExperienceId(experienceIdHeaderValue);
}
/**
* The service provider interface that enables requests to be handled via switchable back ends.
* There are supplied implementations of this interface for both OkHttp and Google App Engine's
* URL Fetch API.
*
* @see OkHttpRequestHandler
* @see GaeRequestHandler
*/
public interface RequestHandler {
<T, R extends ApiResponse<T>> PendingResult<T> handle(
String hostName,
String url,
String userAgent,
String experienceIdHeaderValue,
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeout,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics);
<T, R extends ApiResponse<T>> PendingResult<T> handlePost(
String hostName,
String url,
String payload,
String userAgent,
String experienceIdHeaderValue,
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeout,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics);
void shutdown();
/** Builder pattern for {@code GeoApiContext.RequestHandler}. */
interface Builder {
Builder connectTimeout(long timeout, TimeUnit unit);
Builder readTimeout(long timeout, TimeUnit unit);
Builder writeTimeout(long timeout, TimeUnit unit);
Builder queriesPerSecond(int maxQps);
Builder proxy(Proxy proxy);
Builder proxyAuthentication(String proxyUserName, String proxyUserPassword);
Builder apiKey(String apiKey);
Builder apiKeyInQuery(boolean apiKeyInQuery);
RequestHandler build();
}
}
/**
* Sets the value for the HTTP header field name {@link HttpHeaders#X_GOOG_MAPS_EXPERIENCE_ID} to
* be used on subsequent API calls. Calling this method with {@code null} is equivalent to calling
* {@link #clearExperienceId()}.
*
* @param experienceId The experience ID if set, otherwise null
*/
public void setExperienceId(String... experienceId) {
if (experienceId == null || experienceId.length == 0) {
experienceIdHeaderValue = null;
return;
}
experienceIdHeaderValue = StringJoin.join(",", experienceId);
}
/** @return Returns the experience ID if set, otherwise, null */
public String getExperienceId() {
return experienceIdHeaderValue;
}
/**
* Clears the experience ID if set the HTTP header field {@link
* HttpHeaders#X_GOOG_MAPS_EXPERIENCE_ID} will be omitted from subsequent calls.
*/
public void clearExperienceId() {
experienceIdHeaderValue = null;
}
/**
* Shut down this GeoApiContext instance, reclaiming resources. After shutdown() has been called,
* no further queries may be done against this instance.
*/
public void shutdown() {
requestHandler.shutdown();
}
<T, R extends ApiResponse<T>> PendingResult<T> get(
ApiConfig config, Class<? extends R> clazz, Map<String, List<String>> params) {
if (channel != null && !channel.isEmpty() && !params.containsKey("channel")) {
params.put("channel", Collections.singletonList(channel));
}
StringBuilder query = new StringBuilder();
for (Map.Entry<String, List<String>> param : params.entrySet()) {
List<String> values = param.getValue();
for (String value : values) {
query.append('&').append(param.getKey()).append("=").append(value);
}
}
return getWithPath(
clazz,
config.fieldNamingPolicy,
config.hostName,
config.path,
config.supportsClientId,
query.toString(),
requestMetricsReporter.newRequest(config.path));
}
<T, R extends ApiResponse<T>> PendingResult<T> get(
ApiConfig config, Class<? extends R> clazz, String... params) {
if (params.length % 2 != 0) {
throw new IllegalArgumentException("Params must be matching key/value pairs.");
}
StringBuilder query = new StringBuilder();
boolean channelSet = false;
for (int i = 0; i < params.length; i += 2) {
if (params[i].equals("channel")) {
channelSet = true;
}
query.append('&').append(params[i]).append('=').append(params[i + 1]);
}
// Channel can be supplied per-request or per-context. We prioritize it from the request,
// so if it's not provided there, provide it here
if (!channelSet && channel != null && !channel.isEmpty()) {
query.append("&channel=").append(channel);
}
return getWithPath(
clazz,
config.fieldNamingPolicy,
config.hostName,
config.path,
config.supportsClientId,
query.toString(),
requestMetricsReporter.newRequest(config.path));
}
<T, R extends ApiResponse<T>> PendingResult<T> post(
ApiConfig config, Class<? extends R> clazz, Map<String, List<String>> params) {
checkContext(config.supportsClientId);
StringBuilder url = new StringBuilder(config.path);
if (config.supportsClientId && clientId != null) {
url.append("?client=").append(clientId);
} else {
url.append("?k=1");
}
if (config.supportsClientId && urlSigner != null) {
String signature = urlSigner.getSignature(url.toString());
url.append("&signature=").append(signature);
}
String hostName = config.hostName;
if (baseUrlOverride != null) {
hostName = baseUrlOverride;
}
return requestHandler.handlePost(
hostName,
url.toString(),
params.get("_payload").get(0),
USER_AGENT,
experienceIdHeaderValue,
clazz,
config.fieldNamingPolicy,
errorTimeout,
maxRetries,
exceptionsAllowedToRetry,
requestMetricsReporter.newRequest(config.path));
}
private <T, R extends ApiResponse<T>> PendingResult<T> getWithPath(
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
String hostName,
String path,
boolean canUseClientId,
String encodedPath,
RequestMetrics metrics) {
checkContext(canUseClientId);
if (!encodedPath.startsWith("&")) {
throw new IllegalArgumentException("encodedPath must start with &");
}
StringBuilder url = new StringBuilder(path);
if (canUseClientId && clientId != null) {
url.append("?client=").append(clientId);
} else {
url.append("?k=1");
}
url.append(encodedPath);
if (canUseClientId && urlSigner != null) {
String signature = urlSigner.getSignature(url.toString());
url.append("&signature=").append(signature);
}
if (baseUrlOverride != null) {
hostName = baseUrlOverride;
}
return requestHandler.handle(
hostName,
url.toString(),
USER_AGENT,
experienceIdHeaderValue,
clazz,
fieldNamingPolicy,
errorTimeout,
maxRetries,
exceptionsAllowedToRetry,
metrics);
}
private void checkContext(boolean canUseClientId) {
if (urlSigner == null && apiKey == null) {
throw new IllegalStateException("Must provide either API key or Maps for Work credentials.");
} else if (!canUseClientId && apiKey == null) {
throw new IllegalStateException(
"API does not support client ID & secret - you must provide a key");
}
}
/** The Builder for {@code GeoApiContext}. */
public static class Builder {
private RequestHandler.Builder builder;
private String apiKey;
private boolean apiKeyInQuery = false;
private String baseUrlOverride;
private String channel;
private String clientId;
private long errorTimeout = DEFAULT_BACKOFF_TIMEOUT_MILLIS;
private final ExceptionsAllowedToRetry exceptionsAllowedToRetry =
new ExceptionsAllowedToRetry();
private Integer maxRetries;
private UrlSigner urlSigner;
private RequestMetricsReporter requestMetricsReporter = new NoOpRequestMetricsReporter();
private String[] experienceIdHeaderValue;
/** Builder pattern for the enclosing {@code GeoApiContext}. */
public Builder() {
requestHandlerBuilder(new OkHttpRequestHandler.Builder());
}
public Builder(RequestHandler.Builder builder) {
requestHandlerBuilder(builder);
}
/**
* Changes the RequestHandler.Builder strategy to change between the {@code
* OkHttpRequestHandler} and the {@code GaeRequestHandler}.
*
* @param builder The {@code RequestHandler.Builder} to use for {@link #build()}
* @return Returns this builder for call chaining.
* @see OkHttpRequestHandler
* @see GaeRequestHandler
*/
public Builder requestHandlerBuilder(RequestHandler.Builder builder) {
this.builder = builder;
this.exceptionsAllowedToRetry.add(OverQueryLimitException.class);
return this;
}
/**
* Overrides the base URL of the API endpoint. Useful for testing or certain international usage
* scenarios.
*
* @param hostName The URL to use, without a trailing slash
* @return Returns this builder for call chaining.
*/
public Builder hostName(String hostName) {
baseUrlOverride = hostName;
return this;
}
/**
* Sets the API Key to use for authorizing requests.
*
* @param apiKey The API Key to use.
* @return Returns this builder for call chaining.
*/
public Builder apiKey(String apiKey) {
this.apiKey = apiKey;
builder.apiKey(apiKey);
return this;
}
/**
* Sets the API Key to use for authorizing requests.
*
* @param apiKeyInQuery apiKeyInQuery
* @return Returns this builder for call chaining.
*/
public Builder apiKeyInQuery(boolean apiKeyInQuery) {
this.apiKeyInQuery = apiKeyInQuery;
builder.apiKeyInQuery(apiKeyInQuery);
return this;
}
/**
* Sets the ClientID/Secret pair to use for authorizing requests. Most users should use {@link
* #apiKey(String)} instead.
*
* @param clientId The Client ID to use.
* @param cryptographicSecret The Secret to use.
* @return Returns this builder for call chaining.
*/
public Builder enterpriseCredentials(String clientId, String cryptographicSecret) {
this.clientId = clientId;
try {
this.urlSigner = new UrlSigner(cryptographicSecret);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
return this;
}
/**
* Sets the default channel for requests (can be overridden by requests). Only useful for Google
* Maps for Work clients.
*
* @param channel The channel to use for analytics
* @return Returns this builder for call chaining.
*/
public Builder channel(String channel) {
this.channel = channel;
return this;
}
/**
* Sets the default connect timeout for new connections. A value of 0 means no timeout.
*
* @see java.net.URLConnection#setConnectTimeout(int)
* @param timeout The connect timeout period in {@code unit}s.
* @param unit The connect timeout time unit.
* @return Returns this builder for call chaining.
*/
public Builder connectTimeout(long timeout, TimeUnit unit) {
builder.connectTimeout(timeout, unit);
return this;
}
/**
* Sets the default read timeout for new connections. A value of 0 means no timeout.
*
* @see java.net.URLConnection#setReadTimeout(int)
* @param timeout The read timeout period in {@code unit}s.
* @param unit The read timeout time unit.
* @return Returns this builder for call chaining.
*/
public Builder readTimeout(long timeout, TimeUnit unit) {
builder.readTimeout(timeout, unit);
return this;
}
/**
* Sets the default write timeout for new connections. A value of 0 means no timeout.
*
* @param timeout The write timeout period in {@code unit}s.
* @param unit The write timeout time unit.
* @return Returns this builder for call chaining.
*/
public Builder writeTimeout(long timeout, TimeUnit unit) {
builder.writeTimeout(timeout, unit);
return this;
}
/**
* Sets the cumulative time limit for which retry-able errors will be retried. Defaults to 60
* seconds. Set to zero to retry requests forever.
*
* <p>This operates separately from the count-based {@link #maxRetries(Integer)}.
*
* @param timeout The retry timeout period in {@code unit}s.
* @param unit The retry timeout time unit.
* @return Returns this builder for call chaining.
*/
public Builder retryTimeout(long timeout, TimeUnit unit) {
this.errorTimeout = unit.toMillis(timeout);
return this;
}
/**
* Sets the maximum number of times each retry-able errors will be retried. Set this to null to
* not have a max number. Set this to zero to disable retries.
*
* <p>This operates separately from the time-based {@link #retryTimeout(long, TimeUnit)}.
*
* @param maxRetries The maximum number of times to retry.
* @return Returns this builder for call chaining.
*/
public Builder maxRetries(Integer maxRetries) {
this.maxRetries = maxRetries;
return this;
}
/**
* Disables retries completely, by setting max retries to 0 and retry timeout to 0.
*
* @return Returns this builder for call chaining.
*/
public Builder disableRetries() {
maxRetries(0);
retryTimeout(0, TimeUnit.MILLISECONDS);
return this;
}
/**
* Sets the maximum number of queries that will be executed during a 1 second interval. The
* default is 50. A minimum interval between requests will also be enforced, set to 1/(2 *
* {@code maxQps}).
*
* @param maxQps The maximum queries per second.
* @return Returns this builder for call chaining.
*/
public Builder queryRateLimit(int maxQps) {
builder.queriesPerSecond(maxQps);
return this;
}
/**
* Allows specific API exceptions to be retried or not retried.
*
* @param exception The {@code ApiException} to allow or deny being re-tried.
* @param allowedToRetry Whether to allow or deny re-trying {@code exception}.
* @return Returns this builder for call chaining.
*/
public Builder setIfExceptionIsAllowedToRetry(
Class<? extends ApiException> exception, boolean allowedToRetry) {
if (allowedToRetry) {
exceptionsAllowedToRetry.add(exception);
} else {
exceptionsAllowedToRetry.remove(exception);
}
return this;
}
/**
* Sets the proxy for new connections.
*
* @param proxy The proxy to be used by the underlying HTTP client.
* @return Returns this builder for call chaining.
*/
public Builder proxy(Proxy proxy) {
builder.proxy(proxy == null ? Proxy.NO_PROXY : proxy);
return this;
}
/**
* set authentication for proxy
*
* @param proxyUserName username for proxy authentication
* @param proxyUserPassword username for proxy authentication
* @return Returns this builder for call chaining.
*/
public Builder proxyAuthentication(String proxyUserName, String proxyUserPassword) {
builder.proxyAuthentication(proxyUserName, proxyUserPassword);
return this;
}
/**
* Sets the value for the HTTP header field name {@link HttpHeaders#X_GOOG_MAPS_EXPERIENCE_ID}
* HTTP header value for the field name on subsequent API calls.
*
* @param experienceId The experience ID
* @return Returns this builder for call chaining.
*/
public Builder experienceId(String... experienceId) {
this.experienceIdHeaderValue = experienceId;
return this;
}
public Builder requestMetricsReporter(RequestMetricsReporter requestMetricsReporter) {
this.requestMetricsReporter = requestMetricsReporter;
return this;
}
/**
* Converts this builder into a {@code GeoApiContext}.
*
* @return Returns the built {@code GeoApiContext}.
*/
public GeoApiContext build() {
return new GeoApiContext(
builder.build(),
apiKey,
apiKeyInQuery,
baseUrlOverride,
channel,
clientId,
errorTimeout,
exceptionsAllowedToRetry,
maxRetries,
urlSigner,
requestMetricsReporter,
experienceIdHeaderValue);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/GeocodingApi.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.model.LatLng;
/**
* Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View,
* CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you
* can use to place markers or position the map. Reverse geocoding is the process of converting
* geographic coordinates into a human-readable address.
*
* @see <a href="https://developers.google.com/maps/documentation/geocoding/">Geocoding
* documentation</a>
*/
public class GeocodingApi {
private GeocodingApi() {}
/**
* Creates a new Geocoding API request.
*
* @param context The {@link GeoApiContext} to make requests through.
* @return Returns the request, ready to run.
*/
public static GeocodingApiRequest newRequest(GeoApiContext context) {
return new GeocodingApiRequest(context);
}
/**
* Requests the latitude and longitude of an {@code address}.
*
* @param context The {@link GeoApiContext} to make requests through.
* @param address The address to geocode.
* @return Returns the request, ready to run.
*/
public static GeocodingApiRequest geocode(GeoApiContext context, String address) {
throw new UnsupportedOperationException("Not supported yet");
}
/**
* Requests the street address of a {@code location}.
*
* @param context The {@link GeoApiContext} to make requests through.
* @param location The location to reverse geocode.
* @return Returns the request, ready to run.
*/
public static GeocodingApiRequest reverseGeocode(GeoApiContext context, LatLng location) {
GeocodingApiRequest request = new GeocodingApiRequest(context);
request.latlng(location);
return request;
}
public static class Response implements ApiResponse<String[]> {
public String status;
public String errorMessage;
public String[] names;
@Override
public boolean successful() {
return "Ok".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public String[] getResult() {
return names;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/GeocodingApiRequest.java
|
package ai.nextbillion.maps;
import static ai.nextbillion.maps.internal.StringJoin.join;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.model.AddressType;
import ai.nextbillion.maps.model.ComponentFilter;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.LocationType;
/** A request for the Geocoding API. */
public class GeocodingApiRequest
extends PendingResultBase<String[], GeocodingApiRequest, GeocodingApi.Response> {
private static final ApiConfig API_CONFIG = new ApiConfig("/geocode/json");
public GeocodingApiRequest(GeoApiContext context) {
super(context, API_CONFIG, GeocodingApi.Response.class);
}
@Override
protected void validateRequest() {
// Must not have both address and latlng.
if (params().containsKey("latlng")
&& params().containsKey("address")
&& params().containsKey("place_id")) {
throw new IllegalArgumentException(
"Request must contain only one of 'address', 'latlng' or 'place_id'.");
}
// Must contain at least one of place_id, address, latlng, and components;
if (!params().containsKey("coordinate")
&& !params().containsKey("address")
&& !params().containsKey("components")
&& !params().containsKey("place_id")) {
throw new IllegalArgumentException(
"Request must contain at least one of 'address', 'latlng', 'place_id' and 'components'.");
}
}
/**
* Creates a forward geocode for {@code address}.
*
* @param address The address to geocode.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest address(String address) {
return param("address", address);
}
/**
* Creates a forward geocode for {@code placeId}.
*
* @param placeId The Place ID to geocode.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest place(String placeId) {
return param("place_id", placeId);
}
/**
* Creates a reverse geocode for {@code latlng}.
*
* @param latlng The location to reverse geocode.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest latlng(LatLng latlng) {
return param("coordinate", latlng);
}
/**
* Sets the bounding box of the viewport within which to bias geocode results more prominently.
* This parameter will only influence, not fully restrict, results from the geocoder.
*
* <p>For more information see <a
* href="https://developers.google.com/maps/documentation/geocoding/intro?hl=pl#Viewports">
* Viewport Biasing</a>.
*
* @param southWestBound The South West bound of the bounding box.
* @param northEastBound The North East bound of the bounding box.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest bounds(LatLng southWestBound, LatLng northEastBound) {
return param("bounds", join('|', southWestBound, northEastBound));
}
/**
* Sets the region code, specified as a ccTLD ("top-level domain") two-character value. This
* parameter will only influence, not fully restrict, results from the geocoder.
*
* <p>For more information see <a
* href="https://developers.google.com/maps/documentation/geocoding/intro?hl=pl#RegionCodes">Region
* Biasing</a>.
*
* @param region The region code to influence results.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest region(String region) {
return param("region", region);
}
/**
* Sets the component filters. Each component filter consists of a component:value pair and will
* fully restrict the results from the geocoder.
*
* <p>For more information see <a
* href="https://developers.google.com/maps/documentation/geocoding/intro?hl=pl#ComponentFiltering">
* Component Filtering</a>.
*
* @param filters Component filters to apply to the request.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest components(ComponentFilter... filters) {
return param("components", join('|', filters));
}
/**
* Sets the result type. Specifying a type will restrict the results to this type. If multiple
* types are specified, the API will return all addresses that match any of the types.
*
* @param resultTypes The result types to restrict to.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest resultType(AddressType... resultTypes) {
return param("result_type", join('|', resultTypes));
}
/**
* Sets the location type. Specifying a type will restrict the results to this type. If multiple
* types are specified, the API will return all addresses that match any of the types.
*
* @param locationTypes The location types to restrict to.
* @return Returns this {@code GeocodingApiRequest} for call chaining.
*/
public GeocodingApiRequest locationType(LocationType... locationTypes) {
return param("location_type", join('|', locationTypes));
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/GeolocationApi.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.model.GeolocationPayload;
import ai.nextbillion.maps.model.GeolocationResult;
import ai.nextbillion.maps.model.LatLng;
import com.google.gson.FieldNamingPolicy;
/*
* The Google Maps Geolocation API returns a location and accuracy radius based on information
* about cell towers and WiFi nodes that the mobile client can detect.
*
* <p>Please see the<a href="https://developers.google.com/maps/documentation/geolocation/intro#top_of_page">
* Geolocation API</a> for more detail.
*
*
*/
public class GeolocationApi {
private static final String API_BASE_URL = "https://www.googleapis.com";
static final ApiConfig GEOLOCATION_API_CONFIG =
new ApiConfig("/geolocation/v1/geolocate")
.hostName(API_BASE_URL)
.supportsClientId(false)
.fieldNamingPolicy(FieldNamingPolicy.IDENTITY)
.requestVerb("POST");
private GeolocationApi() {}
public static PendingResult<GeolocationResult> geolocate(
GeoApiContext context, GeolocationPayload payload) {
return new GeolocationApiRequest(context).Payload(payload).CreatePayload();
}
public static GeolocationApiRequest newRequest(GeoApiContext context) {
return new GeolocationApiRequest(context);
}
public static class Response implements ApiResponse<GeolocationResult> {
public int code = 200;
public String message = "OK";
public double accuracy = -1.0;
public LatLng location = null;
public String domain = null;
public String reason = null;
public String debugInfo = null;
@Override
public boolean successful() {
return code == 200;
}
@Override
public GeolocationResult getResult() {
GeolocationResult result = new GeolocationResult();
result.accuracy = accuracy;
result.location = location;
return result;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(reason, message);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/GeolocationApiRequest.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.model.CellTower;
import ai.nextbillion.maps.model.GeolocationPayload;
import ai.nextbillion.maps.model.GeolocationPayload.GeolocationPayloadBuilder;
import ai.nextbillion.maps.model.GeolocationResult;
import ai.nextbillion.maps.model.WifiAccessPoint;
import com.google.gson.Gson;
/** A request for the Geolocation API. */
public class GeolocationApiRequest
extends PendingResultBase<GeolocationResult, GeolocationApiRequest, GeolocationApi.Response> {
private GeolocationPayload payload = null;
private GeolocationPayloadBuilder builder = null;
GeolocationApiRequest(GeoApiContext context) {
super(context, GeolocationApi.GEOLOCATION_API_CONFIG, GeolocationApi.Response.class);
builder = new GeolocationPayload.GeolocationPayloadBuilder();
}
@Override
protected void validateRequest() {
if (this.payload.considerIp != null
&& !this.payload.considerIp
&& this.payload.wifiAccessPoints != null
&& this.payload.wifiAccessPoints.length < 2) {
throw new IllegalArgumentException("Request must contain two or more 'Wifi Access Points'");
}
}
public GeolocationApiRequest HomeMobileCountryCode(int newHomeMobileCountryCode) {
this.builder.HomeMobileCountryCode(newHomeMobileCountryCode);
return this;
}
public GeolocationApiRequest HomeMobileNetworkCode(int newHomeMobileNetworkCode) {
this.builder.HomeMobileNetworkCode(newHomeMobileNetworkCode);
return this;
}
public GeolocationApiRequest RadioType(String newRadioType) {
this.builder.RadioType(newRadioType);
return this;
}
public GeolocationApiRequest Carrier(String newCarrier) {
this.builder.Carrier(newCarrier);
return this;
}
public GeolocationApiRequest ConsiderIp(boolean newConsiderIp) {
this.builder.ConsiderIp(newConsiderIp);
return this;
}
public GeolocationApiRequest CellTowers(CellTower[] newCellTowers) {
this.builder.CellTowers(newCellTowers);
return this;
}
public GeolocationApiRequest AddCellTower(CellTower newCellTower) {
this.builder.AddCellTower(newCellTower);
return this;
}
public GeolocationApiRequest WifiAccessPoints(WifiAccessPoint[] newWifiAccessPoints) {
this.builder.WifiAccessPoints(newWifiAccessPoints);
return this;
}
public GeolocationApiRequest AddWifiAccessPoint(WifiAccessPoint newWifiAccessPoint) {
this.builder.AddWifiAccessPoint(newWifiAccessPoint);
return this;
}
public GeolocationApiRequest Payload(GeolocationPayload payload) {
this.payload = payload;
return this;
}
public GeolocationApiRequest CreatePayload() {
if (this.payload == null) {
// if the payload has not been set, create it
this.payload = this.builder.createGeolocationPayload();
} else {
// use the payload that has been explicitly set by the Payload method above
}
Gson gson = new Gson();
String jsonPayload = gson.toJson(this.payload);
return param("_payload", jsonPayload);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/ImageResult.java
|
/*
* Copyright 2018 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiResponse;
import java.io.Serializable;
/** {@code ImageResult} is the object returned from API end points that return images. */
public class ImageResult implements Serializable {
public ImageResult(String contentType, byte[] imageData) {
this.imageData = imageData;
this.contentType = contentType;
}
private static final long serialVersionUID = 1L;
/** The image data from the Photos API call. */
public final byte[] imageData;
/** The Content-Type header of the returned result. */
public final String contentType;
/**
* <code>ImageResult.Response</code> is a type system hack to enable API endpoints to return a
* <code>ImageResult</code>.
*/
public static class Response implements ApiResponse<ImageResult> {
@Override
public boolean successful() {
return true;
}
@Override
public ApiException getError() {
return null;
}
@Override
public ImageResult getResult() {
return null;
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/Main.java
|
package ai.nextbillion.maps;
import ai.nextbillion.maps.model.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.time.Instant;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
GeoApiContext context =
new GeoApiContext.Builder()
.hostName("https://ola.nextbillion.io")
.apiKey("olatesting")
.apiKeyInQuery(true)
.build();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map<String, DirectionsTableApi.DirectionsTableEntry> results =
DirectionsTableApi.getDirections(
context,
new LatLng(12.31619769, 76.64564422),
new LatLng(12.32394862, 76.62618961))
.alternatives(false)
.departureTime(Instant.ofEpochSecond(1608709385))
.mode("2w,3w,4w")
.await();
System.out.println(gson.toJson(results));
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/NearbySearchRequest.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.PlaceType;
import ai.nextbillion.maps.model.PlacesSearchResponse;
import ai.nextbillion.maps.model.PlacesSearchResult;
import ai.nextbillion.maps.model.PriceLevel;
import ai.nextbillion.maps.model.RankBy;
import com.google.gson.FieldNamingPolicy;
/**
* A <a href="https://developers.google.com/places/web-service/search#PlaceSearchRequests">Nearby
* Search</a> request.
*/
public class NearbySearchRequest
extends PendingResultBase<
PlacesSearchResponse, NearbySearchRequest, NearbySearchRequest.Response> {
static final ApiConfig API_CONFIG =
new ApiConfig("/maps/api/place/nearbysearch/json")
.fieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
/**
* Constructs a new {@code NearbySearchRequest}.
*
* @param context The {@code GeoApiContext} to make requests through.
*/
public NearbySearchRequest(GeoApiContext context) {
super(context, API_CONFIG, Response.class);
}
/**
* Specifies the latitude/longitude around which to retrieve place information.
*
* @param location The location to use as the center of the Nearby Search.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest location(LatLng location) {
return param("location", location);
}
/**
* Specifies the distance (in meters) within which to return place results. The maximum allowed
* radius is 50,000 meters. Note that radius must not be included if {@code rankby=DISTANCE} is
* specified.
*
* @param distance The distance in meters around the {@link #location(LatLng)} to search.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest radius(int distance) {
if (distance > 50000) {
throw new IllegalArgumentException("The maximum allowed radius is 50,000 meters.");
}
return param("radius", String.valueOf(distance));
}
/**
* Specifies the order in which results are listed.
*
* @param ranking The rank by method.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest rankby(RankBy ranking) {
return param("rankby", ranking);
}
/**
* Specifies a term to be matched against all content that Google has indexed for this place. This
* includes but is not limited to name, type, and address, as well as customer reviews and other
* third-party content.
*
* @param keyword The keyword to search for.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest keyword(String keyword) {
return param("keyword", keyword);
}
/**
* Restricts to places that are at least this price level.
*
* @param priceLevel The price level to set as minimum.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest minPrice(PriceLevel priceLevel) {
return param("minprice", priceLevel);
}
/**
* Restricts to places that are at most this price level.
*
* @param priceLevel The price level to set as maximum.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest maxPrice(PriceLevel priceLevel) {
return param("maxprice", priceLevel);
}
/**
* Specifies one or more terms to be matched against the names of places, separated by spaces.
*
* @param name Search for Places with this name.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest name(String name) {
return param("name", name);
}
/**
* Restricts to only those places that are open for business at the time the query is sent.
*
* @param openNow Whether to restrict to places that are open.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest openNow(boolean openNow) {
return param("opennow", String.valueOf(openNow));
}
/**
* Returns the next 20 results from a previously run search. Setting {@code pageToken} will
* execute a search with the same parameters used previously — all parameters other than {@code
* pageToken} will be ignored.
*
* @param nextPageToken The page token from a previous result.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest pageToken(String nextPageToken) {
return param("pagetoken", nextPageToken);
}
/**
* Restricts the results to places matching the specified type.
*
* @param type The {@link PlaceType} to restrict results to.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
public NearbySearchRequest type(PlaceType type) {
return param("type", type);
}
/**
* Restricts the results to places matching the specified type. Provides support for multiple
* types.
*
* @deprecated Multiple search types are ignored by the Places API.
* @param types The {@link PlaceType}s to restrict results to.
* @return Returns this {@code NearbyApiRequest} for call chaining.
*/
@Deprecated
public NearbySearchRequest type(PlaceType... types) {
return param("type", StringJoin.join('|', types));
}
@Override
protected void validateRequest() {
// If pagetoken is included, all other parameters are ignored.
if (params().containsKey("pagetoken")) {
return;
}
// radius must not be included if rankby=distance
if (params().containsKey("rankby")
&& params().get("rankby").get(0).equals(RankBy.DISTANCE.toString())
&& params().containsKey("radius")) {
throw new IllegalArgumentException("Request must not contain radius with rankby=distance");
}
// If rankby=distance is specified, then one or more of keyword, name, or type is required.
if (params().containsKey("rankby")
&& params().get("rankby").get(0).equals(RankBy.DISTANCE.toString())
&& !params().containsKey("keyword")
&& !params().containsKey("name")
&& !params().containsKey("type")) {
throw new IllegalArgumentException(
"With rankby=distance is specified, then one or more of keyword, name, or type is required");
}
}
public static class Response implements ApiResponse<PlacesSearchResponse> {
public String status;
public String[] htmlAttributions;
public PlacesSearchResult[] results;
public String nextPageToken;
public String errorMessage;
@Override
public boolean successful() {
return "OK".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public PlacesSearchResponse getResult() {
PlacesSearchResponse result = new PlacesSearchResponse();
result.htmlAttributions = htmlAttributions;
result.results = results;
result.nextPageToken = nextPageToken;
return result;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/OkHttpRequestHandler.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.GeoApiContext.RequestHandler;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.ExceptionsAllowedToRetry;
import ai.nextbillion.maps.internal.HttpHeaders;
import ai.nextbillion.maps.internal.OkHttpPendingResult;
import ai.nextbillion.maps.internal.RateLimitExecutorService;
import ai.nextbillion.maps.metrics.RequestMetrics;
import com.google.gson.FieldNamingPolicy;
import java.io.IOException;
import java.net.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.Dispatcher;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
/**
* A strategy for handling URL requests using OkHttp.
*
* @see GeoApiContext.RequestHandler
*/
public class OkHttpRequestHandler implements GeoApiContext.RequestHandler {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private final OkHttpClient client;
private final ExecutorService executorService;
private final String apiKey;
private boolean apiKeyInQuery;
/* package */ OkHttpRequestHandler(
OkHttpClient client, ExecutorService executorService, String apiKey, boolean apiKeyInQuery) {
this.client = client;
this.executorService = executorService;
this.apiKey = apiKey;
this.apiKeyInQuery = apiKeyInQuery;
}
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handle(
String hostName,
String url,
String userAgent,
String experienceIdHeaderValue,
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeout,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics) {
Request.Builder builder = new Request.Builder().get().header("User-Agent", userAgent);
if (apiKeyInQuery) {
if (url.contains("?")) {
url = url + "&key=" + apiKey;
} else {
url = url + "?key=" + apiKey;
}
} else {
builder.header("Authorization", apiKey);
}
if (experienceIdHeaderValue != null) {
builder = builder.header(HttpHeaders.X_GOOG_MAPS_EXPERIENCE_ID, experienceIdHeaderValue);
}
Request req = builder.url(hostName + url).build();
return new OkHttpPendingResult<>(
req,
client,
clazz,
fieldNamingPolicy,
errorTimeout,
maxRetries,
exceptionsAllowedToRetry,
metrics);
}
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handlePost(
String hostName,
String url,
String payload,
String userAgent,
String experienceIdHeaderValue,
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeout,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics) {
RequestBody body = RequestBody.create(JSON, payload);
Request.Builder builder = new Request.Builder().post(body).header("User-Agent", userAgent);
if (apiKeyInQuery) {
if (url.contains("?")) {
url = url + "&key=" + apiKey;
} else {
url = url + "?key=" + apiKey;
}
} else {
builder.header("Authorization", apiKey);
}
if (experienceIdHeaderValue != null) {
builder = builder.header(HttpHeaders.X_GOOG_MAPS_EXPERIENCE_ID, experienceIdHeaderValue);
}
Request req = builder.url(hostName + url).build();
return new OkHttpPendingResult<>(
req,
client,
clazz,
fieldNamingPolicy,
errorTimeout,
maxRetries,
exceptionsAllowedToRetry,
metrics);
}
@Override
public void shutdown() {
executorService.shutdown();
client.connectionPool().evictAll();
}
/** Builder strategy for constructing an {@code OkHTTPRequestHandler}. */
public static class Builder implements GeoApiContext.RequestHandler.Builder {
private final OkHttpClient.Builder builder;
private final RateLimitExecutorService rateLimitExecutorService;
private final Dispatcher dispatcher;
private String apiKey;
private boolean apiKeyInQuery = false;
public Builder() {
builder = new OkHttpClient.Builder();
rateLimitExecutorService = new RateLimitExecutorService();
dispatcher = new Dispatcher(rateLimitExecutorService);
builder.dispatcher(dispatcher);
}
@Override
public Builder connectTimeout(long timeout, TimeUnit unit) {
builder.connectTimeout(timeout, unit);
return this;
}
@Override
public Builder readTimeout(long timeout, TimeUnit unit) {
builder.readTimeout(timeout, unit);
return this;
}
@Override
public Builder writeTimeout(long timeout, TimeUnit unit) {
builder.writeTimeout(timeout, unit);
return this;
}
@Override
public Builder queriesPerSecond(int maxQps) {
dispatcher.setMaxRequests(maxQps);
dispatcher.setMaxRequestsPerHost(maxQps);
rateLimitExecutorService.setQueriesPerSecond(maxQps);
return this;
}
@Override
public Builder proxy(Proxy proxy) {
builder.proxy(proxy);
return this;
}
@Override
public Builder proxyAuthentication(String proxyUserName, String proxyUserPassword) {
final String userName = proxyUserName;
final String password = proxyUserPassword;
builder.proxyAuthenticator(
new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(userName, password);
return response
.request()
.newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
});
return this;
}
@Override
public RequestHandler.Builder apiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
@Override
public RequestHandler.Builder apiKeyInQuery(boolean apiKeyInQuery) {
this.apiKeyInQuery = apiKeyInQuery;
return this;
}
/**
* Gets a reference to the OkHttpClient.Builder used to build the OkHttpRequestHandler's
* internal OkHttpClient. This allows you to fully customize the OkHttpClient that the resulting
* OkHttpRequestHandler will make HTTP requests through.
*
* @return OkHttpClient.Builder that will produce the OkHttpClient used by the
* OkHttpRequestHandler built by this.
*/
public OkHttpClient.Builder okHttpClientBuilder() {
return builder;
}
@Override
public RequestHandler build() {
OkHttpClient client = builder.build();
return new OkHttpRequestHandler(client, rateLimitExecutorService, apiKey, apiKeyInQuery);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/PendingResult.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import java.io.IOException;
/**
* A pending result from an API call.
*
* @param <T> the type of the result object.
*/
public interface PendingResult<T> {
/**
* Performs the request asynchronously, calling {@link PendingResult.Callback#onResult onResult}
* or {@link PendingResult.Callback#onFailure onFailure} after the request has been completed.
*
* @param callback The callback to call on completion.
*/
void setCallback(Callback<T> callback);
/**
* Performs the request synchronously.
*
* @return The result.
* @throws ApiException Thrown if the API Returned result is an error.
* @throws InterruptedException Thrown when a thread is waiting, sleeping, or otherwise occupied,
* and the thread is interrupted.
* @throws IOException Thrown when an I/O exception of some sort has occurred.
*/
T await() throws ApiException, InterruptedException, IOException;
/**
* Performs the request synchronously, ignoring exceptions while performing the request and errors
* returned by the server.
*
* @return The result, or null if there was any error or exception ignored.
*/
T awaitIgnoreError();
/** Attempts to cancel the request. */
void cancel();
/**
* The callback interface the API client code needs to implement to handle API results.
*
* @param <T> The type of the result object.
*/
interface Callback<T> {
/**
* Called when the request was successfully completed.
*
* @param result The result of the call.
*/
void onResult(T result);
/**
* Called when there was an error performing the request.
*
* @param e The exception describing the failure.
*/
void onFailure(Throwable e);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/PendingResultBase.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.StringJoin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Base implementation for {@code PendingResult}.
*
* <p>{@code T} is the class of the result, {@code A} is the actual base class of this abstract
* class, and R is the type of the request.
*/
abstract class PendingResultBase<T, A extends PendingResultBase<T, A, R>, R extends ApiResponse<T>>
implements PendingResult<T> {
private final GeoApiContext context;
private final ApiConfig config;
private final HashMap<String, List<String>> params = new HashMap<>();
private PendingResult<T> delegate;
private final Class<? extends R> responseClass;
protected PendingResultBase(GeoApiContext context, ApiConfig config, Class<? extends R> clazz) {
this.context = context;
this.config = config;
this.responseClass = clazz;
}
@Override
public final void setCallback(Callback<T> callback) {
makeRequest().setCallback(callback);
}
@Override
public final T await() throws ApiException, InterruptedException, IOException {
PendingResult<T> request = makeRequest();
return request.await();
}
@Override
public final T awaitIgnoreError() {
return makeRequest().awaitIgnoreError();
}
@Override
public final void cancel() {
if (delegate == null) {
return;
}
delegate.cancel();
}
private PendingResult<T> makeRequest() {
if (delegate != null) {
throw new IllegalStateException(
"'await', 'awaitIgnoreError' or 'setCallback' was already called.");
}
validateRequest();
switch (config.requestVerb) {
case "GET":
return delegate = context.get(config, responseClass, params);
case "POST":
return delegate = context.post(config, responseClass, params);
default:
throw new IllegalStateException(
String.format("Unexpected request method '%s'", config.requestVerb));
}
}
protected abstract void validateRequest();
private A getInstance() {
@SuppressWarnings("unchecked")
A result = (A) this;
return result;
}
protected A param(String key, String val) {
// Enforce singleton parameter semantics for most API surfaces
params.put(key, new ArrayList<String>());
return paramAddToList(key, val);
}
protected A param(String key, int val) {
return this.param(key, Integer.toString(val));
}
protected A param(String key, StringJoin.UrlValue val) {
if (val != null) {
return this.param(key, val.toUrlValue());
}
return getInstance();
}
protected A paramAddToList(String key, String val) {
// Multiple parameter values required to support Static Maps API paths and markers.
if (params.get(key) == null) {
params.put(key, new ArrayList<String>());
}
params.get(key).add(val);
return getInstance();
}
protected A paramAddToList(String key, StringJoin.UrlValue val) {
if (val != null) {
return this.paramAddToList(key, val.toUrlValue());
}
return getInstance();
}
protected Map<String, List<String>> params() {
return Collections.unmodifiableMap(params);
}
/**
* The language in which to return results. Note that we often update supported languages so this
* list may not be exhaustive.
*
* @param language The language code, e.g. "en-AU" or "es".
* @see <a href="https://developers.google.com/maps/faq#languagesupport">List of supported domain
* languages</a>
* @return Returns the request for call chaining.
*/
public final A language(String language) {
return param("language", language);
}
/**
* A channel to pass with the request. channel is used by Google Maps API for Work users to be
* able to track usage across different applications with the same clientID. See <a
* href="https://developers.google.com/maps/documentation/business/clientside/quota">Premium Plan
* Usage Rates and Limits</a>.
*
* @param channel String to pass with the request for analytics.
* @return Returns the request for call chaining.
*/
public A channel(String channel) {
return param("channel", channel);
}
/**
* Custom parameter. For advanced usage only.
*
* @param parameter The name of the custom parameter.
* @param value The value of the custom parameter.
* @return Returns the request for call chaining.
*/
public A custom(String parameter, String value) {
return param(parameter, value);
}
public A context(String context) {
return param("context", context);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/PhotoRequest.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.internal.ApiConfig;
/**
* A <a href="https://developers.google.com/places/web-service/photos#place_photo_requests">Place
* Photo</a> request.
*/
public class PhotoRequest
extends PendingResultBase<ImageResult, PhotoRequest, ImageResult.Response> {
static final ApiConfig API_CONFIG = new ApiConfig("/maps/api/place/photo");
public PhotoRequest(GeoApiContext context) {
super(context, API_CONFIG, ImageResult.Response.class);
}
@Override
protected void validateRequest() {
if (!params().containsKey("photoreference")) {
throw new IllegalArgumentException("Request must contain 'photoReference'.");
}
if (!params().containsKey("maxheight") && !params().containsKey("maxwidth")) {
throw new IllegalArgumentException("Request must contain 'maxHeight' or 'maxWidth'.");
}
}
/**
* Sets the photoReference for this request.
*
* @param photoReference A string identifier that uniquely identifies a photo. Photo references
* are returned from either a Place Search or Place Details request.
* @return Returns the configured PhotoRequest.
*/
public PhotoRequest photoReference(String photoReference) {
return param("photoreference", photoReference);
}
/**
* Sets the maxHeight for this request.
*
* @param maxHeight The maximum desired height, in pixels, of the image returned by the Place
* Photos service.
* @return Returns the configured PhotoRequest.
*/
public PhotoRequest maxHeight(int maxHeight) {
return param("maxheight", String.valueOf(maxHeight));
}
/**
* Sets the maxWidth for this request.
*
* @param maxWidth The maximum desired width, in pixels, of the image returned by the Place Photos
* service.
* @return Returns the configured PhotoRequest.
*/
public PhotoRequest maxWidth(int maxWidth) {
return param("maxwidth", String.valueOf(maxWidth));
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/PlaceAutocompleteRequest.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import static ai.nextbillion.maps.internal.StringJoin.join;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.StringJoin.UrlValue;
import ai.nextbillion.maps.model.AutocompletePrediction;
import ai.nextbillion.maps.model.ComponentFilter;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.PlaceAutocompleteType;
import com.google.gson.FieldNamingPolicy;
import java.io.Serializable;
import java.util.UUID;
/**
* A <a
* href="https://developers.google.com/places/web-service/autocomplete#place_autocomplete_requests">Place
* Autocomplete</a> request.
*/
public class PlaceAutocompleteRequest
extends PendingResultBase<
AutocompletePrediction[], PlaceAutocompleteRequest, PlaceAutocompleteRequest.Response> {
static final ApiConfig API_CONFIG =
new ApiConfig("/maps/api/place/autocomplete/json")
.fieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
protected PlaceAutocompleteRequest(GeoApiContext context) {
super(context, API_CONFIG, Response.class);
}
/** SessionToken represents an Autocomplete session. */
public static final class SessionToken implements UrlValue, Serializable {
private static final long serialVersionUID = 1L;
private final UUID uuid;
/** This constructor creates a new session. */
public SessionToken() {
uuid = UUID.randomUUID();
}
/**
* Construct a session that is a continuation of a previous session.
*
* @param uuid The universally unique identifier for this session.
*/
public SessionToken(UUID uuid) {
this.uuid = uuid;
}
/**
* Retrieve the universally unique identifier for this session. This enables you to recreate the
* session token in a later context.
*
* @return Returns the universally unique identifier for this session.
*/
public UUID getUUID() {
return uuid;
}
@Override
public String toUrlValue() {
return uuid.toString();
}
}
/**
* Sets the SessionToken for this request. Using session token makes sure the autocomplete is
* priced per session, instead of per keystroke.
*
* @param sessionToken Session Token is the session identifier.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest sessionToken(SessionToken sessionToken) {
return param("sessiontoken", sessionToken);
}
/**
* Sets the text string on which to search. The Places service will return candidate matches based
* on this string and order results based on their perceived relevance.
*
* @param input The input text to autocomplete.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest input(String input) {
return param("input", input);
}
/**
* The character position in the input term at which the service uses text for predictions. For
* example, if the input is 'Googl' and the completion point is 3, the service will match on
* 'Goo'. The offset should generally be set to the position of the text caret. If no offset is
* supplied, the service will use the entire term.
*
* @param offset The character offset position of the user's cursor.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest offset(int offset) {
return param("offset", String.valueOf(offset));
}
/**
* The origin point from which to calculate straight-line distance to the destination (returned as
* {@link AutocompletePrediction#distanceMeters}). If this value is omitted, straight-line
* distance will not be returned.
*
* @param origin The {@link LatLng} origin point from which to calculate distance.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest origin(LatLng origin) {
return param("origin", origin);
}
/**
* The point around which you wish to retrieve place information.
*
* @param location The {@link LatLng} location to center this autocomplete search.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest location(LatLng location) {
return param("location", location);
}
/**
* The distance (in meters) within which to return place results. Note that setting a radius
* biases results to the indicated area, but may not fully restrict results to the specified area.
*
* @param radius The radius over which to bias results.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest radius(int radius) {
return param("radius", String.valueOf(radius));
}
/**
* Restricts the results to places matching the specified type.
*
* @param type The type to restrict results to.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
* @deprecated Please use {@code types} instead.
*/
public PlaceAutocompleteRequest type(PlaceAutocompleteType type) {
return this.types(type);
}
/**
* Restricts the results to places matching the specified type.
*
* @param types The type to restrict results to.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest types(PlaceAutocompleteType types) {
return param("types", types);
}
/**
* A grouping of places to which you would like to restrict your results. Currently, you can use
* components to filter by country.
*
* @param filters The component filter to restrict results with.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest components(ComponentFilter... filters) {
return param("components", join('|', filters));
}
/**
* StrictBounds returns only those places that are strictly within the region defined by location
* and radius. This is a restriction, rather than a bias, meaning that results outside this region
* will not be returned even if they match the user input.
*
* @param strictBounds Whether to strictly bound results.
* @return Returns this {@code PlaceAutocompleteRequest} for call chaining.
*/
public PlaceAutocompleteRequest strictBounds(boolean strictBounds) {
return param("strictbounds", Boolean.toString(strictBounds));
}
@Override
protected void validateRequest() {
if (!params().containsKey("input")) {
throw new IllegalArgumentException("Request must contain 'input'.");
}
}
public static class Response implements ApiResponse<AutocompletePrediction[]> {
public String status;
public AutocompletePrediction[] predictions;
public String errorMessage;
@Override
public boolean successful() {
return "OK".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public AutocompletePrediction[] getResult() {
return predictions;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/QueryAutocompleteRequest.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.model.AutocompletePrediction;
import ai.nextbillion.maps.model.LatLng;
import com.google.gson.FieldNamingPolicy;
/**
* A <a
* href="https://developers.google.com/places/web-service/query#query_autocomplete_requests">Query
* Autocomplete</a> request.
*/
public class QueryAutocompleteRequest
extends PendingResultBase<
AutocompletePrediction[], QueryAutocompleteRequest, QueryAutocompleteRequest.Response> {
static final ApiConfig API_CONFIG =
new ApiConfig("/maps/api/place/queryautocomplete/json")
.fieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
protected QueryAutocompleteRequest(GeoApiContext context) {
super(context, API_CONFIG, Response.class);
}
@Override
protected void validateRequest() {
if (!params().containsKey("input")) {
throw new IllegalArgumentException("Request must contain 'input'.");
}
}
/**
* The text string on which to search. The Places service will return candidate matches based on
* this string and order results based on their perceived relevance.
*
* @param input The input text to autocomplete.
* @return Returns this {@code QueryAutocompleteRequest} for call chaining.
*/
public QueryAutocompleteRequest input(String input) {
return param("input", input);
}
/**
* The character position in the input term at which the service uses text for predictions. For
* example, if the input is 'Googl' and the completion point is 3, the service will match on
* 'Goo'. The offset should generally be set to the position of the text caret. If no offset is
* supplied, the service will use the entire term.
*
* @param offset The character offset to search from.
* @return Returns this {@code QueryAutocompleteRequest} for call chaining.
*/
public QueryAutocompleteRequest offset(int offset) {
return param("offset", String.valueOf(offset));
}
/**
* The point around which you wish to retrieve place information.
*
* @param location The location point around which to search.
* @return Returns this {@code QueryAutocompleteRequest} for call chaining.
*/
public QueryAutocompleteRequest location(LatLng location) {
return param("location", location);
}
/**
* The distance (in meters) within which to return place results. Note that setting a radius
* biases results to the indicated area, but may not fully restrict results to the specified area.
*
* @param radius The radius around which to bias results.
* @return Returns this {@code QueryAutocompleteRequest} for call chaining.
*/
public QueryAutocompleteRequest radius(int radius) {
return param("radius", String.valueOf(radius));
}
public static class Response implements ApiResponse<AutocompletePrediction[]> {
public String status;
public AutocompletePrediction[] predictions;
public String errorMessage;
@Override
public boolean successful() {
return "OK".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public AutocompletePrediction[] getResult() {
return predictions;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/RoadsApi.java
|
package ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.internal.StringJoin;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.SnappedPoint;
import com.google.gson.FieldNamingPolicy;
/**
* The Google Maps Roads API identifies the roads a vehicle was traveling along and provides
* additional metadata about those roads, such as speed limits.
*
* <p>See also: <a href="https://developers.google.com/maps/documentation/roads">Roads API
* documentation</a>.
*/
public class RoadsApi {
static final ApiConfig SNAP_TO_ROADS_API_CONFIG =
new ApiConfig("/snapToRoads/json").fieldNamingPolicy(FieldNamingPolicy.IDENTITY);
private RoadsApi() {}
/**
* Takes up to 100 GPS points collected along a route, and returns a similar set of data with the
* points snapped to the most likely roads the vehicle was traveling along.
*
* @param context The {@link GeoApiContext} to make requests through.
* @param path The collected GPS points as a path.
* @return Returns the snapped points as a {@link PendingResult}.
*/
public static PendingResult<SnappedPoint[]> snapToRoads(GeoApiContext context, LatLng... path) {
return context.get(
SNAP_TO_ROADS_API_CONFIG, RoadsResponse.class, "path", StringJoin.join('|', path));
}
public static class RoadsResponse implements ApiResponse<SnappedPoint[]> {
public String status;
public SnappedPoint[] snappedPoints;
public double distance;
public String errorMessage;
@Override
public boolean successful() {
return "Ok".equals(status);
}
@Override
public SnappedPoint[] getResult() {
return snappedPoints;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/TextSearchRequest.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.internal.ApiConfig;
import ai.nextbillion.maps.internal.ApiResponse;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.PlaceType;
import ai.nextbillion.maps.model.PlacesSearchResponse;
import ai.nextbillion.maps.model.PlacesSearchResult;
import ai.nextbillion.maps.model.PriceLevel;
import ai.nextbillion.maps.model.RankBy;
import com.google.gson.FieldNamingPolicy;
/**
* A <a href="https://developers.google.com/places/web-service/search#TextSearchRequests">Text
* Search</a> request.
*/
public class TextSearchRequest
extends PendingResultBase<PlacesSearchResponse, TextSearchRequest, TextSearchRequest.Response> {
static final ApiConfig API_CONFIG =
new ApiConfig("/maps/api/place/textsearch/json")
.fieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
public TextSearchRequest(GeoApiContext context) {
super(context, API_CONFIG, Response.class);
}
/**
* Specifies the text string on which to search, for example: {@code "restaurant"}.
*
* @param query The query string to search for.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest query(String query) {
return param("query", query);
}
/**
* Specifies the latitude/longitude around which to retrieve place information.
*
* @param location The location of the center of the search.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest location(LatLng location) {
return param("location", location);
}
/**
* Region used to influence search results. This parameter will only influence, not fully
* restrict, search results. If more relevant results exist outside of the specified region, they
* may be included. When this parameter is used, the country name is omitted from the resulting
* formatted_address for results in the specified region.
*
* @param region The ccTLD two-letter code of the region.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest region(String region) {
return param("region", region);
}
/**
* Specifies the distance (in meters) within which to bias place results.
*
* @param radius The radius of the search bias.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest radius(int radius) {
if (radius > 50000) {
throw new IllegalArgumentException("The maximum allowed radius is 50,000 meters.");
}
return param("radius", String.valueOf(radius));
}
/**
* Restricts to places that are at least this price level.
*
* @param priceLevel The minimum price level to restrict results with.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest minPrice(PriceLevel priceLevel) {
return param("minprice", priceLevel);
}
/**
* Restricts to places that are at most this price level.
*
* @param priceLevel The maximum price leve to restrict results with.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest maxPrice(PriceLevel priceLevel) {
return param("maxprice", priceLevel);
}
/**
* Specifies one or more terms to be matched against the names of places, separated with space
* characters.
*
* @param name The name to search for.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest name(String name) {
return param("name", name);
}
/**
* Restricts to only those places that are open for business at the time the query is sent.
*
* @param openNow Whether to restrict this search to open places.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest openNow(boolean openNow) {
return param("opennow", String.valueOf(openNow));
}
/**
* Returns the next 20 results from a previously run search. Setting pageToken will execute a
* search with the same parameters used previously — all parameters other than pageToken will be
* ignored.
*
* @param nextPageToken A {@code pageToken} from a prior result.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest pageToken(String nextPageToken) {
return param("pagetoken", nextPageToken);
}
/**
* Specifies the order in which results are listed.
*
* @param ranking The rank by method.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest rankby(RankBy ranking) {
return param("rankby", ranking);
}
/**
* Restricts the results to places matching the specified type.
*
* @param type The type of place to restrict the results with.
* @return Returns this {@code TextSearchRequest} for call chaining.
*/
public TextSearchRequest type(PlaceType type) {
return param("type", type);
}
@Override
protected void validateRequest() {
// All other parameters are ignored if pagetoken is specified.
if (params().containsKey("pagetoken")) {
return;
}
if (!params().containsKey("query") && !params().containsKey("type")) {
throw new IllegalArgumentException(
"Request must contain 'query' or a 'pageToken'. If a 'type' is specified 'query' becomes optional.");
}
if (params().containsKey("location") && !params().containsKey("radius")) {
throw new IllegalArgumentException(
"Request must contain 'radius' parameter when it contains a 'location' parameter.");
}
}
public static class Response implements ApiResponse<PlacesSearchResponse> {
public String status;
public String[] htmlAttributions;
public PlacesSearchResult[] results;
public String nextPageToken;
public String errorMessage;
@Override
public boolean successful() {
return "OK".equals(status) || "ZERO_RESULTS".equals(status);
}
@Override
public PlacesSearchResponse getResult() {
PlacesSearchResponse result = new PlacesSearchResponse();
result.htmlAttributions = htmlAttributions;
result.results = results;
result.nextPageToken = nextPageToken;
return result;
}
@Override
public ApiException getError() {
if (successful()) {
return null;
}
return ApiException.from(status, errorMessage);
}
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/AccessNotConfiguredException.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* Indicates that the API call was not configured for the supplied credentials and environmental
* conditions. Check the error message for details.
*/
public class AccessNotConfiguredException extends ApiException {
private static final long serialVersionUID = -9167434506751721386L;
public AccessNotConfiguredException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/ApiError.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/** An error returned by the API, including some extra information for aiding in debugging. */
public class ApiError {
public int code;
public String message;
public String status;
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/ApiException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* ApiException and its descendants represent an error returned by the remote API. API errors are
* determined by the {@code status} field returned in any of the Geo API responses.
*/
public class ApiException extends Exception {
private static final long serialVersionUID = -6550606366694345191L;
protected ApiException(String message) {
super(message);
}
/**
* Construct the appropriate ApiException from the response. If the response was successful, this
* method will return null.
*
* @param status The status field returned from the API
* @param errorMessage The error message returned from the API
* @return The appropriate ApiException based on the status or null if no error occurred.
*/
public static ApiException from(String status, String errorMessage) {
// Classic Geo API error formats
if ("OK".equals(status)) {
return null;
} else if ("INVALID_REQUEST".equals(status)) {
return new InvalidRequestException(errorMessage);
} else if ("MAX_ELEMENTS_EXCEEDED".equals(status)) {
return new MaxElementsExceededException(errorMessage);
} else if ("MAX_ROUTE_LENGTH_EXCEEDED".equals(status)) {
return new MaxRouteLengthExceededException(errorMessage);
} else if ("MAX_WAYPOINTS_EXCEEDED".equals(status)) {
return new MaxWaypointsExceededException(errorMessage);
} else if ("NOT_FOUND".equals(status)) {
return new NotFoundException(errorMessage);
} else if ("OVER_QUERY_LIMIT".equals(status)) {
if ("You have exceeded your daily request quota for this API."
.equalsIgnoreCase(errorMessage)) {
return new OverDailyLimitException(errorMessage);
}
return new OverQueryLimitException(errorMessage);
} else if ("REQUEST_DENIED".equals(status)) {
return new RequestDeniedException(errorMessage);
} else if ("UNKNOWN_ERROR".equals(status)) {
return new UnknownErrorException(errorMessage);
} else if ("ZERO_RESULTS".equals(status)) {
return new ZeroResultsException(errorMessage);
}
// New-style Geo API error formats
if ("ACCESS_NOT_CONFIGURED".equals(status)) {
return new AccessNotConfiguredException(errorMessage);
} else if ("INVALID_ARGUMENT".equals(status)) {
return new InvalidRequestException(errorMessage);
} else if ("RESOURCE_EXHAUSTED".equals(status)) {
return new OverQueryLimitException(errorMessage);
} else if ("PERMISSION_DENIED".equals(status)) {
return new RequestDeniedException(errorMessage);
}
// Geolocation Errors
if ("keyInvalid".equals(status)) {
return new AccessNotConfiguredException(errorMessage);
} else if ("dailyLimitExceeded".equals(status)) {
return new OverDailyLimitException(errorMessage);
} else if ("userRateLimitExceeded".equals(status)) {
return new OverQueryLimitException(errorMessage);
} else if ("notFound".equals(status)) {
return new NotFoundException(errorMessage);
} else if ("parseError".equals(status)) {
return new InvalidRequestException(errorMessage);
} else if ("invalid".equals(status)) {
return new InvalidRequestException(errorMessage);
}
// We've hit an unknown error. This is not a state we should hit,
// but we don't want to crash a user's application if we introduce a new error.
return new UnknownErrorException(
"An unexpected error occurred. Status: " + status + ", Message: " + errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/InvalidRequestException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/** Indicates that the API received a malformed request. */
public class InvalidRequestException extends ApiException {
private static final long serialVersionUID = -5682669561780594333L;
public InvalidRequestException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/MaxElementsExceededException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* Indicates that the product of origins and destinations exceeds the per-query limit.
*
* @see <a href="https://developers.google.com/maps/documentation/distance-matrix/usage-limits">
* Limits</a>
*/
public class MaxElementsExceededException extends ApiException {
private static final long serialVersionUID = 5926526363472768479L;
public MaxElementsExceededException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/MaxRouteLengthExceededException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* Indicates that the requested route is too long and cannot be processed.
*
* <p>This error occurs when more complex directions are returned. Try reducing the number of
* waypoints, turns, or instructions.
*
* @see <a href="https://developers.google.com/maps/documentation/directions/intro#StatusCodes">
* Status Codes</a>
*/
public class MaxRouteLengthExceededException extends ApiException {
private static final long serialVersionUID = 5926526363472768479L;
public MaxRouteLengthExceededException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/MaxWaypointsExceededException.java
|
/*
* Copyright 2019 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* Indicates that too many waypoints were provided in the request.
*
* @see <a href="https://developers.google.com/maps/documentation/directions/intro#StatusCodes">
* Status Codes</a>
*/
public class MaxWaypointsExceededException extends ApiException {
private static final long serialVersionUID = 1L;
public MaxWaypointsExceededException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/NotFoundException.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* Indicates at least one of the locations specified in the request's origin, destination, or
* waypoints could not be geocoded.
*/
public class NotFoundException extends ApiException {
private static final long serialVersionUID = -5447625132975504651L;
public NotFoundException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/OverDailyLimitException.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/** Indicates that the requesting account has exceeded its daily quota. */
public class OverDailyLimitException extends ApiException {
private static final long serialVersionUID = 9172790459877314621L;
public OverDailyLimitException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/OverQueryLimitException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/** Indicates that the requesting account has exceeded its short-term quota. */
public class OverQueryLimitException extends ApiException {
private static final long serialVersionUID = -6888513535435397042L;
public OverQueryLimitException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/RequestDeniedException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/** Indicates that the API denied the request. Check the message for more detail. */
public class RequestDeniedException extends ApiException {
private static final long serialVersionUID = -1434641617962369958L;
public RequestDeniedException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/UnknownErrorException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* Indicates that the server encountered an unknown error. In some cases these are safe to retry.
*/
public class UnknownErrorException extends ApiException {
private static final long serialVersionUID = -4588344280364816431L;
public UnknownErrorException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/errors/ZeroResultsException.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.errors;
/**
* Indicates that no results were returned.
*
* <p>In some cases, this will be treated as a success state and you will only see an empty array.
* For time zone data, it means that no time zone information could be found for the specified
* position or time. Confirm that the request is for a location on land, and not over water.
*/
public class ZeroResultsException extends ApiException {
private static final long serialVersionUID = -9096790004183184907L;
public ZeroResultsException(String errorMessage) {
super(errorMessage);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/ApiConfig.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import com.google.gson.FieldNamingPolicy;
/** API configuration builder. Defines fields that are variable per-API. */
public class ApiConfig {
public String path;
public FieldNamingPolicy fieldNamingPolicy = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES;
public String hostName = "https://api.nextbillion.io";
public boolean supportsClientId = true;
public String requestVerb = "GET";
public ApiConfig(String path) {
this.path = path;
}
public ApiConfig fieldNamingPolicy(FieldNamingPolicy fieldNamingPolicy) {
this.fieldNamingPolicy = fieldNamingPolicy;
return this;
}
public ApiConfig hostName(String hostName) {
this.hostName = hostName;
return this;
}
public ApiConfig supportsClientId(boolean supportsClientId) {
this.supportsClientId = supportsClientId;
return this;
}
public ApiConfig requestVerb(String requestVerb) {
this.requestVerb = requestVerb;
return this;
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/ApiResponse.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.errors.ApiException;
/** All Geo API responses implement this Interface. */
public interface ApiResponse<T> {
boolean successful();
T getResult();
ApiException getError();
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/DayOfWeekAdapter.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.OpeningHours.Period.OpenClose.DayOfWeek;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/**
* This class handles conversion from JSON to {@link DayOfWeek}.
*
* <p>Please see <a
* href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html">GSON
* Type Adapter</a> for more detail.
*/
public class DayOfWeekAdapter extends TypeAdapter<DayOfWeek> {
@Override
public DayOfWeek read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() == JsonToken.NUMBER) {
int day = reader.nextInt();
switch (day) {
case 0:
return DayOfWeek.SUNDAY;
case 1:
return DayOfWeek.MONDAY;
case 2:
return DayOfWeek.TUESDAY;
case 3:
return DayOfWeek.WEDNESDAY;
case 4:
return DayOfWeek.THURSDAY;
case 5:
return DayOfWeek.FRIDAY;
case 6:
return DayOfWeek.SATURDAY;
}
}
return DayOfWeek.UNKNOWN;
}
/** This method is not implemented. */
@Override
public void write(JsonWriter writer, DayOfWeek value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/DistanceAdapter.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.Distance;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/**
* This class handles conversion from JSON to {@link Distance}.
*
* <p>Please see <a
* href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html">GSON
* Type Adapter</a> for more detail.
*/
public class DistanceAdapter extends TypeAdapter<Distance> {
/**
* Read a distance object from a Directions API result and convert it to a {@link Distance}.
*
* <p>We are expecting to receive something akin to the following:
*
* <pre>
* {
* "value": 207, "text": "0.1 mi"
* }
* </pre>
*/
@Override
public Distance read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
Distance distance = new Distance();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("text")) {
distance.humanReadable = reader.nextString();
} else if (name.equals("value")) {
distance.inMeters = reader.nextLong();
}
}
reader.endObject();
return distance;
}
/** This method is not implemented. */
@Override
public void write(JsonWriter writer, Distance value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/DurationAdapter.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.Distance;
import ai.nextbillion.maps.model.Duration;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/**
* This class handles conversion from JSON to {@link Distance}.
*
* <p>Please see <a
* href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html">GSON
* Type Adapter</a> for more detail.
*/
public class DurationAdapter extends TypeAdapter<Duration> {
/**
* Read a distance object from a Directions API result and convert it to a {@link Distance}.
*
* <p>We are expecting to receive something akin to the following:
*
* <pre>
* {
* "value": 207,
* "text": "0.1 mi"
* }
* </pre>
*/
@Override
public Duration read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
Duration duration = new Duration();
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("text")) {
duration.humanReadable = reader.nextString();
} else if (name.equals("value")) {
duration.inSeconds = reader.nextLong();
}
}
reader.endObject();
return duration;
}
/** This method is not implemented. */
@Override
public void write(JsonWriter writer, Duration value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/EncodedPolylineInstanceCreator.java
|
/*
* Copyright 2017 by https://github.com/ArielY15
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.EncodedPolyline;
import com.google.gson.InstanceCreator;
import java.lang.reflect.Type;
public class EncodedPolylineInstanceCreator implements InstanceCreator<EncodedPolyline> {
private final String points;
public EncodedPolylineInstanceCreator(String points) {
this.points = points;
}
@Override
public EncodedPolyline createInstance(Type type) {
return new EncodedPolyline(points);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/ExceptionsAllowedToRetry.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.errors.ApiException;
import java.util.HashSet;
public final class ExceptionsAllowedToRetry extends HashSet<Class<? extends ApiException>> {
private static final long serialVersionUID = 5283992240187266422L;
@Override
public String toString() {
StringBuilder sb = new StringBuilder().append("ExceptionsAllowedToRetry[");
Object[] array = toArray();
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
if (i < array.length - 1) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString();
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/FareAdapter.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.Fare;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Currency;
/** This class handles conversion from JSON to {@link Fare}. */
public class FareAdapter extends TypeAdapter<Fare> {
/**
* Read a Fare object from the Directions API and convert to a {@link Fare}
*
* <pre>{
* "currency": "USD",
* "value": 6
* }</pre>
*/
@Override
public Fare read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
Fare fare = new Fare();
reader.beginObject();
while (reader.hasNext()) {
String key = reader.nextName();
if ("currency".equals(key)) {
fare.currency = Currency.getInstance(reader.nextString());
} else if ("value".equals(key)) {
// this relies on nextString() being able to coerce raw numbers to strings
fare.value = new BigDecimal(reader.nextString());
} else {
// Be forgiving of unexpected values
reader.skipValue();
}
}
reader.endObject();
return fare;
}
/** This method is not implemented. */
@Override
public void write(JsonWriter out, Fare value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/GaePendingResult.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.GeolocationApi;
import ai.nextbillion.maps.ImageResult;
import ai.nextbillion.maps.PendingResult;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.errors.UnknownErrorException;
import ai.nextbillion.maps.metrics.RequestMetrics;
import ai.nextbillion.maps.model.AddressComponentType;
import ai.nextbillion.maps.model.AddressType;
import ai.nextbillion.maps.model.Distance;
import ai.nextbillion.maps.model.Duration;
import ai.nextbillion.maps.model.EncodedPolyline;
import ai.nextbillion.maps.model.Fare;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.LocationType;
import ai.nextbillion.maps.model.OpeningHours.Period.OpenClose.DayOfWeek;
import ai.nextbillion.maps.model.PlaceDetails.Review.AspectRating.RatingType;
import ai.nextbillion.maps.model.PriceLevel;
import ai.nextbillion.maps.model.TravelMode;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A PendingResult backed by a HTTP call executed by Google App Engine URL Fetch capability, a
* deserialization step using Gson, and a retry policy.
*
* <p>{@code T} is the type of the result of this pending result, and {@code R} is the type of the
* request.
*/
public class GaePendingResult<T, R extends ApiResponse<T>> implements PendingResult<T> {
private final HTTPRequest request;
private final URLFetchService client;
private final Class<R> responseClass;
private final FieldNamingPolicy fieldNamingPolicy;
private final Integer maxRetries;
private final ExceptionsAllowedToRetry exceptionsAllowedToRetry;
private final RequestMetrics metrics;
private final long errorTimeOut;
private int retryCounter = 0;
private final long cumulativeSleepTime = 0;
private Future<HTTPResponse> call;
private static final Logger LOG = LoggerFactory.getLogger(GaePendingResult.class.getName());
private static final List<Integer> RETRY_ERROR_CODES = Arrays.asList(500, 503, 504);
/**
* @param request HTTP request to execute.
* @param client The client used to execute the request.
* @param responseClass Model class to unmarshal JSON body content.
* @param fieldNamingPolicy FieldNamingPolicy for unmarshaling JSON.
* @param errorTimeOut Number of milliseconds to re-send erroring requests.
* @param maxRetries Number of times allowed to re-send erroring requests.
* @param exceptionsAllowedToRetry exceptionsAllowedToRetry
* @param metrics metrics
*/
public GaePendingResult(
HTTPRequest request,
URLFetchService client,
Class<R> responseClass,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeOut,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics) {
this.request = request;
this.client = client;
this.responseClass = responseClass;
this.fieldNamingPolicy = fieldNamingPolicy;
this.errorTimeOut = errorTimeOut;
this.maxRetries = maxRetries;
this.exceptionsAllowedToRetry = exceptionsAllowedToRetry;
this.metrics = metrics;
metrics.startNetwork();
this.call = client.fetchAsync(request);
}
@Override
public void setCallback(Callback<T> callback) {
throw new RuntimeException("setCallback not implemented for Google App Engine");
}
@Override
public T await() throws ApiException, IOException, InterruptedException {
try {
HTTPResponse result = call.get();
metrics.endNetwork();
return parseResponse(this, result);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
// According to
// https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/URLFetchService
// all exceptions should be subclass of IOException so this should not happen.
throw new UnknownErrorException("Unexpected exception from " + e.getMessage());
}
}
}
@Override
public T awaitIgnoreError() {
try {
return await();
} catch (Exception e) {
return null;
}
}
@Override
public void cancel() {
call.cancel(true);
}
@SuppressWarnings("unchecked")
private T parseResponse(GaePendingResult<T, R> request, HTTPResponse response)
throws IOException, ApiException, InterruptedException {
try {
T result = parseResponseInternal(request, response);
metrics.endRequest(null, response.getResponseCode(), retryCounter);
return result;
} catch (Exception e) {
metrics.endRequest(e, response.getResponseCode(), retryCounter);
throw e;
}
}
@SuppressWarnings("unchecked")
private T parseResponseInternal(GaePendingResult<T, R> request, HTTPResponse response)
throws IOException, ApiException, InterruptedException {
if (shouldRetry(response)) {
// Retry is a blocking method, but that's OK. If we're here, we're either in an await()
// call, which is blocking anyway, or we're handling a callback in a separate thread.
return request.retry();
}
byte[] bytes = response.getContent();
R resp;
String contentType = null;
for (HTTPHeader header : response.getHeaders()) {
if (header.getName().equalsIgnoreCase("Content-Type")) {
contentType = header.getValue();
}
}
if (contentType != null
&& contentType.startsWith("image")
&& responseClass == ImageResult.Response.class
&& response.getResponseCode() == 200) {
ImageResult result = new ImageResult(contentType, bytes);
return (T) result;
}
Gson gson =
new GsonBuilder()
.registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter())
.registerTypeAdapter(Distance.class, new DistanceAdapter())
.registerTypeAdapter(Duration.class, new DurationAdapter())
.registerTypeAdapter(Fare.class, new FareAdapter())
.registerTypeAdapter(LatLng.class, new LatLngAdapter())
.registerTypeAdapter(
AddressComponentType.class, new SafeEnumAdapter<>(AddressComponentType.UNKNOWN))
.registerTypeAdapter(AddressType.class, new SafeEnumAdapter<>(AddressType.UNKNOWN))
.registerTypeAdapter(TravelMode.class, new SafeEnumAdapter<>(TravelMode.UNKNOWN))
.registerTypeAdapter(LocationType.class, new SafeEnumAdapter<>(LocationType.UNKNOWN))
.registerTypeAdapter(RatingType.class, new SafeEnumAdapter<>(RatingType.UNKNOWN))
.registerTypeAdapter(DayOfWeek.class, new DayOfWeekAdapter())
.registerTypeAdapter(PriceLevel.class, new PriceLevelAdapter())
.registerTypeAdapter(Instant.class, new InstantAdapter())
.registerTypeAdapter(LocalTime.class, new LocalTimeAdapter())
.registerTypeAdapter(GeolocationApi.Response.class, new GeolocationResponseAdapter())
.registerTypeAdapter(EncodedPolyline.class, new EncodedPolylineInstanceCreator(""))
.setFieldNamingPolicy(fieldNamingPolicy)
.create();
// Attempt to de-serialize before checking the HTTP status code, as there may be JSON in the
// body that we can use to provide a more descriptive exception.
try {
resp = gson.fromJson(new String(bytes, StandardCharsets.UTF_8), responseClass);
} catch (JsonSyntaxException e) {
// Check HTTP status for a more suitable exception
if (response.getResponseCode() > 399) {
// Some of the APIs return 200 even when the API request fails, as long as the transport
// mechanism succeeds. In these cases, INVALID_RESPONSE, etc are handled by the Gson
// parsing.
throw new IOException(
String.format(
"Server Error: %d %s",
response.getResponseCode(),
new String(response.getContent(), Charset.defaultCharset())));
}
// Otherwise just cough up the syntax exception.
throw e;
}
if (resp.successful()) {
// Return successful responses
return resp.getResult();
} else {
ApiException e = resp.getError();
if (shouldRetry(e)) {
// Retry over_query_limit errors
return request.retry();
} else {
// Throw anything else, including OQLs if we've spent too much time retrying
throw e;
}
}
}
private T retry() throws IOException, ApiException, InterruptedException {
retryCounter++;
LOG.info("Retrying request. Retry #{}", retryCounter);
metrics.startNetwork();
this.call = client.fetchAsync(request);
return this.await();
}
private boolean shouldRetry(HTTPResponse response) {
return RETRY_ERROR_CODES.contains(response.getResponseCode())
&& cumulativeSleepTime < errorTimeOut
&& (maxRetries == null || retryCounter < maxRetries);
}
private boolean shouldRetry(ApiException exception) {
return exceptionsAllowedToRetry.contains(exception.getClass())
&& cumulativeSleepTime < errorTimeOut
&& (maxRetries == null || retryCounter < maxRetries);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/GeolocationResponseAdapter.java
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.GeolocationApi;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
public class GeolocationResponseAdapter extends TypeAdapter<GeolocationApi.Response> {
/**
* Reads in a JSON object to create a Geolocation Response. See:
* https://developers.google.com/maps/documentation/geolocation/intro#responses
*
* <p>Success Case:
*
* <pre>
* {
* "location": {
* "lat": 51.0,
* "lng": -0.1
* },
* "accuracy": 1200.4
* }
* </pre>
*
* Error Case: The response contains an object with a single error object with the following keys:
*
* <p>code: This is the same as the HTTP status of the response. {@code message}: A short
* description of the error. {@code errors}: A list of errors which occurred. Each error contains
* an identifier for the type of error (the reason) and a short description (the message). For
* example, sending invalid JSON will return the following error:
*
* <pre>
* {
* "error": {
* "errors": [ {
* "domain": "geolocation",
* "reason": "notFound",
* "message": "Not Found",
* "debugInfo": "status: ZERO_RESULTS\ncom.google.api.server.core.Fault: Immu...
* }],
* "code": 404,
* "message": "Not Found"
* }
* }
* </pre>
*/
@Override
public GeolocationApi.Response read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
GeolocationApi.Response response = new GeolocationApi.Response();
LatLngAdapter latLngAdapter = new LatLngAdapter();
reader.beginObject(); // opening {
while (reader.hasNext()) {
String name = reader.nextName();
// two different objects could be returned a success object containing "location" and
// "accuracy" keys or an error object containing an "error" key
if (name.equals("location")) {
// we already have a parser for the LatLng object so lets use that
response.location = latLngAdapter.read(reader);
} else if (name.equals("accuracy")) {
response.accuracy = reader.nextDouble();
} else if (name.equals("error")) {
reader.beginObject(); // the error key leads to another object...
while (reader.hasNext()) {
String errName = reader.nextName();
// ...with keys "errors", "code" and "message"
if (errName.equals("code")) {
response.code = reader.nextInt();
} else if (errName.equals("message")) {
response.message = reader.nextString();
} else if (errName.equals("errors")) {
reader.beginArray(); // its plural because its an array of errors...
while (reader.hasNext()) {
reader.beginObject(); // ...and each error array element is an object...
while (reader.hasNext()) {
errName = reader.nextName();
// ...with keys "reason", "domain", "debugInfo", "location", "locationType", and
// "message" (again)
if (errName.equals("reason")) {
response.reason = reader.nextString();
} else if (errName.equals("domain")) {
response.domain = reader.nextString();
} else if (errName.equals("debugInfo")) {
response.debugInfo = reader.nextString();
} else if (errName.equals("message")) {
// have this already
reader.nextString();
} else if (errName.equals("location")) {
reader.nextString();
} else if (errName.equals("locationType")) {
reader.nextString();
}
}
reader.endObject();
}
reader.endArray();
}
}
reader.endObject(); // closing }
}
}
reader.endObject();
return response;
}
/** Not supported. */
@Override
public void write(JsonWriter out, GeolocationApi.Response value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method.");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/HttpHeaders.java
|
/*
* Copyright 2020 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
/** Contains HTTP header name constants. */
public final class HttpHeaders {
/** The HTTP {@code X-Goog-Maps-Experience-ID} header field name. */
public static final String X_GOOG_MAPS_EXPERIENCE_ID = "X-Goog-Maps-Experience-ID";
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/InstantAdapter.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.Instant;
/** This class handles conversion from JSON to {@link Instant}. */
public class InstantAdapter extends TypeAdapter<Instant> {
/** Read a time from the Places API and convert to a {@link Instant} */
@Override
public Instant read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() == JsonToken.NUMBER) {
// Number is the number of seconds since Epoch.
return Instant.ofEpochMilli(reader.nextLong() * 1000L);
}
throw new UnsupportedOperationException("Unsupported format");
}
/** This method is not implemented. */
@Override
public void write(JsonWriter out, Instant value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/LatLngAdapter.java
|
package ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.LatLng;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/** Handle conversion from varying types of latitude and longitude representations. */
public class LatLngAdapter extends TypeAdapter<LatLng> {
/**
* Reads in a JSON object and try to create a LatLng in one of the following formats.
*
* <pre>{
* "lat" : -33.8353684,
* "lng" : 140.8527069
* }
*
* {
* "latitude": -33.865257570508334,
* "longitude": 151.19287000481452
* }</pre>
*/
@Override
public LatLng read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
double lat = 0;
double lng = 0;
boolean hasLat = false;
boolean hasLng = false;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if ("lat".equals(name) || "latitude".equals(name)) {
lat = reader.nextDouble();
hasLat = true;
} else if ("lng".equals(name) || "longitude".equals(name)) {
lng = reader.nextDouble();
hasLng = true;
}
}
reader.endObject();
if (hasLat && hasLng) {
return new LatLng(lat, lng);
} else {
return null;
}
}
/** Not supported. */
@Override
public void write(JsonWriter out, LatLng value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method.");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/LocalTimeAdapter.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/** This class handles conversion from JSON to {@link LocalTime}. */
public class LocalTimeAdapter extends TypeAdapter<LocalTime> {
/** Read a time from the Places API and convert to a {@link LocalTime} */
@Override
public LocalTime read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() == JsonToken.STRING) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HHmm");
return LocalTime.parse(reader.nextString(), dtf);
}
throw new UnsupportedOperationException("Unsupported format");
}
/** This method is not implemented. */
@Override
public void write(JsonWriter out, LocalTime value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method");
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/OkHttpPendingResult.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.GeolocationApi;
import ai.nextbillion.maps.ImageResult;
import ai.nextbillion.maps.PendingResult;
import ai.nextbillion.maps.errors.ApiException;
import ai.nextbillion.maps.metrics.RequestMetrics;
import ai.nextbillion.maps.model.AddressComponentType;
import ai.nextbillion.maps.model.AddressType;
import ai.nextbillion.maps.model.Distance;
import ai.nextbillion.maps.model.Duration;
import ai.nextbillion.maps.model.Fare;
import ai.nextbillion.maps.model.LatLng;
import ai.nextbillion.maps.model.LocationType;
import ai.nextbillion.maps.model.OpeningHours.Period.OpenClose.DayOfWeek;
import ai.nextbillion.maps.model.PlaceDetails.Review.AspectRating.RatingType;
import ai.nextbillion.maps.model.PriceLevel;
import ai.nextbillion.maps.model.TravelMode;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A PendingResult backed by a HTTP call executed by OkHttp, a deserialization step using Gson, rate
* limiting and a retry policy.
*
* <p>{@code T} is the type of the result of this pending result, and {@code R} is the type of the
* request.
*/
public class OkHttpPendingResult<T, R extends ApiResponse<T>>
implements PendingResult<T>, Callback {
private final Request request;
private final OkHttpClient client;
private final Class<R> responseClass;
private final FieldNamingPolicy fieldNamingPolicy;
private final Integer maxRetries;
private final RequestMetrics metrics;
private Call call;
private Callback<T> callback;
private final long errorTimeOut;
private int retryCounter = 0;
private long cumulativeSleepTime = 0;
private final ExceptionsAllowedToRetry exceptionsAllowedToRetry;
private static final Logger LOG = LoggerFactory.getLogger(OkHttpPendingResult.class.getName());
private static final List<Integer> RETRY_ERROR_CODES = Arrays.asList(500, 503, 504);
/**
* @param request HTTP request to execute.
* @param client The client used to execute the request.
* @param responseClass Model class to unmarshal JSON body content.
* @param fieldNamingPolicy FieldNamingPolicy for unmarshaling JSON.
* @param errorTimeOut Number of milliseconds to re-send erroring requests.
* @param maxRetries Number of times allowed to re-send erroring requests.
* @param exceptionsAllowedToRetry The exceptions to retry.
* @param metrics metrics
*/
public OkHttpPendingResult(
Request request,
OkHttpClient client,
Class<R> responseClass,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeOut,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics) {
this.request = request;
this.client = client;
this.responseClass = responseClass;
this.fieldNamingPolicy = fieldNamingPolicy;
this.errorTimeOut = errorTimeOut;
this.maxRetries = maxRetries;
this.exceptionsAllowedToRetry = exceptionsAllowedToRetry;
this.metrics = metrics;
metrics.startNetwork();
this.call = client.newCall(request);
}
@Override
public void setCallback(Callback<T> callback) {
this.callback = callback;
call.enqueue(this);
}
/** Preserve a request/response pair through an asynchronous callback. */
private class QueuedResponse {
private final OkHttpPendingResult<T, R> request;
private final Response response;
private final IOException e;
public QueuedResponse(OkHttpPendingResult<T, R> request, Response response) {
this.request = request;
this.response = response;
this.e = null;
}
public QueuedResponse(OkHttpPendingResult<T, R> request, IOException e) {
this.request = request;
this.response = null;
this.e = e;
}
}
@Override
public T await() throws ApiException, IOException, InterruptedException {
// Handle sleeping for retried requests
if (retryCounter > 0) {
// 0.5 * (1.5 ^ i) represents an increased sleep time of 1.5x per iteration,
// starting at 0.5s when i = 0. The retryCounter will be 1 for the 1st retry,
// so subtract 1 here.
double delaySecs = 0.5 * Math.pow(1.5, retryCounter - 1);
// Generate a jitter value between -delaySecs / 2 and +delaySecs / 2
long delayMillis = (long) (delaySecs * (Math.random() + 0.5) * 1000);
LOG.debug(
String.format(
"Sleeping between errors for %dms (retry #%d, already slept %dms)",
delayMillis, retryCounter, cumulativeSleepTime));
cumulativeSleepTime += delayMillis;
try {
Thread.sleep(delayMillis);
} catch (InterruptedException e) {
// No big deal if we don't sleep as long as intended.
}
}
final BlockingQueue<QueuedResponse> waiter = new ArrayBlockingQueue<>(1);
final OkHttpPendingResult<T, R> parent = this;
// This callback will be called on another thread, handled by the RateLimitExecutorService.
// Calling call.execute() directly would bypass the rate limiting.
call.enqueue(
new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
metrics.endNetwork();
waiter.add(new QueuedResponse(parent, e));
}
@Override
public void onResponse(Call call, Response response) throws IOException {
metrics.endNetwork();
waiter.add(new QueuedResponse(parent, response));
}
});
QueuedResponse r = waiter.take();
if (r.response != null) {
return parseResponse(r.request, r.response);
} else {
metrics.endRequest(r.e, 0, retryCounter);
throw r.e;
}
}
@Override
public T awaitIgnoreError() {
try {
return await();
} catch (Exception e) {
return null;
}
}
@Override
public void cancel() {
call.cancel();
}
@Override
public void onFailure(Call call, IOException ioe) {
metrics.endNetwork();
if (callback != null) {
metrics.endRequest(ioe, 0, retryCounter);
callback.onFailure(ioe);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
metrics.endNetwork();
if (callback != null) {
try {
callback.onResult(parseResponse(this, response));
} catch (Exception e) {
callback.onFailure(e);
}
}
}
@SuppressWarnings("unchecked")
private T parseResponse(OkHttpPendingResult<T, R> request, Response response)
throws ApiException, InterruptedException, IOException {
try {
T result = parseResponseInternal(request, response);
metrics.endRequest(null, response.code(), retryCounter);
return result;
} catch (Exception e) {
metrics.endRequest(e, response.code(), retryCounter);
throw e;
}
}
@SuppressWarnings("unchecked")
private T parseResponseInternal(OkHttpPendingResult<T, R> request, Response response)
throws ApiException, InterruptedException, IOException {
if (shouldRetry(response)) {
// since we are retrying the request we must close the response
response.close();
// Retry is a blocking method, but that's OK. If we're here, we're either in an await()
// call, which is blocking anyway, or we're handling a callback in a separate thread.
return request.retry();
}
byte[] bytes;
try (ResponseBody body = response.body()) {
bytes = body.bytes();
}
R resp;
String contentType = response.header("Content-Type");
if (contentType != null
&& contentType.startsWith("image")
&& responseClass == ImageResult.Response.class
&& response.code() == 200) {
ImageResult result = new ImageResult(contentType, bytes);
return (T) result;
}
Gson gson =
new GsonBuilder()
.registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter())
.registerTypeAdapter(Distance.class, new DistanceAdapter())
.registerTypeAdapter(Duration.class, new DurationAdapter())
.registerTypeAdapter(Fare.class, new FareAdapter())
.registerTypeAdapter(LatLng.class, new LatLngAdapter())
.registerTypeAdapter(
AddressComponentType.class,
new SafeEnumAdapter<AddressComponentType>(AddressComponentType.UNKNOWN))
.registerTypeAdapter(
AddressType.class, new SafeEnumAdapter<AddressType>(AddressType.UNKNOWN))
.registerTypeAdapter(
TravelMode.class, new SafeEnumAdapter<TravelMode>(TravelMode.UNKNOWN))
.registerTypeAdapter(
LocationType.class, new SafeEnumAdapter<LocationType>(LocationType.UNKNOWN))
.registerTypeAdapter(
RatingType.class, new SafeEnumAdapter<RatingType>(RatingType.UNKNOWN))
.registerTypeAdapter(DayOfWeek.class, new DayOfWeekAdapter())
.registerTypeAdapter(PriceLevel.class, new PriceLevelAdapter())
.registerTypeAdapter(Instant.class, new InstantAdapter())
.registerTypeAdapter(LocalTime.class, new LocalTimeAdapter())
.registerTypeAdapter(GeolocationApi.Response.class, new GeolocationResponseAdapter())
.setFieldNamingPolicy(fieldNamingPolicy)
.create();
// Attempt to de-serialize before checking the HTTP status code, as there may be JSON in the
// body that we can use to provide a more descriptive exception.
try {
String json = new String(bytes, StandardCharsets.UTF_8);
resp = gson.fromJson(json, responseClass);
} catch (JsonSyntaxException e) {
// Check HTTP status for a more suitable exception
if (!response.isSuccessful()) {
// Some of the APIs return 200 even when the API request fails, as long as the transport
// mechanism succeeds. In these cases, INVALID_RESPONSE, etc are handled by the Gson
// parsing.
throw new IOException(
String.format("Server Error: %d %s", response.code(), response.message()));
}
// Otherwise just cough up the syntax exception.
throw e;
}
if (resp.successful()) {
// Return successful responses
return resp.getResult();
} else {
ApiException e = resp.getError();
if (shouldRetry(e)) {
return request.retry();
} else {
throw e;
}
}
}
private T retry() throws ApiException, InterruptedException, IOException {
retryCounter++;
LOG.info("Retrying request. Retry #" + retryCounter);
metrics.startNetwork();
this.call = client.newCall(request);
return this.await();
}
private boolean shouldRetry(Response response) {
return RETRY_ERROR_CODES.contains(response.code())
&& cumulativeSleepTime < errorTimeOut
&& (maxRetries == null || retryCounter < maxRetries);
}
private boolean shouldRetry(ApiException exception) {
return exceptionsAllowedToRetry.contains(exception.getClass())
&& cumulativeSleepTime < errorTimeOut
&& (maxRetries == null || retryCounter < maxRetries);
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/PolylineEncoding.java
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.LatLng;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Utility class that encodes and decodes Polylines.
*
* <p>See <a href="https://developers.google.com/maps/documentation/utilities/polylinealgorithm">
* https://developers.google.com/maps/documentation/utilities/polylinealgorithm</a> for detailed
* description of this format.
*/
public class PolylineEncoding {
public static List<LatLng> decode(final String encodedPath) {
int len = encodedPath.length();
final List<LatLng> path = new ArrayList<>(len / 2);
int index = 0;
int lat = 0;
int lng = 0;
while (index < len) {
int result = 1;
int shift = 0;
int b;
do {
b = encodedPath.charAt(index++) - 63 - 1;
result += b << shift;
shift += 5;
} while (b >= 0x1f);
lat += (result & 1) != 0 ? ~(result >> 1) : (result >> 1);
result = 1;
shift = 0;
do {
b = encodedPath.charAt(index++) - 63 - 1;
result += b << shift;
shift += 5;
} while (b >= 0x1f);
lng += (result & 1) != 0 ? ~(result >> 1) : (result >> 1);
path.add(new LatLng(lat * 1e-5, lng * 1e-5));
}
return path;
}
public static String encode(final List<LatLng> path) {
long lastLat = 0;
long lastLng = 0;
final StringBuilder result = new StringBuilder();
for (final LatLng point : path) {
long lat = Math.round(point.lat * 1e5);
long lng = Math.round(point.lng * 1e5);
long dLat = lat - lastLat;
long dLng = lng - lastLng;
encode(dLat, result);
encode(dLng, result);
lastLat = lat;
lastLng = lng;
}
return result.toString();
}
private static void encode(long v, StringBuilder result) {
v = v < 0 ? ~(v << 1) : v << 1;
while (v >= 0x20) {
result.append(Character.toChars((int) ((0x20 | (v & 0x1f)) + 63)));
v >>= 5;
}
result.append(Character.toChars((int) (v + 63)));
}
public static String encode(LatLng[] path) {
return encode(Arrays.asList(path));
}
}
|
0
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps
|
java-sources/ai/nextbillion/nb-maps-client/1.7.1/ai/nextbillion/maps/internal/PriceLevelAdapter.java
|
/*
* Copyright 2015 Google Inc. All rights reserved.
*
*
* 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 ai.nextbillion.maps.internal;
import ai.nextbillion.maps.model.PriceLevel;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/**
* This class handles conversion from JSON to {@link PriceLevel}.
*
* <p>Please see <a
* href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html">GSON
* Type Adapter</a> for more detail.
*/
public class PriceLevelAdapter extends TypeAdapter<PriceLevel> {
@Override
public PriceLevel read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() == JsonToken.NUMBER) {
int priceLevel = reader.nextInt();
switch (priceLevel) {
case 0:
return PriceLevel.FREE;
case 1:
return PriceLevel.INEXPENSIVE;
case 2:
return PriceLevel.MODERATE;
case 3:
return PriceLevel.EXPENSIVE;
case 4:
return PriceLevel.VERY_EXPENSIVE;
}
}
return PriceLevel.UNKNOWN;
}
/** This method is not implemented. */
@Override
public void write(JsonWriter writer, PriceLevel value) throws IOException {
throw new UnsupportedOperationException("Unimplemented method");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.