Commit 8967be74 by Kunj

Fixed -

1. Implemented Refresh API.
2. Added Question choice related issue.
3. Added logout button.
4. Handled access token expire issue.
parent 9754760c
Showing with 708 additions and 272 deletions
...@@ -34,7 +34,7 @@ android { ...@@ -34,7 +34,7 @@ android {
minSdkVersion 9 minSdkVersion 9
targetSdkVersion 24 targetSdkVersion 24
versionCode 1 versionCode 1
versionName "0.0.21" versionName "0.0.22"
multiDexEnabled true multiDexEnabled true
} }
buildTypes { buildTypes {
......
package com.vsoft.uoflservicenow; package com.vsoft.uoflservicenow;
import android.app.Application; import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics; import com.crashlytics.android.Crashlytics;
import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker; import com.google.android.gms.analytics.Tracker;
import com.vsoft.uoflservicenow.ui.LoginScreen;
import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Fabric;
public class CatalogueApplication extends Application { public class CatalogueApplication extends Application {
...@@ -16,12 +26,41 @@ public class CatalogueApplication extends Application { ...@@ -16,12 +26,41 @@ public class CatalogueApplication extends Application {
private static Context mContext; private static Context mContext;
private Tracker mTracker; private Tracker mTracker;
private BroadcastReceiver mSyncBroadCastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra(Constants.APPLICATION_BROADCAST_DATA_ACTION);
Log.d(Constants.TAG, "CatalogueApplication: onReceive: action: "+action);
if(Constants.ACTION_PROMPT_LOGIN.equals(action)) {
Toast.makeText(CatalogueApplication.this, R.string.prompt_relogin_login_expired, Toast.LENGTH_SHORT).show();
PrefManager.setSharedPref(CatalogueApplication.this, PrefManager.PREFERENCE_ACCESS_TOKEN, "");
PrefManager.setSharedPref(CatalogueApplication.this, PrefManager.PREFERENCE_REFRESH_TOKEN, "");
PrefManager.setSharedPref(CatalogueApplication.this, PrefManager.PREFERENCE_LAST_NAME, "");
PrefManager.setSharedPref(CatalogueApplication.this, PrefManager.PREFERENCE_SYS_ID, "");
PrefManager.setSharedPref(CatalogueApplication.this, PrefManager.PREFERENCE_FIRST_NAME, "");
PrefManager.setSharedPref(CatalogueApplication.this, PrefManager.PREFERENCE_USER_ID, "");
PrefManager.setSharedPref(CatalogueApplication.this, PrefManager.PREFERENCE_USER_FULL_NAME, "");
Intent loginIntent = new Intent(CatalogueApplication.this, LoginScreen.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
}
}
};
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
Fabric.with(this, new Crashlytics()); Fabric.with(this, new Crashlytics());
mContext = getApplicationContext(); mContext = getApplicationContext();
LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadCastReceiver,
new IntentFilter(Constants.APPLICATION_BROADCAST_INTENT));
}
@Override
public void onTerminate() {
super.onTerminate();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadCastReceiver);
} }
public static Context getContext() { public static Context getContext() {
......
package com.vsoft.uoflservicenow.api; package com.vsoft.uoflservicenow.api;
import android.util.Base64; import android.text.TextUtils;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
...@@ -22,8 +22,7 @@ import retrofit2.converter.gson.GsonConverterFactory; ...@@ -22,8 +22,7 @@ import retrofit2.converter.gson.GsonConverterFactory;
public class RestClient { public class RestClient {
public static Retrofit getInitializedRestAdapter(String username, String password) { public static Retrofit getInitializedRestAdapter(final String accessToken) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level // set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY); logging.setLevel(HttpLoggingInterceptor.Level.BODY);
...@@ -31,17 +30,19 @@ public class RestClient { ...@@ -31,17 +30,19 @@ public class RestClient {
.connectTimeout(10, TimeUnit.SECONDS) .connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS); .readTimeout(30, TimeUnit.SECONDS);
String credentials = username + ":" + password;
final String basic =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
// add your other interceptors // add your other interceptors
Interceptor interceptor = new Interceptor() { Interceptor interceptor = new Interceptor() {
@Override @Override
public Response intercept(Chain chain) { public Response intercept(Chain chain) {
Request original = chain.request(); Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder() Request.Builder requestBuilder = original.newBuilder();
.header(Constants.API_HEADER_PARAM_AUTHORIZATION, basic);
if(!TextUtils.isEmpty(accessToken)) {
final String bearer = "Bearer " + accessToken;
requestBuilder.header(Constants.API_HEADER_PARAM_AUTHORIZATION, bearer);
}
requestBuilder.header("Accept", "application/json"); requestBuilder.header("Accept", "application/json");
requestBuilder.header("Content-Type", "application/json"); requestBuilder.header("Content-Type", "application/json");
requestBuilder.method(original.method(), original.body()); requestBuilder.method(original.method(), original.body());
......
...@@ -30,8 +30,7 @@ public interface CatalogueVariableApi { ...@@ -30,8 +30,7 @@ public interface CatalogueVariableApi {
// Get Variable Choices API // Get Variable Choices API
@GET(Constants.URL_GET_VARIABLE_CHOICE) @GET(Constants.URL_GET_VARIABLE_CHOICE)
Call<ResponseBody> getVariableChoice(@Query(Constants.URL_PARAM_SYSPRM_QUERY) String sysparmQuery, Call<ResponseBody> getVariableChoice(@Query(Constants.URL_PARAM_SYS_ID) String sysId);
@Query(Constants.URL_PARAM_SYSPRM_FIELDS) String sysParmFields);
// Post catalogue item API // Post catalogue item API
@POST(Constants.URL_POST_CATALOGUE_ITEM) @POST(Constants.URL_POST_CATALOGUE_ITEM)
......
package com.vsoft.uoflservicenow.api.interfaces; package com.vsoft.uoflservicenow.api.interfaces;
import com.vsoft.uoflservicenow.db.models.LoginItem; import com.vsoft.uoflservicenow.api.pojos.LoginApiResponse;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import okhttp3.ResponseBody; import okhttp3.ResponseBody;
...@@ -20,9 +20,19 @@ public interface LoginApi { ...@@ -20,9 +20,19 @@ public interface LoginApi {
// Post Login item API // Post Login item API
@FormUrlEncoded @FormUrlEncoded
@POST(Constants.URL_POST_LOGIN_ITEM) @POST(Constants.URL_POST_LOGIN_ITEM)
Call<ResponseBody> postLoginValues(@Field(LoginItem.Json.GRANT_TYPE) String grantType, @Field(LoginItem.Json.CLIENT_ID) String clientId, Call<ResponseBody> postLoginValues(@Field(LoginApiResponse.Json.GRANT_TYPE) String grantType,
@Field(LoginItem.Json.CLIENT_CECRET) String clientSecret, @Field(LoginItem.Json.USER_NAME) String userName, @Field(LoginApiResponse.Json.CLIENT_ID) String clientId,
@Field(LoginItem.Json.PASSWORD) String password); @Field(LoginApiResponse.Json.CLIENT_SECRET) String clientSecret,
@Field(LoginApiResponse.Json.USER_NAME) String userName,
@Field(LoginApiResponse.Json.PASSWORD) String password);
@FormUrlEncoded
@POST(Constants.URL_REFRESH_LOGIN)
Call<ResponseBody> refreshLogin(@Field(LoginApiResponse.Json.GRANT_TYPE) String grantType,
@Field(LoginApiResponse.Json.CLIENT_ID) String clientId,
@Field(LoginApiResponse.Json.CLIENT_SECRET) String clientSecret,
@Field(LoginApiResponse.Json.REFRESH_TOKEN) String refreshToken);
} }
package com.vsoft.uoflservicenow.api.listeners.get; package com.vsoft.uoflservicenow.api.listeners.get;
import com.vsoft.uoflservicenow.api.pojos.LoginApiResponse;
/** /**
* @since 1.0 * @since 1.0
* @author Kunj on 11/8/16 * @author Kunj on 11/8/16
* *
*/ */
public interface GetUserLoginApiListener { public interface GetUserLoginApiListener {
void onDoneApiCall(); void onDoneApiCall(LoginApiResponse loginApiResponse);
void onFailApiCall(); void onFailApiCall();
} }
package com.vsoft.uoflservicenow.api.managers; package com.vsoft.uoflservicenow.api.managers;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
...@@ -12,8 +15,10 @@ import com.vsoft.uoflservicenow.api.listeners.get.GetCatalogueApiListener; ...@@ -12,8 +15,10 @@ import com.vsoft.uoflservicenow.api.listeners.get.GetCatalogueApiListener;
import com.vsoft.uoflservicenow.api.listeners.get.GetCatalogueOrderApiListener; import com.vsoft.uoflservicenow.api.listeners.get.GetCatalogueOrderApiListener;
import com.vsoft.uoflservicenow.db.models.Catalogue; import com.vsoft.uoflservicenow.db.models.Catalogue;
import com.vsoft.uoflservicenow.db.models.CatalogueOrder; import com.vsoft.uoflservicenow.db.models.CatalogueOrder;
import com.vsoft.uoflservicenow.enums.SyncStatus;
import com.vsoft.uoflservicenow.utils.CatalogueLog; import com.vsoft.uoflservicenow.utils.CatalogueLog;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
...@@ -37,7 +42,7 @@ import retrofit2.Retrofit; ...@@ -37,7 +42,7 @@ import retrofit2.Retrofit;
*/ */
public class CatalogueApiManager { public class CatalogueApiManager {
public static void getCatalogues(final GetCatalogueApiListener listener) { public static void getCatalogues(Context context, final GetCatalogueApiListener listener) {
CatalogueLog.d("CatalogueApiManager: getCatalogues: "); CatalogueLog.d("CatalogueApiManager: getCatalogues: ");
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(Catalogue.Json.URL_PARAM_CATALOGUE_SYSPRM_QUERY_VALUE); stringBuilder.append(Catalogue.Json.URL_PARAM_CATALOGUE_SYSPRM_QUERY_VALUE);
...@@ -45,7 +50,12 @@ public class CatalogueApiManager { ...@@ -45,7 +50,12 @@ public class CatalogueApiManager {
stringBuilder.append("^active=true"); stringBuilder.append("^active=true");
CatalogueLog.d("CatalogueApiManager: getCatalogues: request parameter: "+stringBuilder.toString()); CatalogueLog.d("CatalogueApiManager: getCatalogues: request parameter: "+stringBuilder.toString());
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(CatalogueCategoryApi.class).getCatalogue(stringBuilder.toString(), "sys_id,title,description,homepage_image", "true"); Call<ResponseBody> call = retrofit.create(CatalogueCategoryApi.class).getCatalogue(stringBuilder.toString(), "sys_id,title,description,homepage_image", "true");
try { try {
//Retrofit synchronous call //Retrofit synchronous call
...@@ -105,7 +115,7 @@ public class CatalogueApiManager { ...@@ -105,7 +115,7 @@ public class CatalogueApiManager {
catalogueList.add(catalogue); catalogueList.add(catalogue);
} }
if(!catalogueList.isEmpty()) { if(!catalogueList.isEmpty()) {
getCatalogueOrder(new GetCatalogueOrderApiListener() { getCatalogueOrder(context, new GetCatalogueOrderApiListener() {
@Override @Override
public void onDoneApiCall(List<CatalogueOrder> catalogueOrderList) { public void onDoneApiCall(List<CatalogueOrder> catalogueOrderList) {
for (int i = 0; i<catalogueOrderList.size(); i++) { for (int i = 0; i<catalogueOrderList.size(); i++) {
...@@ -142,7 +152,20 @@ public class CatalogueApiManager { ...@@ -142,7 +152,20 @@ public class CatalogueApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} else { } else {
listener.onFailApiCall(); CatalogueLog.d("CatalogueApiManager: getCatalogues: response is not success");
if(response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
Log.d(Constants.TAG, "refresh token: "+PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if(status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
getCatalogues(context, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
}
} else {
listener.onFailApiCall();
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("CatalogueApiManager: getCatalogues: IOException: ", e); CatalogueLog.e("CatalogueApiManager: getCatalogues: IOException: ", e);
...@@ -153,10 +176,15 @@ public class CatalogueApiManager { ...@@ -153,10 +176,15 @@ public class CatalogueApiManager {
} }
} }
public static void getCatalogueOrder(GetCatalogueOrderApiListener listener) { public static void getCatalogueOrder(Context context, GetCatalogueOrderApiListener listener) {
CatalogueLog.d("CatalogueApiManager: getCatalogueOrder: "); CatalogueLog.d("CatalogueApiManager: getCatalogueOrder: ");
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(CatalogueCategoryApi.class).getCatalogueOrder(); Call<ResponseBody> call = retrofit.create(CatalogueCategoryApi.class).getCatalogueOrder();
try { try {
//Retrofit synchronous call //Retrofit synchronous call
...@@ -237,8 +265,21 @@ public class CatalogueApiManager { ...@@ -237,8 +265,21 @@ public class CatalogueApiManager {
CatalogueLog.e("CatalogueApiManager: getCatalogueOrder: onResponse: ", e); CatalogueLog.e("CatalogueApiManager: getCatalogueOrder: onResponse: ", e);
listener.onFailApiCall(); listener.onFailApiCall();
} }
} else { } else {
listener.onFailApiCall(); CatalogueLog.d("CatalogueApiManager: getCatalogueOrder: response is not success");
if(response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
Log.d(Constants.TAG, "refresh token: "+PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if(status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
getCatalogueOrder(context, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
}
} else {
listener.onFailApiCall();
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("CatalogueApiManager: getCatalogueOrder: IOException: ", e); CatalogueLog.e("CatalogueApiManager: getCatalogueOrder: IOException: ", e);
...@@ -248,4 +289,4 @@ public class CatalogueApiManager { ...@@ -248,4 +289,4 @@ public class CatalogueApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} }
} }
\ No newline at end of file
package com.vsoft.uoflservicenow.api.managers; package com.vsoft.uoflservicenow.api.managers;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
...@@ -10,8 +13,10 @@ import com.vsoft.uoflservicenow.api.RestClient; ...@@ -10,8 +13,10 @@ import com.vsoft.uoflservicenow.api.RestClient;
import com.vsoft.uoflservicenow.api.interfaces.CatalogueCategoryItemApi; import com.vsoft.uoflservicenow.api.interfaces.CatalogueCategoryItemApi;
import com.vsoft.uoflservicenow.api.listeners.get.GetCatalogueItemApiListener; import com.vsoft.uoflservicenow.api.listeners.get.GetCatalogueItemApiListener;
import com.vsoft.uoflservicenow.db.models.CatalogueItem; import com.vsoft.uoflservicenow.db.models.CatalogueItem;
import com.vsoft.uoflservicenow.enums.SyncStatus;
import com.vsoft.uoflservicenow.utils.CatalogueLog; import com.vsoft.uoflservicenow.utils.CatalogueLog;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
...@@ -33,7 +38,7 @@ import retrofit2.Retrofit; ...@@ -33,7 +38,7 @@ import retrofit2.Retrofit;
*/ */
public class CatalogueItemApiManager { public class CatalogueItemApiManager {
public static void getCatalogueItems(String catalogueSysId, GetCatalogueItemApiListener listener) { public static void getCatalogueItems(Context context, String catalogueSysId, GetCatalogueItemApiListener listener) {
CatalogueLog.d("CatalogueItemApiManager: getCatalogueItems: "); CatalogueLog.d("CatalogueItemApiManager: getCatalogueItems: ");
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(CatalogueItem.Json.URL_PARAM_CATALOGUE_SYSPRM_QUERY_VALUE); stringBuilder.append(CatalogueItem.Json.URL_PARAM_CATALOGUE_SYSPRM_QUERY_VALUE);
...@@ -42,7 +47,12 @@ public class CatalogueItemApiManager { ...@@ -42,7 +47,12 @@ public class CatalogueItemApiManager {
stringBuilder.append("^active=true"); stringBuilder.append("^active=true");
CatalogueLog.d("CatalogueItemApiManager: getCatalogueItems: request parameter: "+stringBuilder.toString()); CatalogueLog.d("CatalogueItemApiManager: getCatalogueItems: request parameter: "+stringBuilder.toString());
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(CatalogueCategoryItemApi.class).getCatalogueItem(stringBuilder.toString(), "sys_id,short_description,name,description,icon", "true"); Call<ResponseBody> call = retrofit.create(CatalogueCategoryItemApi.class).getCatalogueItem(stringBuilder.toString(), "sys_id,short_description,name,description,icon", "true");
try { try {
//Retrofit synchronous call //Retrofit synchronous call
...@@ -114,7 +124,20 @@ public class CatalogueItemApiManager { ...@@ -114,7 +124,20 @@ public class CatalogueItemApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} else { } else {
listener.onFailApiCall(); CatalogueLog.d("CatalogueItemApiManager: getCatalogueItems: response is not success");
if (response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
Log.d(Constants.TAG, "refresh token: " + PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if (status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
getCatalogueItems(context, catalogueSysId, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
}
} else {
listener.onFailApiCall();
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("CatalogueItemApiManager: getCatalogueItems: IOException: ", e); CatalogueLog.e("CatalogueItemApiManager: getCatalogueItems: IOException: ", e);
...@@ -124,4 +147,4 @@ public class CatalogueItemApiManager { ...@@ -124,4 +147,4 @@ public class CatalogueItemApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} }
} }
\ No newline at end of file
package com.vsoft.uoflservicenow.api.managers; package com.vsoft.uoflservicenow.api.managers;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
...@@ -11,8 +14,10 @@ import com.vsoft.uoflservicenow.api.interfaces.IncidentApi; ...@@ -11,8 +14,10 @@ import com.vsoft.uoflservicenow.api.interfaces.IncidentApi;
import com.vsoft.uoflservicenow.api.listeners.get.GetIncidentApiListener; import com.vsoft.uoflservicenow.api.listeners.get.GetIncidentApiListener;
import com.vsoft.uoflservicenow.api.listeners.post.PostIncidentApiListener; import com.vsoft.uoflservicenow.api.listeners.post.PostIncidentApiListener;
import com.vsoft.uoflservicenow.db.models.Incident; import com.vsoft.uoflservicenow.db.models.Incident;
import com.vsoft.uoflservicenow.enums.SyncStatus;
import com.vsoft.uoflservicenow.utils.CatalogueLog; import com.vsoft.uoflservicenow.utils.CatalogueLog;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
...@@ -34,13 +39,19 @@ import retrofit2.Retrofit; ...@@ -34,13 +39,19 @@ import retrofit2.Retrofit;
*/ */
public class IncidentApiManager { public class IncidentApiManager {
public static void getIncident(GetIncidentApiListener listener) { public static void getIncident(Context context, GetIncidentApiListener listener) {
CatalogueLog.d("IncidentApiManager: getIncident: "); CatalogueLog.d("IncidentApiManager: getIncident: ");
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("caller_id=javascript:gs.getUserID()"); stringBuilder.append("caller_id=javascript:gs.getUserID()");
CatalogueLog.d("IncidentApiManager: getIncident: request parameter: "+stringBuilder.toString()); CatalogueLog.d("IncidentApiManager: getIncident: request parameter: "+stringBuilder.toString());
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(IncidentApi.class).getIncident(stringBuilder.toString(), ""); Call<ResponseBody> call = retrofit.create(IncidentApi.class).getIncident(stringBuilder.toString(), "");
try { try {
//Retrofit synchronous call //Retrofit synchronous call
...@@ -113,7 +124,20 @@ public class IncidentApiManager { ...@@ -113,7 +124,20 @@ public class IncidentApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} else { } else {
listener.onFailApiCall(); CatalogueLog.d("IncidentApiManager: getIncident: response is not success");
if (response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
Log.d(Constants.TAG, "refresh token: " + PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if (status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
getIncident(context, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
}
} else {
listener.onFailApiCall();
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("IncidentApiManager: getIncident: IOException: ", e); CatalogueLog.e("IncidentApiManager: getIncident: IOException: ", e);
...@@ -124,9 +148,14 @@ public class IncidentApiManager { ...@@ -124,9 +148,14 @@ public class IncidentApiManager {
} }
} }
public static void submitIncidentForm(String incidentJsonString, PostIncidentApiListener listener) { public static void submitIncidentForm(Context context, String incidentJsonString, PostIncidentApiListener listener) {
CatalogueLog.d("submitIncidentForm: incidentJson" + incidentJsonString); CatalogueLog.d("submitIncidentForm: incidentJson" + incidentJsonString);
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(IncidentApi.class).submitIncident(incidentJsonString); Call<ResponseBody> call = retrofit.create(IncidentApi.class).submitIncident(incidentJsonString);
try { try {
//Retrofit synchronous call //Retrofit synchronous call
...@@ -144,7 +173,20 @@ public class IncidentApiManager { ...@@ -144,7 +173,20 @@ public class IncidentApiManager {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
listener.onFailApiCall(); CatalogueLog.d("IncidentApiManager: submitIncidentForm: response is not success");
if(response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if(status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
submitIncidentForm(context, incidentJsonString, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
listener.onFailApiCall();
}
} else {
listener.onFailApiCall();
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("IncidentApiManager: submitIncidentForm: IOException: ", e); CatalogueLog.e("IncidentApiManager: submitIncidentForm: IOException: ", e);
...@@ -154,4 +196,4 @@ public class IncidentApiManager { ...@@ -154,4 +196,4 @@ public class IncidentApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} }
} }
\ No newline at end of file
package com.vsoft.uoflservicenow.api.managers;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.vsoft.uoflservicenow.api.RestClient;
import com.vsoft.uoflservicenow.api.interfaces.LoginApi;
import com.vsoft.uoflservicenow.api.listeners.get.GetUserLoginApiListener;
import com.vsoft.uoflservicenow.api.pojos.LoginApiResponse;
import com.vsoft.uoflservicenow.enums.SyncStatus;
import com.vsoft.uoflservicenow.utils.CatalogueLog;
import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* Created by kvemulavada on 8/29/2016.
*/
public class LoginApiManager {
public static void submitLoginValues(String grantType, String clientId, String clientSecret, String userName, String password, GetUserLoginApiListener listener) {
final Retrofit retrofit = RestClient.getInitializedRestAdapterWithOutAuthorizationHeader();
Call<ResponseBody> call = retrofit.create(LoginApi.class).postLoginValues(grantType, clientId, clientSecret, userName, password);
try {
//Retrofit synchronous call
Response<ResponseBody> response = call.execute();
if (response.isSuccessful()) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject error = jsonObject.optJSONObject(Constants.RESPONSE_ERROR_OBJECT_NAME);
if (error == null) {
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapter(long.class, new JsonDeserializer<Long>() {
@Override
public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
long value = 0;
try {
value = json.getAsLong();
} catch (NumberFormatException e) {
CatalogueLog.d("LoginApiManager: getCatalogues: deserialize: long.class: NumberFormatException: ");
}
return value;
}
})
.registerTypeAdapter(int.class, new JsonDeserializer<Integer>() {
@Override
public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
int value = 0;
try {
value = json.getAsInt();
} catch (NumberFormatException e) {
CatalogueLog.d("LoginApiManager: submitLoginValues: deserialize: int.class: NumberFormatException: ");
}
return value;
}
})
.registerTypeAdapter(float.class, new JsonDeserializer<Float>() {
@Override
public Float deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
float value = 0;
try {
value = json.getAsFloat();
} catch (NumberFormatException e) {
CatalogueLog.e("LoginApiManager: submitLoginValues: deserialize: float.class: NumberFormatException: ", e);
}
return value;
}
})
.create();
LoginApiResponse loginApiResponse = gson.fromJson(jsonObject.toString(), LoginApiResponse.class);
listener.onDoneApiCall(loginApiResponse);
} else
listener.onFailApiCall();
} catch (JSONException e) {
CatalogueLog.e("LoginApiManager: submitLoginValues: onResponse: ", e);
listener.onFailApiCall();
} catch (IOException e) {
CatalogueLog.e("LoginApiManager: submitLoginValues: onResponse: ", e);
listener.onFailApiCall();
}
} else {
listener.onFailApiCall();
}
} catch (IOException e) {
CatalogueLog.e("LoginApiManager: submitLoginValues: IOException: ", e);
listener.onFailApiCall();
} catch (NullPointerException e) {
CatalogueLog.e("LoginApiManager: submitLoginValues: IOException: ", e);
listener.onFailApiCall();
}
}
public static SyncStatus refreshLogin(Context context, String refreshToken) {
CatalogueLog.d("LoginApiManager: refreshLogin");
final Retrofit retrofit = RestClient.getInitializedRestAdapterWithOutAuthorizationHeader();
Call<ResponseBody> call = retrofit.create(LoginApi.class).refreshLogin(LoginApiResponse.Json.REFRESH_TOKEN,
Constants.LOGIN_CLIENT_ID,
Constants.LOGIN_CLIENT_SECRET,
refreshToken);
try {
Response<ResponseBody> response = call.execute();
if (response.isSuccessful()) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
CatalogueLog.d("refreshLogin: successfully refreshed login.");
PrefManager.setSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN, jsonObject.getString(LoginApiResponse.Json.JSON_ACCESS_TOKEN));
return SyncStatus.SUCCESS;
} catch(JSONException e) {
CatalogueLog.e("refreshLogin: JSONException: ", e);
return SyncStatus.FAIL;
}
} else {
CatalogueLog.d("refreshLogin: failed to refresh token...");
if(response.code() == 401) {
CatalogueLog.d("---- 401, unSetting access and refresh token, prompt user to login again");
PrefManager.setSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN, "");
PrefManager.setSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN, "");
Intent intent = new Intent(Constants.APPLICATION_BROADCAST_INTENT);
intent.putExtra(Constants.APPLICATION_BROADCAST_DATA_ACTION, Constants.ACTION_PROMPT_LOGIN);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
return SyncStatus.FAIL;
}
} catch(IOException e) {
CatalogueLog.e("refreshLogin: IOException: ", e);
return SyncStatus.FAIL;
}
}
}
package com.vsoft.uoflservicenow.api.managers;
import com.vsoft.uoflservicenow.api.RestClient;
import com.vsoft.uoflservicenow.api.interfaces.LoginApi;
import com.vsoft.uoflservicenow.api.listeners.get.GetUserLoginApiListener;
import com.vsoft.uoflservicenow.utils.CatalogueLog;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* Created by kvemulavada on 8/29/2016.
*/
public class LoginApiManger {
public static void submitLoginValues(String garntType, String clientId, String clientSecret, String userName, String password, GetUserLoginApiListener listener) {
final Retrofit retrofit = RestClient.getInitializedRestAdapterWithOutAuthorizationHeader();
Call<ResponseBody> call = retrofit.create(LoginApi.class).postLoginValues(garntType, clientId, clientSecret, userName, password);
try {
//Retrofit synchronous call
Response<ResponseBody> response = call.execute();
ResponseBody body = response.body();
if (body != null) {
if (body.contentLength() != -1) {
listener.onDoneApiCall();
} else {
listener.onFailApiCall();
}
} else {
listener.onFailApiCall();
}
} catch (IOException e) {
CatalogueLog.e("LoginApiManger: submitLoginValues: IOException: ", e);
listener.onFailApiCall();
} catch (NullPointerException e) {
CatalogueLog.e("LoginApiManger: submitLoginValues: IOException: ", e);
listener.onFailApiCall();
}
}
}
package com.vsoft.uoflservicenow.api.managers; package com.vsoft.uoflservicenow.api.managers;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
...@@ -13,13 +16,17 @@ import com.vsoft.uoflservicenow.db.models.MyRequest; ...@@ -13,13 +16,17 @@ import com.vsoft.uoflservicenow.db.models.MyRequest;
import com.vsoft.uoflservicenow.enums.SyncStatus; import com.vsoft.uoflservicenow.enums.SyncStatus;
import com.vsoft.uoflservicenow.utils.CatalogueLog; import com.vsoft.uoflservicenow.utils.CatalogueLog;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import okhttp3.ResponseBody; import okhttp3.ResponseBody;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Response; import retrofit2.Response;
...@@ -30,12 +37,17 @@ import retrofit2.Retrofit; ...@@ -30,12 +37,17 @@ import retrofit2.Retrofit;
*/ */
public class MyRequestApiManager { public class MyRequestApiManager {
public static SyncStatus getMyrequests(GetMyRequestApiListener listener) { public static SyncStatus getMyRequests(Context context, GetMyRequestApiListener listener) {
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(MyRequest.Json.URL_PARAM_CATALOGUE_SYSPRM_QUERY_VALUE); stringBuilder.append(MyRequest.Json.URL_PARAM_CATALOGUE_SYSPRM_QUERY_VALUE);
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return SyncStatus.FAIL;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(MyRequestApi.class).getMyRequest(stringBuilder.toString(), "true"); Call<ResponseBody> call = retrofit.create(MyRequestApi.class).getMyRequest(stringBuilder.toString(), "true");
try { try {
//Retrofit synchronous call //Retrofit synchronous call
...@@ -109,7 +121,22 @@ public class MyRequestApiManager { ...@@ -109,7 +121,22 @@ public class MyRequestApiManager {
return SyncStatus.FAIL; return SyncStatus.FAIL;
} }
} else { } else {
return SyncStatus.FAIL; CatalogueLog.d("MyRequestApiManager: getMyRequest: response is not success");
if(response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if(status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
return getMyRequests(context, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
listener.onFailApiCall();
return SyncStatus.FAIL;
}
} else {
listener.onFailApiCall();
return SyncStatus.FAIL;
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("CatalogueApiManager: getCatalogues: IOException: ", e); CatalogueLog.e("CatalogueApiManager: getCatalogues: IOException: ", e);
......
package com.vsoft.uoflservicenow.api.managers; package com.vsoft.uoflservicenow.api.managers;
import android.content.Context;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
...@@ -12,6 +14,7 @@ import com.vsoft.uoflservicenow.api.listeners.get.GetUserDetailApiListener; ...@@ -12,6 +14,7 @@ import com.vsoft.uoflservicenow.api.listeners.get.GetUserDetailApiListener;
import com.vsoft.uoflservicenow.db.models.UserApiValues; import com.vsoft.uoflservicenow.db.models.UserApiValues;
import com.vsoft.uoflservicenow.utils.CatalogueLog; import com.vsoft.uoflservicenow.utils.CatalogueLog;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
...@@ -31,9 +34,14 @@ import retrofit2.Retrofit; ...@@ -31,9 +34,14 @@ import retrofit2.Retrofit;
* Created by kvemulavada on 8/31/2016. * Created by kvemulavada on 8/31/2016.
*/ */
public class UserApiManager { public class UserApiManager {
public static void getUserDetailResponse(String userName, GetUserDetailApiListener listener) { public static void getUserDetailResponse(Context context, String userName, GetUserDetailApiListener listener) {
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(UserApi.class).getuserDetails(userName); Call<ResponseBody> call = retrofit.create(UserApi.class).getuserDetails(userName);
try { try {
//Retrofit synchronous call //Retrofit synchronous call
......
package com.vsoft.uoflservicenow.api.managers; package com.vsoft.uoflservicenow.api.managers;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
...@@ -12,8 +15,10 @@ import com.vsoft.uoflservicenow.api.listeners.get.GetReferenceApiListener; ...@@ -12,8 +15,10 @@ import com.vsoft.uoflservicenow.api.listeners.get.GetReferenceApiListener;
import com.vsoft.uoflservicenow.api.listeners.get.GetVariableChoiceApiListener; import com.vsoft.uoflservicenow.api.listeners.get.GetVariableChoiceApiListener;
import com.vsoft.uoflservicenow.db.models.Reference; import com.vsoft.uoflservicenow.db.models.Reference;
import com.vsoft.uoflservicenow.db.models.VariableChoice; import com.vsoft.uoflservicenow.db.models.VariableChoice;
import com.vsoft.uoflservicenow.enums.SyncStatus;
import com.vsoft.uoflservicenow.utils.CatalogueLog; import com.vsoft.uoflservicenow.utils.CatalogueLog;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.PrefManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
...@@ -32,20 +37,21 @@ import retrofit2.Retrofit; ...@@ -32,20 +37,21 @@ import retrofit2.Retrofit;
/** /**
* @author Kunj on 11/8/16. * @author Kunj on 11/8/16.
* *bkunj@vscbkunj@vsc
*/ */
public class VariableChoiceApiManager { public class VariableChoiceApiManager {
public static void getVariableChoice(String variableSysId, GetVariableChoiceApiListener listener) { public static void getVariableChoice(Context context, String variableSysId, GetVariableChoiceApiListener listener) {
CatalogueLog.d("VariableChoiceApiManager: getVariableChoice: "); CatalogueLog.d("VariableChoiceApiManager: getVariableChoice: ");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(VariableChoice.Json.URL_PARAM_VARIABLE_CHOICE_SYSPRM_QUERY_VALUE);
stringBuilder.append("=");
stringBuilder.append(variableSysId);
CatalogueLog.d("VariableChoiceApiManager: getVariableChoice: request parameter: "+stringBuilder.toString());
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
Call<ResponseBody> call = retrofit.create(CatalogueVariableApi.class).getVariableChoice(stringBuilder.toString(), "text,value,order,misc"); if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(CatalogueVariableApi.class).getVariableChoice(variableSysId);
try { try {
//Retrofit synchronous call //Retrofit synchronous call
Response<ResponseBody> response = call.execute(); Response<ResponseBody> response = call.execute();
...@@ -116,7 +122,20 @@ public class VariableChoiceApiManager { ...@@ -116,7 +122,20 @@ public class VariableChoiceApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} else { } else {
listener.onFailApiCall(); CatalogueLog.d("VariableChoiceApiManager: getVariableChoice: response is not success");
if(response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if(status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
getVariableChoice(context, variableSysId, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
listener.onFailApiCall();
}
} else {
listener.onFailApiCall();
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("VariableChoiceApiManager: getVariableChoice: IOException: ", e); CatalogueLog.e("VariableChoiceApiManager: getVariableChoice: IOException: ", e);
...@@ -127,10 +146,16 @@ public class VariableChoiceApiManager { ...@@ -127,10 +146,16 @@ public class VariableChoiceApiManager {
} }
} }
public static void getReference(String tableName, Map<String,String> queryMap, GetReferenceApiListener listener) { public static void getReference(Context context, String tableName, Map<String,String> queryMap, GetReferenceApiListener listener) {
CatalogueLog.d("VariableChoiceApiManager: getReference: tableName: "+tableName); CatalogueLog.d("VariableChoiceApiManager: getReference: tableName: "+tableName);
final Retrofit retrofit = RestClient.getInitializedRestAdapter(Constants.API_AUTH_PARAM_USER_NAME, Constants.API_AUTH_PARAM_PASSWORD); String accessToken = PrefManager.getSharedPref(context, PrefManager.PREFERENCE_ACCESS_TOKEN);
if(accessToken.isEmpty()) {
listener.onFailApiCall();
return;
}
final Retrofit retrofit = RestClient.getInitializedRestAdapter(accessToken);
Call<ResponseBody> call = retrofit.create(CatalogueVariableApi.class).getReference(Constants.URL_GET_REFERENCE + tableName, queryMap); Call<ResponseBody> call = retrofit.create(CatalogueVariableApi.class).getReference(Constants.URL_GET_REFERENCE + tableName, queryMap);
try { try {
//Retrofit synchronous call //Retrofit synchronous call
...@@ -202,7 +227,20 @@ public class VariableChoiceApiManager { ...@@ -202,7 +227,20 @@ public class VariableChoiceApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} else { } else {
listener.onFailApiCall(); CatalogueLog.d("VariableChoiceApiManager: getReference: response is not success");
if(response.code() == 401) {
Log.d(Constants.TAG, "-- is 401, try refresh token...");
SyncStatus status = LoginApiManager.refreshLogin(context, PrefManager.getSharedPref(context, PrefManager.PREFERENCE_REFRESH_TOKEN));
if(status == SyncStatus.SUCCESS) {
CatalogueLog.d("refresh token success, retry same...");
getReference(context, tableName, queryMap, listener);
} else {
CatalogueLog.d("refresh token failed, return FAIL");
listener.onFailApiCall();
}
} else {
listener.onFailApiCall();
}
} }
} catch (IOException e) { } catch (IOException e) {
CatalogueLog.e("VariableChoiceApiManager: getReference: IOException: ", e); CatalogueLog.e("VariableChoiceApiManager: getReference: IOException: ", e);
...@@ -212,4 +250,4 @@ public class VariableChoiceApiManager { ...@@ -212,4 +250,4 @@ public class VariableChoiceApiManager {
listener.onFailApiCall(); listener.onFailApiCall();
} }
} }
} }
\ No newline at end of file
package com.vsoft.uoflservicenow.api.pojos;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by kunj on 14/12/2016.
*/
public class LoginApiResponse {
@SerializedName("access_token")
@Expose
private String accessToken;
@SerializedName("refresh_token")
@Expose
private String refreshToken;
@SerializedName("scope")
@Expose
private String scope;
@SerializedName("token_type")
@Expose
private String tokenType;
@SerializedName("expires_in")
@Expose
private Integer expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public Integer getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}
public static class Json {
public static final String GRANT_TYPE = "grant_type";
public static final String CLIENT_ID = "client_id";
public static final String CLIENT_SECRET = "client_secret";
public static final String USER_NAME = "username";
public static final String PASSWORD = "password";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String JSON_ACCESS_TOKEN = "access_token";
}
}
...@@ -184,7 +184,7 @@ public class SelectReferenceDialog extends DialogFragment { ...@@ -184,7 +184,7 @@ public class SelectReferenceDialog extends DialogFragment {
Map<String, String> stringMap = new HashMap<>(1); Map<String, String> stringMap = new HashMap<>(1);
stringMap.put(Constants.URL_PARAM_SYSPRM_FIELDS, "sys_id,"+mReferenceColumnName); stringMap.put(Constants.URL_PARAM_SYSPRM_FIELDS, "sys_id,"+mReferenceColumnName);
stringMap.put(Constants.URL_PARAM_SYSPRM_QUERY, mReferenceColumnName+"LIKE"+params[0]); stringMap.put(Constants.URL_PARAM_SYSPRM_QUERY, mReferenceColumnName+"LIKE"+params[0]);
VariableChoiceApiManager.getReference(mReferenceTableName, stringMap, new GetReferenceApiListener() { VariableChoiceApiManager.getReference(getActivity(), mReferenceTableName, stringMap, new GetReferenceApiListener() {
@Override @Override
public void onDoneApiCall(List<Reference> referenceList) { public void onDoneApiCall(List<Reference> referenceList) {
syncStatus = SyncStatus.SUCCESS; syncStatus = SyncStatus.SUCCESS;
...@@ -251,4 +251,4 @@ public class SelectReferenceDialog extends DialogFragment { ...@@ -251,4 +251,4 @@ public class SelectReferenceDialog extends DialogFragment {
AlertDialog alert = builder.create(); AlertDialog alert = builder.create();
alert.show(); alert.show();
} }
} }
\ No newline at end of file
...@@ -99,7 +99,7 @@ public class CatalogueItemScreen extends AppCompatActivity { ...@@ -99,7 +99,7 @@ public class CatalogueItemScreen extends AppCompatActivity {
@Override @Override
protected SyncStatus doInBackground(String... params) { protected SyncStatus doInBackground(String... params) {
CatalogueItemApiManager.getCatalogueItems(mCatalogueSysId, new GetCatalogueItemApiListener() { CatalogueItemApiManager.getCatalogueItems(CatalogueItemScreen.this, mCatalogueSysId, new GetCatalogueItemApiListener() {
@Override @Override
public void onDoneApiCall(List<CatalogueItem> catalogueItemList) { public void onDoneApiCall(List<CatalogueItem> catalogueItemList) {
syncStatus = SyncStatus.SUCCESS; syncStatus = SyncStatus.SUCCESS;
......
...@@ -90,7 +90,7 @@ public class CatalogueScreen extends AppCompatActivity { ...@@ -90,7 +90,7 @@ public class CatalogueScreen extends AppCompatActivity {
@Override @Override
protected SyncStatus doInBackground(String... params) { protected SyncStatus doInBackground(String... params) {
CatalogueApiManager.getCatalogues(new GetCatalogueApiListener() { CatalogueApiManager.getCatalogues(CatalogueScreen.this, new GetCatalogueApiListener() {
@Override @Override
public void onDoneApiCall(List<Catalogue> catalogueList) { public void onDoneApiCall(List<Catalogue> catalogueList) {
syncStatus = SyncStatus.SUCCESS; syncStatus = SyncStatus.SUCCESS;
......
...@@ -9,7 +9,6 @@ import android.content.ContentUris; ...@@ -9,7 +9,6 @@ import android.content.ContentUris;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.database.Cursor; import android.database.Cursor;
import android.graphics.Typeface; import android.graphics.Typeface;
...@@ -183,7 +182,7 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -183,7 +182,7 @@ public class CatalogueVariableScreen extends AppCompatActivity {
@Override @Override
protected SyncStatus doInBackground(final String... params) { protected SyncStatus doInBackground(final String... params) {
CatalogueVariableApiManager.getCatalogueVariable(mCatalogueItemSysId, new GetCatalogueVariableApiListener() { CatalogueVariableApiManager.getCatalogueVariable(CatalogueVariableScreen.this, mCatalogueItemSysId, new GetCatalogueVariableApiListener() {
@Override @Override
public void onDoneApiCall(List<CatalogueVariableSet> variableSetList, List<CatalogueVariable> variableList) { public void onDoneApiCall(List<CatalogueVariableSet> variableSetList, List<CatalogueVariable> variableList) {
mSyncStatus = SyncStatus.SUCCESS; mSyncStatus = SyncStatus.SUCCESS;
...@@ -199,7 +198,7 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -199,7 +198,7 @@ public class CatalogueVariableScreen extends AppCompatActivity {
/*For variable list*/ /*For variable list*/
mSyncStatus = setVariableChoiceData(variableList); mSyncStatus = setVariableChoiceData(variableList);
if(mSyncStatus != SyncStatus.FAIL) { if(mSyncStatus != SyncStatus.FAIL) {
CatalogueVariableApiManager.getUiPolicy(mCatalogueItemSysId, new GetUiPolicyApiListener() { CatalogueVariableApiManager.getUiPolicy(CatalogueVariableScreen.this, mCatalogueItemSysId, new GetUiPolicyApiListener() {
@Override @Override
public void onDoneApiCall(List<UiPolicyItem> uiPolicyItemList) { public void onDoneApiCall(List<UiPolicyItem> uiPolicyItemList) {
mSyncStatus = SyncStatus.SUCCESS; mSyncStatus = SyncStatus.SUCCESS;
...@@ -278,7 +277,7 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -278,7 +277,7 @@ public class CatalogueVariableScreen extends AppCompatActivity {
if (catalogueVariable.getType() == ViewType.MULTIPLE_CHOICE if (catalogueVariable.getType() == ViewType.MULTIPLE_CHOICE
|| catalogueVariable.getType() == ViewType.SELECT_BOX) { || catalogueVariable.getType() == ViewType.SELECT_BOX) {
/*Fetch multi choice variable values*/ /*Fetch multi choice variable values*/
VariableChoiceApiManager.getVariableChoice(catalogueVariable.getSysId(), new GetVariableChoiceApiListener() { VariableChoiceApiManager.getVariableChoice(CatalogueVariableScreen.this, catalogueVariable.getSysId(), new GetVariableChoiceApiListener() {
@Override @Override
public void onDoneApiCall(List<VariableChoice> variableChoiceList) { public void onDoneApiCall(List<VariableChoice> variableChoiceList) {
mSyncStatus = SyncStatus.SUCCESS; mSyncStatus = SyncStatus.SUCCESS;
...@@ -365,11 +364,7 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -365,11 +364,7 @@ public class CatalogueVariableScreen extends AppCompatActivity {
if(!mCatalogueVariableList.isEmpty()) { if(!mCatalogueVariableList.isEmpty()) {
VariableViewContainer container; VariableViewContainer container;
SharedPreferences sharedPreferences = null;
for (int i = 0; i < mCatalogueVariableList.size(); i++) { for (int i = 0; i < mCatalogueVariableList.size(); i++) {
if(sharedPreferences == null) {
sharedPreferences = getSharedPreferences(PrefManager.PREFERENCES_USER_VALUES_KEY, Context.MODE_PRIVATE);
}
CatalogueVariable catalogueVariable = mCatalogueVariableList.get(i); CatalogueVariable catalogueVariable = mCatalogueVariableList.get(i);
/*If API return active false for a variable, there is no need show that variable*/ /*If API return active false for a variable, there is no need show that variable*/
if(catalogueVariable.isActive()) { if(catalogueVariable.isActive()) {
...@@ -409,10 +404,10 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -409,10 +404,10 @@ public class CatalogueVariableScreen extends AppCompatActivity {
if (controlView != null) { if (controlView != null) {
/*For set default text in full_name and user_id textView.*/ /*For set default text in full_name and user_id textView.*/
if(catalogueVariable.getName().equals(getString(R.string.catalogue_user_full_name))) { if(catalogueVariable.getName().equals(getString(R.string.catalogue_user_full_name))) {
String userFullName = sharedPreferences.getString(PrefManager.PREFERENCE_USER_FULL_NAME, ""); String userFullName = PrefManager.getSharedPref(CatalogueVariableScreen.this, PrefManager.PREFERENCE_USER_FULL_NAME);
((EditText)controlView).setText(userFullName); ((EditText)controlView).setText(userFullName);
} else if(catalogueVariable.getName().equals(getString(R.string.catalogue_user_id))) { } else if(catalogueVariable.getName().equals(getString(R.string.catalogue_user_id))) {
String userId = sharedPreferences.getString(PrefManager.PREFERENCE_USER_ID, ""); String userId = PrefManager.getSharedPref(CatalogueVariableScreen.this, PrefManager.PREFERENCE_USER_ID);
((EditText)controlView).setText(userId); ((EditText)controlView).setText(userId);
} }
if (viewType == ViewType.DATE) { if (viewType == ViewType.DATE) {
...@@ -728,7 +723,7 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -728,7 +723,7 @@ public class CatalogueVariableScreen extends AppCompatActivity {
@Override @Override
protected SyncStatus doInBackground(String... params) { protected SyncStatus doInBackground(String... params) {
CatalogueVariableApiManager.submitVariableForm(mCatalogueItemSysId, params[0], new PostVariableFormApiListener() { CatalogueVariableApiManager.submitVariableForm(CatalogueVariableScreen.this, mCatalogueItemSysId, params[0], new PostVariableFormApiListener() {
@Override @Override
public void onDoneApiCall(String variableFromSysId) { public void onDoneApiCall(String variableFromSysId) {
syncStatus = SyncStatus.SUCCESS; syncStatus = SyncStatus.SUCCESS;
...@@ -749,7 +744,7 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -749,7 +744,7 @@ public class CatalogueVariableScreen extends AppCompatActivity {
e.printStackTrace(); e.printStackTrace();
} }
RequestBody requestBody = RequestBody.create(MediaType.parse(uriContentType), buf); RequestBody requestBody = RequestBody.create(MediaType.parse(uriContentType), buf);
CatalogueVariableApiManager.postAttachment(uriContentType, variableFromSysId, CatalogueVariableApiManager.postAttachment(CatalogueVariableScreen.this, uriContentType, variableFromSysId,
mAttachmentFile.getName(), requestBody, new PostAttachmentApiListener() { mAttachmentFile.getName(), requestBody, new PostAttachmentApiListener() {
@Override @Override
public void onDoneApiCall() { public void onDoneApiCall() {
...@@ -1244,4 +1239,4 @@ public class CatalogueVariableScreen extends AppCompatActivity { ...@@ -1244,4 +1239,4 @@ public class CatalogueVariableScreen extends AppCompatActivity {
} }
} }
} }
} }
\ No newline at end of file
...@@ -68,7 +68,13 @@ public class HomeScreen extends AppCompatActivity { ...@@ -68,7 +68,13 @@ public class HomeScreen extends AppCompatActivity {
.setCancelable(false) .setCancelable(false)
.setPositiveButton(R.string.ok_string, new DialogInterface.OnClickListener() { .setPositiveButton(R.string.ok_string, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
PrefManager.saveUserDetailsInPreferences(HomeScreen.this, "", "", "", "", ""); PrefManager.setSharedPref(HomeScreen.this, PrefManager.PREFERENCE_ACCESS_TOKEN, "");
PrefManager.setSharedPref(HomeScreen.this, PrefManager.PREFERENCE_REFRESH_TOKEN, "");
PrefManager.setSharedPref(HomeScreen.this, PrefManager.PREFERENCE_LAST_NAME, "");
PrefManager.setSharedPref(HomeScreen.this, PrefManager.PREFERENCE_SYS_ID, "");
PrefManager.setSharedPref(HomeScreen.this, PrefManager.PREFERENCE_FIRST_NAME, "");
PrefManager.setSharedPref(HomeScreen.this, PrefManager.PREFERENCE_USER_ID, "");
PrefManager.setSharedPref(HomeScreen.this, PrefManager.PREFERENCE_USER_FULL_NAME, "");
Intent loginIntent = new Intent(HomeScreen.this, LoginScreen.class); Intent loginIntent = new Intent(HomeScreen.this, LoginScreen.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent); startActivity(loginIntent);
......
...@@ -2,9 +2,7 @@ package com.vsoft.uoflservicenow.ui; ...@@ -2,9 +2,7 @@ package com.vsoft.uoflservicenow.ui;
import android.app.Activity; import android.app.Activity;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.text.TextUtils; import android.text.TextUtils;
...@@ -18,8 +16,9 @@ import com.vsoft.uoflservicenow.CatalogueApplication; ...@@ -18,8 +16,9 @@ import com.vsoft.uoflservicenow.CatalogueApplication;
import com.vsoft.uoflservicenow.R; import com.vsoft.uoflservicenow.R;
import com.vsoft.uoflservicenow.api.listeners.get.GetUserDetailApiListener; import com.vsoft.uoflservicenow.api.listeners.get.GetUserDetailApiListener;
import com.vsoft.uoflservicenow.api.listeners.get.GetUserLoginApiListener; import com.vsoft.uoflservicenow.api.listeners.get.GetUserLoginApiListener;
import com.vsoft.uoflservicenow.api.managers.LoginApiManger; import com.vsoft.uoflservicenow.api.managers.LoginApiManager;
import com.vsoft.uoflservicenow.api.managers.UserApiManager; import com.vsoft.uoflservicenow.api.managers.UserApiManager;
import com.vsoft.uoflservicenow.api.pojos.LoginApiResponse;
import com.vsoft.uoflservicenow.db.models.UserApiValues; import com.vsoft.uoflservicenow.db.models.UserApiValues;
import com.vsoft.uoflservicenow.utils.Constants; import com.vsoft.uoflservicenow.utils.Constants;
import com.vsoft.uoflservicenow.utils.DialogUtils; import com.vsoft.uoflservicenow.utils.DialogUtils;
...@@ -48,7 +47,6 @@ public class LoginScreen extends Activity { ...@@ -48,7 +47,6 @@ public class LoginScreen extends Activity {
private static final int API_FAIL_USER_LOGIN = 2; private static final int API_FAIL_USER_LOGIN = 2;
private static final int API_SUCCESS_USER_DETAIL = 3; private static final int API_SUCCESS_USER_DETAIL = 3;
private static final int API_FAIL_USER_DETAIL = 4; private static final int API_FAIL_USER_DETAIL = 4;
private int apiStatus;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
...@@ -59,8 +57,6 @@ public class LoginScreen extends Activity { ...@@ -59,8 +57,6 @@ public class LoginScreen extends Activity {
ButterKnife.bind(this); ButterKnife.bind(this);
mApplication = (CatalogueApplication) getApplication(); mApplication = (CatalogueApplication) getApplication();
PrefManager prefManager = PrefManager.getInstance();
prefManager.init(LoginScreen.this);
CheckLoginValues(); CheckLoginValues();
mPasswordEditText.setOnKeyListener(new View.OnKeyListener() { mPasswordEditText.setOnKeyListener(new View.OnKeyListener() {
...@@ -85,8 +81,7 @@ public class LoginScreen extends Activity { ...@@ -85,8 +81,7 @@ public class LoginScreen extends Activity {
} }
private void CheckLoginValues() { private void CheckLoginValues() {
SharedPreferences sharedPreferences = getSharedPreferences(PrefManager.PREFERENCES_USER_VALUES_KEY, Context.MODE_PRIVATE); String sysId = PrefManager.getSharedPref(LoginScreen.this, PrefManager.PREFERENCE_SYS_ID);
String sysId = sharedPreferences.getString(PrefManager.PREFERENCE_SYS_ID, "");
if (!TextUtils.isEmpty(sysId)) { if (!TextUtils.isEmpty(sysId)) {
startActivity(new Intent(LoginScreen.this, HomeScreen.class)); startActivity(new Intent(LoginScreen.this, HomeScreen.class));
finish(); finish();
...@@ -121,7 +116,7 @@ public class LoginScreen extends Activity { ...@@ -121,7 +116,7 @@ public class LoginScreen extends Activity {
private class LoginDetailsSendToServer extends AsyncTask<String, Integer, Integer> { private class LoginDetailsSendToServer extends AsyncTask<String, Integer, Integer> {
private ProgressDialog progressDialog; private ProgressDialog progressDialog;
private static final int USER_DETAIL = 1; private static final int USER_DETAIL = 1;
private String userName; private int apiStatus;
@Override @Override
protected void onPreExecute() { protected void onPreExecute() {
...@@ -134,15 +129,19 @@ public class LoginScreen extends Activity { ...@@ -134,15 +129,19 @@ public class LoginScreen extends Activity {
@Override @Override
protected Integer doInBackground(String... params) { protected Integer doInBackground(String... params) {
userName = params[0];//"a0kuma18"; final String userName = params[0];
String password = params[1];//"v$0ftA$win"; String password = params[1];
LoginApiManger.submitLoginValues(Constants.GRANT_TYPE, Constants.CLIENT_ID, Constants LoginApiManager.submitLoginValues(LoginApiResponse.Json.PASSWORD, Constants.LOGIN_CLIENT_ID, Constants
.CLIENT_SECRET, userName, password, new GetUserLoginApiListener() { .LOGIN_CLIENT_SECRET, userName, password, new GetUserLoginApiListener() {
@Override @Override
public void onDoneApiCall() { public void onDoneApiCall(LoginApiResponse loginApiResponse) {
/*Save access token in Preference*/
PrefManager.setSharedPref(LoginScreen.this, PrefManager.PREFERENCE_ACCESS_TOKEN, loginApiResponse.getAccessToken());
PrefManager.setSharedPref(LoginScreen.this, PrefManager.PREFERENCE_REFRESH_TOKEN, loginApiResponse.getRefreshToken());
apiStatus = API_SUCCESS_USER_LOGIN; apiStatus = API_SUCCESS_USER_LOGIN;
publishProgress(USER_DETAIL); publishProgress(USER_DETAIL);
UserApiManager.getUserDetailResponse(userName, new GetUserDetailApiListener() { UserApiManager.getUserDetailResponse(LoginScreen.this, userName, new GetUserDetailApiListener() {
@Override @Override
public void onDoneApiCall(List<UserApiValues> userValues) { public void onDoneApiCall(List<UserApiValues> userValues) {
apiStatus = API_SUCCESS_USER_DETAIL; apiStatus = API_SUCCESS_USER_DETAIL;
...@@ -181,10 +180,18 @@ public class LoginScreen extends Activity { ...@@ -181,10 +180,18 @@ public class LoginScreen extends Activity {
if (mUserDetails != null) { if (mUserDetails != null) {
String firstName = mUserDetails.get(0).getFirstName(); String firstName = mUserDetails.get(0).getFirstName();
String lastName = mUserDetails.get(0).getLastName(); String lastName = mUserDetails.get(0).getLastName();
String sysId = mUserDetails.get(0).getSysId(); String sysid = mUserDetails.get(0).getSysId();
String userFullName = mUserDetails.get(0).getFullName(); String userFullName = mUserDetails.get(0).getFullName();
String userId = mUserDetails.get(0).getUserId(); String userId = mUserDetails.get(0).getUserId();
PrefManager.saveUserDetailsInPreferences(LoginScreen.this, userFullName, userId, firstName, lastName, sysId);
PrefManager.setSharedPref(LoginScreen.this, PrefManager.PREFERENCE_FIRST_NAME, firstName);
PrefManager.setSharedPref(LoginScreen.this, PrefManager.PREFERENCE_LAST_NAME, lastName);
PrefManager.setSharedPref(LoginScreen.this, PrefManager.PREFERENCE_SYS_ID, sysid);
/*For prefill value in variable form*/
PrefManager.setSharedPref(LoginScreen.this, PrefManager.PREFERENCE_USER_FULL_NAME, userFullName);
PrefManager.setSharedPref(LoginScreen.this, PrefManager.PREFERENCE_USER_ID, userId);
startActivity(new Intent(LoginScreen.this, HomeScreen.class)); startActivity(new Intent(LoginScreen.this, HomeScreen.class));
finish(); finish();
} else { } else {
......
...@@ -106,7 +106,7 @@ public class MyIncidentScreen extends AppCompatActivity { ...@@ -106,7 +106,7 @@ public class MyIncidentScreen extends AppCompatActivity {
@Override @Override
protected SyncStatus doInBackground(String... params) { protected SyncStatus doInBackground(String... params) {
IncidentApiManager.getIncident(new GetIncidentApiListener() { IncidentApiManager.getIncident(MyIncidentScreen.this, new GetIncidentApiListener() {
@Override @Override
public void onDoneApiCall(List<Incident> incidentList) { public void onDoneApiCall(List<Incident> incidentList) {
syncStatus = SyncStatus.SUCCESS; syncStatus = SyncStatus.SUCCESS;
......
...@@ -85,7 +85,7 @@ public class MyRequestActivity extends AppCompatActivity { ...@@ -85,7 +85,7 @@ public class MyRequestActivity extends AppCompatActivity {
@Override @Override
protected SyncStatus doInBackground(String... params) { protected SyncStatus doInBackground(String... params) {
MyRequestApiManager.getMyrequests(new GetMyRequestApiListener() { MyRequestApiManager.getMyRequests(MyRequestActivity.this, new GetMyRequestApiListener() {
@Override @Override
public void onDoneApiCall(List<MyRequest> requestList) { public void onDoneApiCall(List<MyRequest> requestList) {
syncStatus = SyncStatus.SUCCESS; syncStatus = SyncStatus.SUCCESS;
......
package com.vsoft.uoflservicenow.ui; package com.vsoft.uoflservicenow.ui;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar;
...@@ -134,9 +132,8 @@ public class ReportIncidentScreen extends AppCompatActivity { ...@@ -134,9 +132,8 @@ public class ReportIncidentScreen extends AppCompatActivity {
void submitOnClicked(View view) { void submitOnClicked(View view) {
if(mApplication.isNetConnected()) { if(mApplication.isNetConnected()) {
if (!hasValidateForm()) { if (!hasValidateForm()) {
SharedPreferences sharedPreferences = getSharedPreferences(PrefManager.PREFERENCES_USER_VALUES_KEY, Context.MODE_PRIVATE); String userSysId = PrefManager.getSharedPref(ReportIncidentScreen.this, PrefManager.PREFERENCE_SYS_ID);
String userSysId = sharedPreferences.getString(PrefManager.PREFERENCE_SYS_ID, ""); if(userSysId != null && !userSysId.isEmpty()) {
if(!userSysId.isEmpty()) {
Util.hideSoftKeyboard(ReportIncidentScreen.this, view); Util.hideSoftKeyboard(ReportIncidentScreen.this, view);
new submitIncident().execute(userSysId); new submitIncident().execute(userSysId);
} else { } else {
...@@ -175,7 +172,7 @@ public class ReportIncidentScreen extends AppCompatActivity { ...@@ -175,7 +172,7 @@ public class ReportIncidentScreen extends AppCompatActivity {
e.printStackTrace(); e.printStackTrace();
} }
IncidentApiManager.submitIncidentForm(incidentJsonObject.toString(), new PostIncidentApiListener() { IncidentApiManager.submitIncidentForm(ReportIncidentScreen.this, incidentJsonObject.toString(), new PostIncidentApiListener() {
@Override @Override
public void onDoneApiCall(String incidentNumber) { public void onDoneApiCall(String incidentNumber) {
syncStatus = SyncStatus.SUCCESS; syncStatus = SyncStatus.SUCCESS;
......
...@@ -8,10 +8,6 @@ import com.vsoft.uoflservicenow.BuildConfig; ...@@ -8,10 +8,6 @@ import com.vsoft.uoflservicenow.BuildConfig;
*/ */
public class Constants { public class Constants {
public static final String GRANT_TYPE = "password";
public static final String CLIENT_ID = "ac0dd3408c1031006907010c2cc6ef6d";
public static final String CLIENT_SECRET = "oklj6znxv3o9jmyn2mlp";
public static final String TAG = "UofLCatalogue"; public static final String TAG = "UofLCatalogue";
public static final String[] month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; public static final String[] month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
...@@ -27,6 +23,12 @@ public class Constants { ...@@ -27,6 +23,12 @@ public class Constants {
public static final String DATA_KEY_REFERENCE_TABLE_COLUMN_NAME = "table_column_name"; public static final String DATA_KEY_REFERENCE_TABLE_COLUMN_NAME = "table_column_name";
public static final String DATA_KEY_REFERENCE_TITLE = "title"; public static final String DATA_KEY_REFERENCE_TITLE = "title";
/**
* Broadcast custom intent
*/
public static final String APPLICATION_BROADCAST_INTENT = "application_broadcast";
public static final String APPLICATION_BROADCAST_DATA_ACTION = "action";
public static final String ACTION_PROMPT_LOGIN = "action_prompt_login";
/** /**
* Catalogue services post parameters * Catalogue services post parameters
*/ */
...@@ -38,6 +40,7 @@ public class Constants { ...@@ -38,6 +40,7 @@ public class Constants {
public static final String URL_PARAM_TABLE_SYS_ID = "table_sys_id"; public static final String URL_PARAM_TABLE_SYS_ID = "table_sys_id";
public static final String URL_PARAM_TABLE_NAME = "table_name"; public static final String URL_PARAM_TABLE_NAME = "table_name";
public static final String URL_PARAM_FILE_NAME = "file_name"; public static final String URL_PARAM_FILE_NAME = "file_name";
public static final String URL_PARAM_SYS_ID = "sys_id";
/** /**
* Debug logs * Debug logs
...@@ -56,6 +59,23 @@ public class Constants { ...@@ -56,6 +59,23 @@ public class Constants {
private static final int BUILD_TYPE_DEBUG = 1; private static final int BUILD_TYPE_DEBUG = 1;
private static final int BUILD_TYPE_RELEASE = 2; private static final int BUILD_TYPE_RELEASE = 2;
/**
* Decides the Api auth data used
*/
private static final String API_AUTH_PARAM_USER_NAME_PRODUCTION = "vsoft.admin";
private static final String API_AUTH_PARAM_PASSWORD_PRODUCTION = "v50ft@123456";
private static final String API_AUTH_PARAM_USER_NAME_TEST = "a0kuma18";
private static final String API_AUTH_PARAM_PASSWORD_TEST = "v$0ftA$win";
public static final String API_AUTH_PARAM_USER_NAME = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT
? API_AUTH_PARAM_USER_NAME_PRODUCTION
: API_AUTH_PARAM_USER_NAME_TEST);
public static final String API_AUTH_PARAM_PASSWORD = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT
? API_AUTH_PARAM_PASSWORD_PRODUCTION
: API_AUTH_PARAM_PASSWORD_TEST);
private static final String API_PATH = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT private static final String API_PATH = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT
? API_PATH_PRODUCTION ? API_PATH_PRODUCTION
: API_PATH_TEST); : API_PATH_TEST);
...@@ -67,11 +87,11 @@ public class Constants { ...@@ -67,11 +87,11 @@ public class Constants {
/** /**
* Decides the Client data used * Decides the Client data used
*/ */
private static final String LOGIN_CLIENT_ID_PRODUCTION = "a40b3f05ae582600433c09623de6cbe4"; private static final String LOGIN_CLIENT_ID_PRODUCTION = "ac0dd3408c1031006907010c2cc6ef6d";
private static final String LOGIN_CLIENT_SECRET_PRODUCTION = "t8SdV}crm&"; private static final String LOGIN_CLIENT_SECRET_PRODUCTION = "oklj6znxv3o9jmyn2mlp";
private static final String LOGIN_CLIENT_ID_TEST = "8689966b6f8426001fbf10d078fc4cc5"; private static final String LOGIN_CLIENT_ID_TEST = "ac0dd3408c1031006907010c2cc6ef6d";
private static final String LOGIN_CLIENT_SECRET_TEST = "tGm41IOL6i"; private static final String LOGIN_CLIENT_SECRET_TEST = "oklj6znxv3o9jmyn2mlp";
public static final String LOGIN_CLIENT_ID = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT public static final String LOGIN_CLIENT_ID = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT
? LOGIN_CLIENT_ID_PRODUCTION ? LOGIN_CLIENT_ID_PRODUCTION
...@@ -80,24 +100,7 @@ public class Constants { ...@@ -80,24 +100,7 @@ public class Constants {
public static final String LOGIN_CLIENT_SECRET = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT public static final String LOGIN_CLIENT_SECRET = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT
? LOGIN_CLIENT_SECRET_PRODUCTION ? LOGIN_CLIENT_SECRET_PRODUCTION
: LOGIN_CLIENT_SECRET_TEST); : LOGIN_CLIENT_SECRET_TEST);
/**
* Decides the Api auth data used
*/
private static final String API_AUTH_PARAM_USER_NAME_PRODUCTION = "vsoft.admin";
private static final String API_AUTH_PARAM_PASSWORD_PRODUCTION = "v50ft@123456";
private static final String API_AUTH_PARAM_USER_NAME_TEST = "a0kuma18";
private static final String API_AUTH_PARAM_PASSWORD_TEST = "v$0ftA$win";
public static final String API_AUTH_PARAM_USER_NAME = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT
? API_AUTH_PARAM_USER_NAME_PRODUCTION
: API_AUTH_PARAM_USER_NAME_TEST);
public static final String API_AUTH_PARAM_PASSWORD = (BUILD_TYPE_RELEASE == BuildConfig.BUILD_TYPE_INT
? API_AUTH_PARAM_PASSWORD_PRODUCTION
: API_AUTH_PARAM_PASSWORD_TEST);
/** /**
* Domain to use * Domain to use
*/ */
...@@ -124,6 +127,7 @@ public class Constants { ...@@ -124,6 +127,7 @@ public class Constants {
*/ */
/*Login API */ /*Login API */
public static final String URL_POST_LOGIN_ITEM = "/oauth_token.do"; public static final String URL_POST_LOGIN_ITEM = "/oauth_token.do";
public static final String URL_REFRESH_LOGIN = URL_POST_LOGIN_ITEM;
/*Catalogue Category API */ /*Catalogue Category API */
public static final String URL_GET_CATALOGUE = API_PATH + "sc_category"; public static final String URL_GET_CATALOGUE = API_PATH + "sc_category";
...@@ -135,7 +139,7 @@ public class Constants { ...@@ -135,7 +139,7 @@ public class Constants {
/*Variable form API */ /*Variable form API */
public static final String URL_GET_VARIABLE = "/api/uno33/uofl_mobile/variables"; public static final String URL_GET_VARIABLE = "/api/uno33/uofl_mobile/variables";
public static final String URL_GET_UI_POLICY = "/api/uno33/uofl_mobile/uipolicy"; public static final String URL_GET_UI_POLICY = "/api/uno33/uofl_mobile/uipolicy";
public static final String URL_GET_VARIABLE_CHOICE = API_PATH + "question_choice"; public static final String URL_GET_VARIABLE_CHOICE = DOMAIN + "/api/uno33/uofl_mobile/question_choice";
public static final String URL_POST_CATALOGUE_ITEM = "api/uno33/uofl_mobile"; public static final String URL_POST_CATALOGUE_ITEM = "api/uno33/uofl_mobile";
public static final String URL_GET_REFERENCE = API_PATH; public static final String URL_GET_REFERENCE = API_PATH;
public static final String URL_POST_ATTACHMENT = DOMAIN + "api/now/v1/attachment/file"; public static final String URL_POST_ATTACHMENT = DOMAIN + "api/now/v1/attachment/file";
......
...@@ -2,102 +2,42 @@ package com.vsoft.uoflservicenow.utils; ...@@ -2,102 +2,42 @@ package com.vsoft.uoflservicenow.utils;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/** /**
* Created by krishna on 08-31-2016. * Created by krishna on 08-31-2016.
*/ */
public class PrefManager { public class PrefManager {
private static volatile PrefManager pSelf = null;
private SharedPreferences sharedPref = null;
private SharedPreferences.Editor editor = null;
//Login Preferences //Login Preferences
public static final String PREFERENCES_USER_VALUES_KEY = "UserPrefs"; public static final String PREFERENCE_USER_VALUES_KEY = "UserPrefs";
private static final String PREFERENCES_FIRST_NAME = "firstName"; public static final String PREFERENCE_FIRST_NAME = "firstName";
private static final String PREFERENCE_LAST_NAME = "lastName"; public static final String PREFERENCE_LAST_NAME = "lastName";
public static final String PREFERENCE_SYS_ID = "sysId"; public static final String PREFERENCE_SYS_ID = "sysId";
public static final String PREFERENCE_USER_FULL_NAME = "full_name"; public static final String PREFERENCE_USER_FULL_NAME = "full_name";
public static final String PREFERENCE_USER_ID = "user_id"; public static final String PREFERENCE_USER_ID = "user_id";
public static PrefManager getInstance() { /*Access Token */
if(pSelf == null) { public static final String PREFERENCE_LOGIN_VALUES_KEY = "LoginPrefs";
synchronized(PrefManager.class) { public static final String PREFERENCE_ACCESS_TOKEN = "access_token";
if(pSelf == null) { public static final String PREFERENCE_REFRESH_TOKEN = "refresh_token";
pSelf = new PrefManager();
}
}
}
return pSelf;
}
private static final String SHARED_PREFERENCE_NAME = PrefManager.class.getSimpleName();
/** public static void setSharedPref(Context context, String key, String data) {
* save username and password in shared preferences SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCE_NAME,
* @param context Context.MODE_PRIVATE);
* @param firstName SharedPreferences.Editor editor = prefs.edit();
* @param lastName if (data == null) {
* @param sysId CatalogueLog.d(": Data is null, cannot save");
*/ return;
public static void saveUserDetailsInPreferences(Context context, String userFullName, String userId, String firstName, String lastName, String sysId) { }
SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCES_USER_VALUES_KEY, Context.MODE_PRIVATE); editor.putString(key, data);
SharedPreferences.Editor editor = sharedPreferences.edit();
/**
* some times we are getting a username with white space
* so we just removed here
*/
editor.putString(PREFERENCES_FIRST_NAME, firstName);
editor.putString(PREFERENCE_LAST_NAME, lastName);
editor.putString(PREFERENCE_SYS_ID, sysId);
editor.putString(PREFERENCE_USER_FULL_NAME, userFullName);
editor.putString(PREFERENCE_USER_ID, userId);
editor.apply(); editor.apply();
} }
public static String getSharedPref(Context context, String key) {
public void init(Context context) { SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCE_NAME,
sharedPref = PreferenceManager.getDefaultSharedPreferences(context); Context.MODE_PRIVATE);
editor = sharedPref.edit(); return prefs.getString(key, null);
}
//! Generic function to get boolean value for specified key.
public boolean getPrefValueBoolean(String mKey,boolean defValue) {
return sharedPref.getBoolean(mKey,defValue);
}
//! Generic function to get int value for specified key.
public int getPrefValueInt(String mKey, int defValue) {
return sharedPref.getInt(mKey, defValue);
}
//! Generic function to string value for specified key.
public String getPrefValueString(String mKey,String defValue) {
return sharedPref.getString(mKey, defValue);
}
public Long getPrefValueLong(String mKey,Long defValue) {
return sharedPref.getLong(mKey,defValue);
}
public void putPrefValueBoolean(String mKey,boolean mValue) {
editor.putBoolean(mKey,mValue);
editor.commit();
}
public void putPrefValueInt(String mKey,int mValue) {
editor.putInt(mKey, mValue);
editor.commit();
}
public void putPrefValueString(String mKey,String mValue) {
editor.putString(mKey, mValue);
editor.commit();
}
public void putLong(String mKey,long mValue) {
editor.putLong(mKey,mValue);
editor.commit();
} }
} }
...@@ -39,6 +39,7 @@ ...@@ -39,6 +39,7 @@
<string name="failed_to_fetch_user_detail_string">Failed to fetch User Details.</string> <string name="failed_to_fetch_user_detail_string">Failed to fetch User Details.</string>
<!--Login Screen--> <!--Login Screen-->
<string name="prompt_relogin_login_expired">Login expired, please login again&#8230;</string>
<string name="login_screen_login_string">Login</string> <string name="login_screen_login_string">Login</string>
<string name="login_screen_logging_in_loading_string">Logging in&#8230;</string> <string name="login_screen_logging_in_loading_string">Logging in&#8230;</string>
<string name="login_screen_getting_user_detail_loading_string">Getting user details&#8230;</string> <string name="login_screen_getting_user_detail_loading_string">Getting user details&#8230;</string>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment