Browse Source

API connection for restaurants addition and filtering

master
Apostolos Fanakis 6 years ago
parent
commit
7b9e3416d5
  1. 88
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/AddRestaurantActivity.java
  2. 137
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainActivity.java
  3. 15
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainAdapter.java
  4. 4
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/fragments/MainMapFragment.java
  5. 29
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseApplication.java
  6. 85
      UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/session/SessionManager.java

88
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/AddRestaurantActivity.java

@ -1,6 +1,7 @@
package gr.auth.databases.flavours.activities;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
@ -18,6 +19,7 @@ import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.Calendar;
@ -28,6 +30,12 @@ import androidx.appcompat.widget.Toolbar;
import gr.auth.databases.flavours.R;
import gr.auth.databases.flavours.base.BaseActivity;
import gr.auth.databases.flavours.model.Restaurant;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static gr.auth.databases.flavours.session.SessionManager.restaurantsUrl;
public class AddRestaurantActivity extends BaseActivity implements AdapterView.OnItemSelectedListener,
TimePickerDialog.OnTimeSetListener, OnMapReadyCallback {
@ -40,6 +48,7 @@ public class AddRestaurantActivity extends BaseActivity implements AdapterView.O
.title("Restaurant location")
.snippet("Please move the marker if needed.")
.draggable(true);
private double markerLogitude, markerLatitude;
@SuppressLint("ClickableViewAccessibility")
@Override
@ -59,7 +68,7 @@ public class AddRestaurantActivity extends BaseActivity implements AdapterView.O
final EditText restaurantName = findViewById(R.id.add_restaurant_name);
Spinner spinner = findViewById(R.id.add_restaurant_type);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.restaurant_type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
@ -109,11 +118,15 @@ public class AddRestaurantActivity extends BaseActivity implements AdapterView.O
return;
}
/*Log.d("THISSS", restaurantName.getText().toString());
Log.d("THISSS", restaurantType);
Log.d("THISSS", "" + selectLocationMarker.getPosition().longitude);
Log.d("THISSS", "" + selectLocationMarker.getPosition().latitude);
Log.d("THISSS", workingHours.getText().toString());*/
String hours = workingHours.getText().toString();
AddRestaurantTask addRestaurantTask = new AddRestaurantTask();
addRestaurantTask.execute(restaurantName.getText().toString(),
restaurantType.toLowerCase(),
"" + markerLogitude, "" + markerLatitude,
hours.isEmpty() ? "" : hours.split("-")[0].trim(),
hours.isEmpty() ? "" : hours.split("-")[1].trim());
finish();
}
});
@ -221,5 +234,68 @@ public class AddRestaurantActivity extends BaseActivity implements AdapterView.O
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(selectLocationMarker);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(Thessaloniki, 12.0f));
googleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
@Override
public void onMarkerDragStart(Marker marker) {
}
@Override
public void onMarkerDrag(Marker marker) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
markerLogitude = marker.getPosition().longitude;
markerLatitude = marker.getPosition().latitude;
}
});
}
private class AddRestaurantTask extends AsyncTask<String, Void, Integer> {
private static final String REQ_RESTAURANT_NAME = "restaurant_name";
private static final String REQ_RESTAURANT_CATEGORY = "restaurant_category";
private static final String REQ_RESTAURANT_LONGITUDE = "restaurant_longitude";
private static final String REQ_RESTAURANT_LATITUDE = "restaurant_latitude";
private static final String REQ_RESTAURANT_OPENING = "restaurant_opening";
private static final String REQ_RESTAURANT_CLOSING = "restaurant_closing";
@Override
protected void onPreExecute() { //Show a progress dialog until done
}
@Override
protected Integer doInBackground(String... params) {
//Builds the signup request
RequestBody formBody = new FormBody.Builder()
.add(REQ_RESTAURANT_NAME, params[0])
.add(REQ_RESTAURANT_CATEGORY, params[1])
.add(REQ_RESTAURANT_LONGITUDE, params[2])
.add(REQ_RESTAURANT_LATITUDE, params[3])
.add(REQ_RESTAURANT_OPENING, params[4])
.add(REQ_RESTAURANT_CLOSING, params[5])
.build();
Request request = new Request.Builder()
.url(restaurantsUrl)
.post(formBody)
.build();
try {
//Makes request & handles response
Response response = client.newCall(request).execute();
if (response.code() == 201) {
Toast.makeText(AddRestaurantActivity.this,
"Restaurant was added and awaits approval!", Toast.LENGTH_SHORT).show();
return 0;
}
return 1;
} catch (Exception e) {
return 2;
}
}
@Override
protected void onPostExecute(Integer result) { //Handle attempt result
}
}
}

137
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainActivity.java

@ -1,10 +1,15 @@
package gr.auth.databases.flavours.activities.main;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
@ -34,12 +39,14 @@ import gr.auth.databases.flavours.activities.main.fragments.MainListFragment;
import gr.auth.databases.flavours.activities.main.fragments.MainMapFragment;
import gr.auth.databases.flavours.base.BaseActivity;
import gr.auth.databases.flavours.model.Restaurant;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import static gr.auth.databases.flavours.session.SessionManager.restaurantsUrl;
public class MainActivity extends BaseActivity {
private static final HttpUrl restaurantsUrl = HttpUrl.parse("http://83.212.109.171:8181/api/restaurant/");
private static final int LOCATION_PERMISSIONS_REQUEST_CODE_FOR_DISTANCE_FILTER = 9000;
private static final int NUM_PAGES = 2;
private ArrayList<Restaurant> restaurants = new ArrayList<>();
@ -47,7 +54,7 @@ public class MainActivity extends BaseActivity {
private ViewPager viewPager;
private MenuItem menuMapItem;
private FloatingActionButton FAB;
private ArrayList<Integer> mSelectedRestaurantTypes;
private ArrayList<Integer> mSelectedRestaurantTypes = new ArrayList<>();
private int maxDistance = -1, maxCalories = -1;
@Override
@ -139,8 +146,6 @@ public class MainActivity extends BaseActivity {
switch (item.getItemId()) {
case R.id.main_filters_type:
mSelectedRestaurantTypes = new ArrayList<>();
builder.setTitle(R.string.main_filters_menu_type)
.setMultiChoiceItems(R.array.restaurant_type, null,
new DialogInterface.OnMultiChoiceClickListener() {
@ -159,7 +164,8 @@ public class MainActivity extends BaseActivity {
.setPositiveButton(R.string.main_filters_dialog_positive, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//TODO
MainTask mainTask = new MainTask();
mainTask.execute();
}
})
.setNegativeButton(R.string.main_filters_dialog_cancel, new DialogInterface.OnClickListener() {
@ -183,6 +189,18 @@ public class MainActivity extends BaseActivity {
if (!distanceString.isEmpty()) {
maxDistance = Integer.parseInt(distanceString);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS_LOCATION = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
requestPermissions(PERMISSIONS_LOCATION, LOCATION_PERMISSIONS_REQUEST_CODE_FOR_DISTANCE_FILTER);
} else {
MainTask mainTask = new MainTask();
mainTask.execute();
}
}
}
})
.setNegativeButton(R.string.main_filters_dialog_cancel, new DialogInterface.OnClickListener() {
@ -205,6 +223,8 @@ public class MainActivity extends BaseActivity {
if (!caloriesString.isEmpty()) {
maxCalories = Integer.parseInt(caloriesString);
}
MainTask mainTask = new MainTask();
mainTask.execute();
}
})
.setNegativeButton(R.string.main_filters_dialog_cancel, new DialogInterface.OnClickListener() {
@ -215,7 +235,11 @@ public class MainActivity extends BaseActivity {
builder.create().show();
break;
case R.id.main_filters_clear:
//TODO
mSelectedRestaurantTypes.clear();
maxDistance = -1;
maxCalories = -1;
MainTask mainTask = new MainTask();
mainTask.execute();
break;
}
return false;
@ -238,44 +262,6 @@ public class MainActivity extends BaseActivity {
return super.onOptionsItemSelected(item);
}
/*private void setupViewPager(ViewPager viewPager) {
RestaurantPagerAdapter adapter = new RestaurantPagerAdapter(getSupportFragmentManager());
adapter.addFrag(DrinkInfoFragment.newInstance(64), "INFO");
adapter.addFrag(DrinkIngredientsFragment.newInstance(64), "INGREDIENTS");
adapter.addFrag(DrinkRatingsFragment.newInstance(64), "RATINGS");
viewPager.setAdapter(adapter);
}
private class MainPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
MainPagerAdapter(FragmentManager manager) {
super(manager);
}
@NonNull
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}*/
private class MainPagerAdapter extends FragmentStatePagerAdapter {
MainPagerAdapter(FragmentManager fm) {
super(fm);
@ -297,6 +283,14 @@ public class MainActivity extends BaseActivity {
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == LOCATION_PERMISSIONS_REQUEST_CODE_FOR_DISTANCE_FILTER) {
MainTask mainTask = new MainTask();
mainTask.execute();
}
}
private class MainTask extends AsyncTask<Void, Void, Integer> {
private static final String JSON_TAG_RESTAURANT_ID = "restaurant_id";
private static final String JSON_TAG_RESTAURANT_NAME = "restaurant_name";
@ -308,20 +302,64 @@ public class MainActivity extends BaseActivity {
@Override
protected void onPreExecute() { //Show a progress dialog until done
restaurants.clear();
}
@Override
protected Integer doInBackground(Void... params) {
StringBuilder requestUrl = new StringBuilder(restaurantsUrl);
if (!mSelectedRestaurantTypes.isEmpty()) {
requestUrl.append("?filter_restaurant_type=");
for (int typeIndex : mSelectedRestaurantTypes) {
requestUrl.append(Restaurant.RestaurantType.getWorkingTypeFromId(typeIndex));
}
}
if (maxDistance != -1) {
if (!mSelectedRestaurantTypes.isEmpty()) {
requestUrl.append("&");
} else {
requestUrl.append("?");
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// get the last know location from your location manager.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS_LOCATION = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
requestPermissions(PERMISSIONS_LOCATION, LOCATION_PERMISSIONS_REQUEST_CODE_FOR_DISTANCE_FILTER);
return 3;
}
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
requestUrl.append("filter_restaurant_radius=").append(maxDistance * 1. / 1000)
.append("&filter_restaurant_longitude=").append(location.getLongitude())
.append("&filter_restaurant_latitude=").append(location.getLatitude());
}
if (maxCalories != -1) {
if (!mSelectedRestaurantTypes.isEmpty() || maxDistance != -1) {
requestUrl.append("&");
} else {
requestUrl.append("?");
}
requestUrl.append("filter_restaurant_calories=").append(maxCalories);
}
//Builds the signup request
Request request = new Request.Builder()
.url(restaurantsUrl)
.url(requestUrl.toString())
.build();
try {
//Makes request & handles response
Response response = client.newCall(request).execute();
String result = response.body().string();
ResponseBody responseBody = response.body();
assert responseBody != null;
String result = responseBody.string();
JSONArray jsonRestaurants = new JSONArray(result);
for (int restaurantIndex = 0; restaurantIndex < jsonRestaurants.length(); ++restaurantIndex) {
@ -343,6 +381,9 @@ public class MainActivity extends BaseActivity {
@Override
protected void onPostExecute(Integer result) { //Handle attempt result
viewPager.setAdapter(null);
PagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
}

15
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/MainAdapter.java

@ -2,7 +2,6 @@ package gr.auth.databases.flavours.activities.main;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@ -46,9 +45,15 @@ public class MainAdapter extends RecyclerView.Adapter<MainAdapter.RestaurantView
}
});
holder.name.setText(restaurants.get(position).getName());
holder.workingHours.setText(context.getString(R.string.main_row_working_hours_placeholder,
restaurants.get(position).getOpeningTime().substring(0, 5),
restaurants.get(position).getClosingTime().substring(0, 5)));
if (!restaurants.get(position).getOpeningTime().equals("null") &&
!restaurants.get(position).getClosingTime().equals("null")) {
holder.workingHours.setVisibility(View.VISIBLE);
holder.workingHours.setText(context.getString(R.string.main_row_working_hours_placeholder,
restaurants.get(position).getOpeningTime().substring(0, 5),
restaurants.get(position).getClosingTime().substring(0, 5)));
} else {
holder.workingHours.setVisibility(View.GONE);
}
switch (restaurants.get(position).getType()) {
case "restaurant":
@ -67,7 +72,7 @@ public class MainAdapter extends RecyclerView.Adapter<MainAdapter.RestaurantView
holder.typeImage.setImageResource(R.drawable.pub_marker);
holder.typeText.setText(context.getResources().getString(R.string.main_pub_type));
break;
case "fast_food":
case "fast food":
holder.typeImage.setImageResource(R.drawable.fast_food_marker);
holder.typeText.setText(context.getResources().getString(R.string.main_fast_food_type));
break;

4
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/activities/main/fragments/MainMapFragment.java

@ -112,7 +112,7 @@ public class MainMapFragment extends Fragment implements OnMapReadyCallback {
public void onMapReady(GoogleMap googleMap) {
// Add markers and move the camera
for (Restaurant restaurant : restaurants) {
LatLng restaurantPosition = new LatLng(restaurant.getLongitude(), restaurant.getLatitude());
LatLng restaurantPosition = new LatLng(restaurant.getLatitude(), restaurant.getLongitude());
switch (restaurant.getType()) {
case "restaurant":
@ -139,7 +139,7 @@ public class MainMapFragment extends Fragment implements OnMapReadyCallback {
.title(restaurant.getName())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pub_marker)));
break;
case "fast_food":
case "fast food":
googleMap.addMarker(new MarkerOptions()
.position(restaurantPosition)
.title(restaurant.getName())

29
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/base/BaseApplication.java

@ -9,12 +9,19 @@ import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import androidx.annotation.NonNull;
import gr.auth.databases.flavours.session.SessionManager;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class BaseApplication extends Application {
public static final String CSRF_TOKEN = "CSRF_TOKEN";
private static BaseApplication baseApplication; //BaseApplication singleton
//Client & SessionManager
@ -35,7 +42,7 @@ public class BaseApplication extends Application {
baseApplication = this; //init singleton
//Shared Preferences
SharedPreferences sharedPrefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
final SharedPreferences sharedPrefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPrefsCookiePersistor sharedPrefsCookiePersistor = new SharedPrefsCookiePersistor(getApplicationContext());
PersistentCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), sharedPrefsCookiePersistor);
@ -43,11 +50,27 @@ public class BaseApplication extends Application {
.cookieJar(cookieJar)
.connectTimeout(40, TimeUnit.SECONDS)
.writeTimeout(40, TimeUnit.SECONDS)
.readTimeout(40, TimeUnit.SECONDS);
.readTimeout(40, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
final Request original = chain.request();
String csrfToken = sharedPrefs.getString(CSRF_TOKEN, "too soon to have a token");
assert csrfToken != null;
final Request authorized = original.newBuilder()
.addHeader("X-CSRFToken", csrfToken)
.build();
return chain.proceed(authorized);
}
});
client = builder.build();
sessionManager = new SessionManager(client, cookieJar, sharedPrefsCookiePersistor, sharedPrefs);
sessionManager = new SessionManager(client, cookieJar, sharedPrefs);
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
dpWidth = displayMetrics.widthPixels / displayMetrics.density;

85
UI/AndroidApp/flavoursWithoutBorders/app/src/main/java/gr/auth/databases/flavours/session/SessionManager.java

@ -1,10 +1,10 @@
package gr.auth.databases.flavours.session;
import android.content.SharedPreferences;
import android.util.Log;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import org.json.JSONObject;
import java.util.List;
@ -15,6 +15,9 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import static gr.auth.databases.flavours.base.BaseApplication.CSRF_TOKEN;
public class SessionManager {
public enum UserType {
@ -45,14 +48,17 @@ public class SessionManager {
}
//Generic constants
private static final HttpUrl loginUrl = HttpUrl.parse("http://83.212.109.171:8181/api/rest-auth/login/");
private static final HttpUrl signupUrl = HttpUrl.parse("http://83.212.109.171:8181/api/rest-auth/registration/");
private static final HttpUrl logoutUrl = HttpUrl.parse("http://83.212.109.171:8181/api/rest-auth/logout/");
public static final String baseServerUrl = "http://83.212.109.171:8181/";
public static final String loginUrl = baseServerUrl + "api/rest-auth/login/";
public static final String signupUrl = baseServerUrl + "api/rest-auth/registration/";
public static final String logoutUrl = baseServerUrl + "api/rest-auth/logout/";
public static final String setUserBirthday = baseServerUrl + "api/setUserBirthday/";
public static final String restaurantsUrl = baseServerUrl + "api/restaurant/";
// Client & Cookies
private final OkHttpClient client;
private final PersistentCookieJar cookieJar;
private final SharedPrefsCookiePersistor cookiePersistor; //Used to explicitly edit cookies in cookieJar
//private final SharedPrefsCookiePersistor cookiePersistor;
//Shared Preferences & its keys
private final SharedPreferences sharedPrefs;
@ -63,10 +69,8 @@ public class SessionManager {
private static final String LOGIN_SCREEN_AS_DEFAULT = "LoginScreenAsDefault";
//Constructor
public SessionManager(OkHttpClient client, PersistentCookieJar cookieJar,
SharedPrefsCookiePersistor cookiePersistor, SharedPreferences sharedPrefs) {
public SessionManager(OkHttpClient client, PersistentCookieJar cookieJar, SharedPreferences sharedPrefs) {
this.client = client;
this.cookiePersistor = cookiePersistor;
this.cookieJar = cookieJar;
this.sharedPrefs = sharedPrefs;
}
@ -95,13 +99,20 @@ public class SessionManager {
setPersistentCookieSession(loginUrl); //Store cookies
ResponseBody responseBody = response.body();
assert responseBody != null;
JSONObject jsonResponse = new JSONObject(responseBody.string());
JSONObject jsonUser = jsonResponse.getJSONObject("user");
int extractedUserId = jsonUser.getInt("id");
int extractedRole = jsonUser.getInt("role");
//Edit SharedPreferences, save session's data
SharedPreferences.Editor editor = sharedPrefs.edit();
setLoginScreenAsDefault(false);
editor.putBoolean(LOGGED_IN, true);
editor.putString(USERNAME, username);
editor.putInt(USER_ID, 10);
editor.putInt(USER_TYPE, UserType.USER.getId());
editor.putInt(USER_ID, extractedUserId);
editor.putInt(USER_TYPE, extractedRole);
editor.apply();
return 0;
} catch (Exception e) {
@ -137,14 +148,37 @@ public class SessionManager {
setPersistentCookieSession(signupUrl); //Store cookies
ResponseBody responseBody = response.body();
assert responseBody != null;
JSONObject jsonResponse = new JSONObject(responseBody.string());
JSONObject jsonUser = jsonResponse.getJSONObject("user");
int extractedUserId = jsonUser.getInt("id");
int extractedRole = jsonUser.getInt("role");
//Edit SharedPreferences, save session's data
SharedPreferences.Editor editor = sharedPrefs.edit();
setLoginScreenAsDefault(false);
editor.putBoolean(LOGGED_IN, true);
editor.putString(USERNAME, username);
editor.putInt(USER_ID, 10);
editor.putInt(USER_TYPE, UserType.USER.getId());
editor.putInt(USER_ID, extractedUserId);
editor.putInt(USER_TYPE, extractedRole);
editor.apply();
} catch (Exception e) {
e.printStackTrace();
return 2;
}
formBody = new FormBody.Builder()
.add("user_age", birthday)
.build();
request = new Request.Builder()
.url(setUserBirthday + getUserId() + "/")
.put(formBody)
.build();
try {
//Makes request & handles response
client.newCall(request).execute();
return 0;
} catch (Exception e) {
return 2;
@ -164,13 +198,17 @@ public class SessionManager {
}
public int logout() {
RequestBody requestBody = RequestBody.create(null, new byte[]{});
Request request = new Request.Builder()
.url(logoutUrl)
.method("POST", requestBody)
.header("Content-Length", "0")
.build();
try {
//Makes request & handles response
Response response = client.newCall(request).execute();
client.newCall(request).execute();
} catch (Exception e) {
return 2;
} finally {
@ -201,18 +239,14 @@ public class SessionManager {
return sharedPrefs.getBoolean(LOGIN_SCREEN_AS_DEFAULT, true);
}
private void setPersistentCookieSession(HttpUrl forUrl) {
List<Cookie> cookieList = cookieJar.loadForRequest(forUrl);
Cookie.Builder builder = new Cookie.Builder();
builder.name(cookieList.get(1).name())
.value(cookieList.get(1).value())
.domain(cookieList.get(1).domain())
.expiresAt(cookieList.get(0).expiresAt());
cookieList.remove(1);
cookieList.add(builder.build());
cookiePersistor.clear();
cookiePersistor.saveAll(cookieList);
private void setPersistentCookieSession(String forUrl) {
HttpUrl httpUrl = HttpUrl.parse(forUrl);
assert httpUrl != null;
List<Cookie> cookieList = cookieJar.loadForRequest(httpUrl);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(CSRF_TOKEN, cookieList.get(0).value());
editor.apply();
}
private void clearSessionData() {
@ -222,6 +256,7 @@ public class SessionManager {
sharedPrefs.edit().putInt(USER_ID, -1).apply();
sharedPrefs.edit().putInt(USER_TYPE, -1).apply();
sharedPrefs.edit().putBoolean(LOGGED_IN, false).apply(); //User logs out
setLoginScreenAsDefault(true);
}
private void setLoginScreenAsDefault(boolean b) {

Loading…
Cancel
Save