Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OkHttp3 & Retrofit2 #55

Merged
merged 3 commits into from
Jan 3, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,10 @@ repositories {
dependencies {
compile 'com.android.support:appcompat-v7:22.2.1@aar'
compile 'com.android.support:support-v4:22.2.1@aar'
compile 'com.squareup.okhttp:okhttp:1.5.2'
compile 'com.squareup.retrofit:retrofit:1.5.0'
compile 'com.squareup.okhttp3:okhttp:3.5.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'javax.annotation:javax.annotation-api:1.2'
compile 'com.github.frankiesardo:auto-parcel:0.3.1'
apt 'com.github.frankiesardo:auto-parcel-processor:0.3.1'
Expand Down
4 changes: 2 additions & 2 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version=1.0.1-SNAPSHOT
version=1.1.0-SNAPSHOT

GROUP=com.mapzen.android
VERSION_NAME=1.0.1-SNAPSHOT
VERSION_NAME=1.1.0-SNAPSHOT

POM_ARTIFACT_ID=pelias-android-sdk

Expand Down
77 changes: 39 additions & 38 deletions src/main/java/com/mapzen/pelias/Pelias.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,25 @@

import com.mapzen.pelias.gson.Result;

import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
* Main class for interaction with Pelias.
*/
public class Pelias {
public static final String DEFAULT_SEARCH_ENDPOINT = "https://search.mapzen.com/v1/";
public static final String DEFAULT_SEARCH_ENDPOINT = "https://search.mapzen.com/";

private PeliasService service;
private PeliasLocationProvider locationProvider;
private PeliasRequestHandler requestHandler;
private String endpoint = DEFAULT_SEARCH_ENDPOINT;
private RestAdapter.LogLevel logLevel = RestAdapter.LogLevel.NONE;
private RestAdapter restAdapter;
private boolean debug = false;
private Retrofit retrofit;
private RequestInterceptor requestInterceptor;

/**
* Constructs a {@link Pelias} object configured to use the default search endpoint for requests.
Expand All @@ -43,27 +46,26 @@ public Pelias(String url) {
}

private void initService() {
restAdapter = new RestAdapter.Builder()
.setEndpoint(endpoint)
.setLogLevel(logLevel)
.setRequestInterceptor(new RequestInterceptor() {
@Override public void intercept(RequestFacade request) {
if (requestHandler != null) {
if (requestHandler.headersForRequest() != null) {
for (String key : requestHandler.headersForRequest().keySet()) {
request.addHeader(key, requestHandler.headersForRequest().get(key));
}
}
if (requestHandler.queryParamsForRequest() != null) {
for (String key : requestHandler.queryParamsForRequest().keySet()) {
request.addQueryParam(key, requestHandler.queryParamsForRequest().get(key));
}
}
}
}
})
requestInterceptor = new RequestInterceptor();
if (requestHandler != null) {
requestInterceptor.setRequestHandler(requestHandler);
}

final OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.addNetworkInterceptor(requestInterceptor);

if (debug) {
final HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
clientBuilder.addNetworkInterceptor(logging);
}

retrofit = new Retrofit.Builder()
.baseUrl(endpoint)
.client(clientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
this.service = restAdapter.create(PeliasService.class);
this.service = retrofit.create(PeliasService.class);
}

/**
Expand All @@ -72,6 +74,9 @@ private void initService() {
*/
public void setRequestHandler(PeliasRequestHandler handler) {
requestHandler = handler;
if (requestInterceptor != null) {
requestInterceptor.setRequestHandler(handler);
}
}

/**
Expand All @@ -88,7 +93,7 @@ public void setEndpoint(String endpoint) {
* @param debug
*/
public void setDebug(boolean debug) {
this.logLevel = debug ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE;
this.debug = debug;
initService();
}

Expand All @@ -106,7 +111,7 @@ public void suggest(String query, Callback<Result> callback) {
* point for results The callback will be notified upon success or failure of the query.
*/
public void suggest(String query, double lat, double lon, Callback<Result> callback) {
service.getSuggest(query, lat, lon, callback);
service.getSuggest(query, lat, lon).enqueue(callback);
}

/**
Expand All @@ -124,8 +129,8 @@ public void search(String query, Callback<Result> callback) {
* the query.
*/
public void search(String query, BoundingBox box, Callback<Result> callback) {
service.getSearch(query, box.getMinLat(), box.getMinLon(), box.getMaxLat(), box.getMaxLon(),
callback);
service.getSearch(query, box.getMinLat(), box.getMinLon(), box.getMaxLat(), box.getMaxLon())
.enqueue(callback);
}

/**
Expand All @@ -134,23 +139,23 @@ public void search(String query, BoundingBox box, Callback<Result> callback) {
* the query.
*/
public void search(String query, double lat, double lon, Callback<Result> callback) {
service.getSearch(query, lat, lon, callback);
service.getSearch(query, lat, lon).enqueue(callback);
}

/**
* Issues a reverse geocode request given the lat/lon. The callback will be notified upon success
* or failure of the query.
*/
public void reverse(double lat, double lon, Callback<Result> callback) {
service.getReverse(lat, lon, callback);
service.getReverse(lat, lon).enqueue(callback);
}

/**
* Issues a place request for a given global identifier. The callback will be notified upon
* success or failure of the query.
*/
public void place(String gid, Callback<Result> callback) {
service.getPlace(gid, callback);
service.getPlace(gid).enqueue(callback);
}

/**
Expand All @@ -174,10 +179,6 @@ public String getEndpoint() {
* @return
*/
public boolean getDebug() {
if (restAdapter == null) {
return false;
}
return (restAdapter.getLogLevel() == RestAdapter.LogLevel.FULL);
return debug;
}

}
26 changes: 13 additions & 13 deletions src/main/java/com/mapzen/pelias/PeliasService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import com.mapzen.pelias.gson.Result;

import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Query;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
* HTTP interface for {@link Pelias}.
Expand All @@ -14,33 +14,33 @@ public interface PeliasService {
/**
* Asynchronously request autocomplete results given a query and focus point.
*/
@GET("/autocomplete") void getSuggest(@Query("text") String query,
@Query("focus.point.lat") double lat, @Query("focus.point.lon") double lon,
Callback<Result> callback);
@GET("/v1/autocomplete") Call<Result> getSuggest(@Query("text") String query,
@Query("focus.point.lat") double lat, @Query("focus.point.lon") double lon);

/**
* Asynchronously request search results given a query and bounding box.
*/
@GET("/search") void getSearch(@Query("text") String query,
@GET("/v1/search") Call<Result> getSearch(@Query("text") String query,
@Query("focus.viewport.min_lat") double minLat,
@Query("focus.viewport.min_lon") double minLon,
@Query("focus.viewport.max_lat") double maxLat,
@Query("focus.viewport.max_lon") double maxLon, Callback<Result> callback);
@Query("focus.viewport.max_lon") double maxLon);

/**
* Asynchronously request search results given a query and focus point.
*/
@GET("/search") void getSearch(@Query("text") String query, @Query("focus.point.lat") double lat,
@Query("focus.point.lon") double lon, Callback<Result> callback);
@GET("/v1/search") Call<Result> getSearch(@Query("text") String query,
@Query("focus.point.lat") double lat,
@Query("focus.point.lon") double lon);

/**
* Asynchronously issue reverse geocode request.
*/
@GET("/reverse") void getReverse(@Query("point.lat") double lat, @Query("point.lon") double lon,
Callback<Result> callback);
@GET("/v1/reverse") Call<Result> getReverse(@Query("point.lat") double lat,
@Query("point.lon") double lon);

/**
* Asynchronously request more information about places given their global unique identifiers.
*/
@GET("/place") void getPlace(@Query("ids") String ids, Callback<Result> callback);
@GET("/v1/place") Call<Result> getPlace(@Query("ids") String ids);
}
71 changes: 71 additions & 0 deletions src/main/java/com/mapzen/pelias/RequestInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.mapzen.pelias;

import java.io.IOException;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
* OkHttp3 style network interceptor to append client headers and query params to outgoing requests.
*/
class RequestInterceptor implements Interceptor {
private PeliasRequestHandler requestHandler;

/**
* Intercepts outgoing requests and makes modifications if a {@link PeliasRequestHandler} is set.
*/
@Override public Response intercept(Chain chain) throws IOException {
if (requestHandler != null) {
return modifyRequest(chain);
}

return chain.proceed(chain.request());
}

/**
* Modifies headers and query params for an outgoing request.
*/
private Response modifyRequest(Chain chain) throws IOException {
final Request originalRequest = chain.request();
final Request.Builder requestBuilder = originalRequest.newBuilder();
addHeaders(requestBuilder);
addQueryParams(requestBuilder, originalRequest);
return chain.proceed(requestBuilder.build());
}

/**
* Add custom headers to outgoing request.
*/
private void addHeaders(Request.Builder requestBuilder) {
final Map<String, String> headers = requestHandler.headersForRequest();
if (headers != null) {
for (String key : headers.keySet()) {
requestBuilder.header(key, headers.get(key));
}
}
}

/**
* Add custom query params to outgoing request.
*/
private void addQueryParams(Request.Builder requestBuilder, Request originalRequest) {
final Map<String, String> params = requestHandler.queryParamsForRequest();
if (params != null) {
for (String key : params.keySet()) {
final HttpUrl url = originalRequest
.url()
.newBuilder()
.addQueryParameter(key, params.get(key))
.build();
requestBuilder.url(url);
}
}
}

void setRequestHandler(PeliasRequestHandler requestHandler) {
this.requestHandler = requestHandler;
}
}
18 changes: 9 additions & 9 deletions src/main/java/com/mapzen/pelias/widget/PeliasSearchView.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@
import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.animation.AnimationUtils.loadAnimation;

Expand Down Expand Up @@ -236,9 +236,9 @@ private void fetchAutoCompleteSuggestions(String text) {
}

pelias.suggest(text, new Callback<Result>() {
@Override public void success(Result result, Response response) {
@Override public void onResponse(Call<Result> call, Response<Result> response) {
final ArrayList<AutoCompleteItem> items = new ArrayList<>();
final List<Feature> features = result.getFeatures();
final List<Feature> features = response.body().getFeatures();
for (Feature feature : features) {
items.add(new AutoCompleteItem(SimpleFeature.fromFeature(feature)));
}
Expand All @@ -253,8 +253,8 @@ private void fetchAutoCompleteSuggestions(String text) {
adapter.notifyDataSetChanged();
}

@Override public void failure(RetrofitError error) {
Log.e(TAG, "Unable to fetch autocomplete results", error);
@Override public void onFailure(Call<Result> call, Throwable t) {
Log.e(TAG, "Unable to fetch autocomplete results", t);
}
});
}
Expand Down Expand Up @@ -387,7 +387,7 @@ public void setAutoCompleteIconResourceId(int autoCompleteIconResourceId) {
public class OnItemClickHandler {

/**
* Returns a click listener to be used by the autcomplete list view. Listener handles setting
* Returns a click listener to be used by the autocomplete list view. Listener handles setting
* the search view's query, resetting the cursor position, clearing view focus, invoking the
* callback and saving the search term.
*/
Expand All @@ -409,7 +409,7 @@ public AdapterView.OnItemClickListener invoke() {
features.add(item.getSimpleFeature().toFeature());
result.setFeatures(features);
if (callback != null) {
callback.success(result, null);
callback.onResponse(null, Response.success(result));
}
storeSavedSearch(item.getText(), item.getSimpleFeature().toParcel());
}
Expand Down
Loading