Skip to content

Commit

Permalink
Merge pull request #1071 from mobreza/brapi-observation-sync
Browse files Browse the repository at this point in the history
BrAPI: Fix handling of lastSyncedTime
  • Loading branch information
trife authored Dec 4, 2024
2 parents 9226f15 + 72b7c24 commit e29bab9
Show file tree
Hide file tree
Showing 9 changed files with 148 additions and 117 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -707,13 +707,6 @@ public void onBackPressed() {
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == 2) {
if (resultCode == RESULT_OK) {
final String chosenFile = data.getStringExtra("result");
showFieldFileDialog(chosenFile, null);
}
}

if (requestCode == REQUEST_FILE_EXPLORER_CODE) {
if (resultCode == RESULT_OK) {
final String chosenFile = data.getStringExtra(FileExploreActivity.EXTRA_RESULT_KEY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.fieldbook.tracker.activities.ThemedActivity;
import com.fieldbook.tracker.preferences.GeneralKeys;

import net.openid.appauth.AppAuthConfiguration;
import net.openid.appauth.AuthorizationException;
import net.openid.appauth.AuthorizationRequest;
import net.openid.appauth.AuthorizationResponse;
Expand Down Expand Up @@ -114,6 +115,38 @@ public void onResume() {
private static final String HTTP = "http";
private static final String HTTPS = "https";

private ConnectionBuilder getConnectionBuilder() {
return uri -> {
Log.d("ConnectionBuilder", "DOING CUSTOM URL");
Preconditions.checkNotNull(uri, "url must not be null");
Preconditions.checkArgument(HTTP.equals(uri.getScheme()) || HTTPS.equals(uri.getScheme()),
"scheme or uri must be http or https");
HttpURLConnection conn = (HttpURLConnection) new URL(uri.toString()).openConnection();
// conn.setConnectTimeout(CONNECTION_TIMEOUT_MS);
// conn.setReadTimeout(READ_TIMEOUT_MS);
conn.setInstanceFollowRedirects(true);

// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
conn.disconnect();
// open the new connection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
} else {
conn = (HttpURLConnection) new URL(uri.toString()).openConnection();
}

return conn;
};
}

public void authorizeBrAPI(SharedPreferences sharedPreferences, Context context) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(GeneralKeys.BRAPI_TOKEN, null);
Expand All @@ -133,35 +166,7 @@ public void authorizeBrAPI(SharedPreferences sharedPreferences, Context context)
Uri.parse("https://phenoapps.org/field-book") : Uri.parse("fieldbook://app/auth");
Uri oidcConfigURI = Uri.parse(sharedPreferences.getString(GeneralKeys.BRAPI_OIDC_URL, ""));

ConnectionBuilder builder = uri -> {

Preconditions.checkNotNull(uri, "url must not be null");
Preconditions.checkArgument(HTTP.equals(uri.getScheme()) || HTTPS.equals(uri.getScheme()),
"scheme or uri must be http or https");
HttpURLConnection conn = (HttpURLConnection) new URL(uri.toString()).openConnection();
// conn.setConnectTimeout(CONNECTION_TIMEOUT_MS);
// conn.setReadTimeout(READ_TIMEOUT_MS);
conn.setInstanceFollowRedirects(true);

// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
conn.disconnect();
// open the new connection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
} else {
conn = (HttpURLConnection) new URL(uri.toString()).openConnection();
}

return conn;
};
ConnectionBuilder builder = getConnectionBuilder();

AuthorizationServiceConfiguration.fetchFromUrl(oidcConfigURI,
new AuthorizationServiceConfiguration.RetrieveConfigurationCallback() {
Expand Down Expand Up @@ -220,7 +225,7 @@ private void requestAuthorization(

AuthorizationRequest authRequest = authRequestBuilder.setPrompt("login").build();

AuthorizationService authService = new AuthorizationService(context);
AuthorizationService authService = getAuthorizationService();

Intent responseIntent = new Intent(context, BrapiAuthActivity.class);
responseIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Expand Down Expand Up @@ -307,8 +312,18 @@ public void checkBrapiAuth_OLD(Uri data) {
}
}

/**
* Create an instance of AuthorizationService with custom connection builder.
* @return Configured auth service
*/
private AuthorizationService getAuthorizationService() {
AppAuthConfiguration.Builder builder = new AppAuthConfiguration.Builder();
builder.setConnectionBuilder(getConnectionBuilder());
return new AuthorizationService(this, builder.build());
}

public void checkBrapiAuth(Uri data) {
AuthorizationService authService = new AuthorizationService(this);
AuthorizationService authService = getAuthorizationService();
AuthorizationException ex = AuthorizationException.fromIntent(getIntent());
AuthorizationResponse response = AuthorizationResponse.fromIntent(getIntent());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,18 @@ class BrapiStudyImportActivity : ThemedActivity(), CoroutineScope by MainScope()
studyList.adapter?.notifyDataSetChanged()

}

if (existingLevels().isEmpty()) {
listView.visibility = View.GONE
}
}

private fun getAttributeKeys() = attributesTable?.values?.flatMap { it.values }?.flatMap { it.keys }?.distinct() ?: listOf()

private fun setSortListOptions() {

listView.visibility = View.VISIBLE

listView.adapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_single_choice,
Expand All @@ -290,6 +296,8 @@ class BrapiStudyImportActivity : ThemedActivity(), CoroutineScope by MainScope()

private fun setPrimaryOrderListOptions() {

listView.visibility = View.VISIBLE

val attributes = getAttributeKeys()

listView.adapter = ArrayAdapter(
Expand All @@ -316,6 +324,8 @@ class BrapiStudyImportActivity : ThemedActivity(), CoroutineScope by MainScope()

private fun setSecondaryOrderListOptions() {

listView.visibility = View.VISIBLE

val attributes = getAttributeKeys()

listView.adapter = ArrayAdapter(
Expand Down Expand Up @@ -609,7 +619,11 @@ class BrapiStudyImportActivity : ThemedActivity(), CoroutineScope by MainScope()

val level = BrapiObservationLevel().also {
it.observationLevelName = try {
existingLevels().elementAt(selectedLevel)
if (selectedLevel in existingLevels().indices) {
existingLevels().elementAt(selectedLevel)
} else {
"plot"
}
} catch (e: Exception) {
Log.e(TAG, "Failed to get observation level", e)
finish()
Expand All @@ -619,7 +633,9 @@ class BrapiStudyImportActivity : ThemedActivity(), CoroutineScope by MainScope()

attributesTable?.get(study.studyDbId)?.let { studyAttributes ->

observationUnits[study.studyDbId]?.filter { it.observationUnitPosition.observationLevel.levelName == level.observationLevelName }
observationUnits[study.studyDbId]?.filter {
if (it.observationUnitPosition.entryType.name == "TEST") true
else it.observationUnitPosition.observationLevel.levelName == level.observationLevelName }
?.let { units ->

val details = BrapiStudyDetails()
Expand Down Expand Up @@ -731,7 +747,7 @@ class BrapiStudyImportActivity : ThemedActivity(), CoroutineScope by MainScope()
models.forEach { unit ->

(unit as? BrAPIGermplasm)?.let { g ->
Log.d("Unit", g.germplasmName)
Log.d("Unit", g.germplasmName ?: "No name")
germs.add(g)
if (total == germs.size) {
germplasms.getOrPut(studyDbId) { hashSetOf() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ public class StatisticsAdapter extends RecyclerView.Adapter<StatisticsAdapter.Vi
DataHelper database;
List<String> seasons;
private final SimpleDateFormat timeStampFormat;
private final SimpleDateFormat failTimeStampFormat;
private static final String TIME_STAMP_PATTERN = "yyyy-MM-dd HH:mm:ss.SSSZZZZZ";
private static final String FAIL_TIME_STAMP_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static final String DATE_FORMAT_PATTERN = "MM-dd-yy";
private static final String YEAR_MONTH_PATTERN = "yyyy-MM";
private static final String MONTH_VIEW_CARD_TITLE_PATTERN ="MMMM yyyy";
Expand All @@ -67,6 +69,7 @@ public StatisticsAdapter(StatisticsActivity context, List<String> seasons, Stati
this.database = originActivity.getDatabase();
this.seasons = seasons;
this.timeStampFormat = new SimpleDateFormat(TIME_STAMP_PATTERN, Locale.getDefault());
this.failTimeStampFormat = new SimpleDateFormat(FAIL_TIME_STAMP_PATTERN, Locale.getDefault());
this.yearMonthFormat = new SimpleDateFormat(YEAR_MONTH_PATTERN, Locale.getDefault());
this.monthViewCardTitle = new SimpleDateFormat(MONTH_VIEW_CARD_TITLE_PATTERN, Locale.getDefault());
this.cardType = cardType;
Expand Down Expand Up @@ -123,7 +126,16 @@ public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
try {
dateObject = timeStampFormat.parse(time);
} catch (ParseException e) {
throw new RuntimeException(e);
try {
if (time != null) {
String split = time.split("\\.")[0];
dateObject = failTimeStampFormat.parse(split);
} else {
dateObject = new Date();
}
} catch (ParseException pe) {
throw new RuntimeException(pe);
}
}
dateObjects.add(dateObject);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ public OffsetDateTime getLastSyncedTime() {
public void setLastSyncedTime(String timestamp) {
this.lastSyncedTime = convertTime(timestamp);
}
public void setLastSyncedTime(OffsetDateTime timestamp) {
this.lastSyncedTime = timestamp;
}

public BrapiObservation.Status getStatus() {

Expand All @@ -74,9 +77,9 @@ public BrapiObservation.Status getStatus() {
status = BrapiObservation.Status.NEW;
} else if (lastSyncedTime == null) {
status = BrapiObservation.Status.INCOMPLETE;
} else if (dbId != null && lastSyncedTime != null && timestamp != null && timestamp.compareTo(lastSyncedTime) < 0) {
} else if (timestamp == null || timestamp.compareTo(lastSyncedTime) <= 0) {
status = BrapiObservation.Status.SYNCED;
} else if (dbId != null && lastSyncedTime != null && timestamp != null && timestamp.compareTo(lastSyncedTime) > 0) {
} else if (timestamp != null && timestamp.compareTo(lastSyncedTime) > 0) {
status = BrapiObservation.Status.EDITED;
}

Expand Down
Loading

0 comments on commit e29bab9

Please sign in to comment.