Skip to content

Instantly share code, notes, and snippets.

@Heroes84
Created October 25, 2016 07:39
Show Gist options
  • Save Heroes84/41e06389045bbabda5ef94227cc13354 to your computer and use it in GitHub Desktop.
Save Heroes84/41e06389045bbabda5ef94227cc13354 to your computer and use it in GitHub Desktop.
Advanced Android training
package com.bignerdranch.android.nerdfinder.web;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.bignerdranch.android.nerdfinder.exception.UnauthorizedException;
import com.bignerdranch.android.nerdfinder.listener.VenueCheckInListener;
import com.bignerdranch.android.nerdfinder.listener.VenueSearchListener;
import com.bignerdranch.android.nerdfinder.model.TokenStore;
import com.bignerdranch.android.nerdfinder.model.Venue;
import com.bignerdranch.android.nerdfinder.model.VenueSearchResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class DataManager
{
private static final String TAG = "DataManager";
private static final String FOURSQUARE_ENDPOINT = "https://api.foursquare.com/v2/";
private static final String CLIENT_ID = "02B4MFMCELM0MBXYMJUJQRQA1I1SNRUDCXZ52RIOLQGRFQ5U";
private static final String CLIENT_SECRET = "GVYABSFGJ4MXZ24VFTUETIACI1ZSLLXOOSYUM2AJS0NY5PIW";
private static final String FOURSQUARE_VERSION = "20150406";
private static final String FOURSQUARE_MODE = "foursquare";
private static final String TEST_LAT_LNG = "33.759,-84.332";
private static final String OAUTH_ENDPOINT = "https://foursquare.com/oauth2/authenticate";
public static final String OAUTH_REDIRECT_URI = "https://www.bignerdranch.com";
private static final String SWARM_MODE = "swarm";
private List<Venue> mVenueList;
private List<VenueSearchListener> mSearchListenerList = new ArrayList<>();
private List<VenueCheckInListener> mCheckInListenerList = new ArrayList<>();
protected static DataManager sDataManager;
private static TokenStore sTokenStore;
private Context mContext;
private Retrofit mRetrofit;
private Retrofit mAuthenticatedRetrofit;
public static DataManager get(Context context)
{
if (sDataManager == null)
{
Gson gson = new GsonBuilder()
.registerTypeAdapter(VenueSearchResponse.class, new VenueListDeserializer())
.create();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(sRequestInterceptor)
.addInterceptor(loggingInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(FOURSQUARE_ENDPOINT)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
OkHttpClient authenticatedClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor(sAuthenticatedRequestInterceptor)
.addInterceptor(sAuthorizationInterceptor)
.build();
Retrofit authenticatedRetrofit = new Retrofit.Builder()
.baseUrl(FOURSQUARE_ENDPOINT)
.client(authenticatedClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
sDataManager = new DataManager(context, retrofit, authenticatedRetrofit);
}
return sDataManager;
}
protected DataManager(Context context, Retrofit retrofit, Retrofit authenticatedRetrofit)
{
mContext = context.getApplicationContext();
mRetrofit = retrofit;
mAuthenticatedRetrofit = authenticatedRetrofit;
sTokenStore = TokenStore.get(context);
}
public void fetchVenueSearch()
{
VenueInterface venueInterface = mRetrofit.create(VenueInterface.class);
venueInterface.venueSearch(TEST_LAT_LNG)
.enqueue(new Callback<VenueSearchResponse>()
{
@Override
public void onResponse(Call<VenueSearchResponse> call, Response<VenueSearchResponse> response)
{
int code = response.code();
if(code == HttpURLConnection.HTTP_OK)
{
mVenueList = response.body().getVenueList();
notifySearchListeners();
}
else
{
Log.e(TAG, "Bad request code=" + code);
}
}
@Override
public void onFailure(Call<VenueSearchResponse> call, Throwable t)
{
Log.e(TAG, "Failed to fetch venue search", t);
}
});
}
public void checkInToVenue(String venueId)
{
VenueInterface venueInterface = mAuthenticatedRetrofit.create(VenueInterface.class);
venueInterface.venueCheckIn(venueId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> notifyCheckinListners(),
error -> handleCheckInExeption(error)
);
}
private void handleCheckInExeption(Throwable error)
{
if (error instanceof UnauthorizedException)
{
sTokenStore.setAccessToken(null);
notifyCheckInListenersTokenExpired();
}
}
private void notifyCheckInListenersTokenExpired()
{
for (VenueCheckInListener listener : mCheckInListenerList)
{
listener.onTokenExpired();
}
}
private void notifyCheckinListners()
{
for (VenueCheckInListener listener : mCheckInListenerList)
{
listener.onVenueCheckInFinished();
}
}
private void notifySearchListeners()
{
for(VenueSearchListener listener : mSearchListenerList)
{
listener.onVenueSearchFinished();
}
}
public void addVenueSearchListener(VenueSearchListener listener)
{
mSearchListenerList.add(listener);
}
public void removeVenueSearchListener(VenueSearchListener listener)
{
mSearchListenerList.remove(listener);
}
public void addVenueCheckInListener(VenueCheckInListener listener)
{
mCheckInListenerList.add(listener);
}
public void removeVenueCheckInListener(VenueCheckInListener listener)
{
mCheckInListenerList.remove(listener);
}
public List<Venue> getVenueList()
{
return mVenueList;
}
public String getAuthenticationUrl()
{
return Uri
.parse(OAUTH_ENDPOINT)
.buildUpon()
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("response_type", "token")
.appendQueryParameter("redirect_uri", OAUTH_REDIRECT_URI)
.build()
.toString();
}
public Venue getVenue(String venueId)
{
for (Venue venue : mVenueList)
{
if (venue.getId().equals(venueId))
{
return venue;
}
}
return null;
}
private static Interceptor sRequestInterceptor = new Interceptor()
{
@Override
public okhttp3.Response intercept(Chain chain) throws IOException
{
HttpUrl url = chain
.request()
.url()
.newBuilder()
.addQueryParameter("client_id", CLIENT_ID)
.addQueryParameter("client_secret", CLIENT_SECRET)
.addQueryParameter("v", FOURSQUARE_VERSION)
.addQueryParameter("m", FOURSQUARE_MODE)
.build();
Request request = chain.request().newBuilder().url(url).build();
return chain.proceed(request);
}
};
private static Interceptor sAuthenticatedRequestInterceptor = new Interceptor()
{
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
HttpUrl url = chain.request().url().newBuilder()
.addQueryParameter("oauth_token", sTokenStore.getAccessToken())
.addQueryParameter("v", FOURSQUARE_VERSION)
.addQueryParameter("m", SWARM_MODE)
.build();
Request request = chain.request().newBuilder()
.url(url)
.build();
return chain.proceed(request);
}
};
private static Interceptor sAuthorizationInterceptor = new Interceptor()
{
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response response = chain.proceed(chain.request());
if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new UnauthorizedException();
}
return response;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment