Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Providing API version header from server to caller when available. #2757

Merged
merged 5 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions app/src/org/commcare/activities/InstallFromListActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
Expand All @@ -12,13 +11,11 @@
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.appcompat.widget.SwitchCompat;

import org.commcare.CommCareApplication;
import org.commcare.android.database.global.models.AppAvailableToInstall;
Expand All @@ -27,7 +24,6 @@
import org.commcare.core.network.AuthenticationInterceptor;
import org.commcare.dalvik.R;
import org.commcare.models.database.SqlStorage;
import org.commcare.modern.util.Pair;
import org.commcare.network.CommcareRequestGenerator;
import org.commcare.preferences.GlobalPrivilegesManager;
import org.commcare.tasks.ModernHttpTask;
Expand All @@ -48,11 +44,8 @@
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import androidx.appcompat.widget.SwitchCompat;

import com.google.common.collect.ImmutableMultimap;

/**
Expand Down Expand Up @@ -95,14 +88,14 @@ public class InstallFromListActivity<T> extends CommCareActivity<T> implements H
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setInitialValues(savedInstanceState);
setupUI();
setupUi();
if (errorMessage != null) {
enterErrorState(errorMessage);
}
loadPreviouslyRetrievedAvailableApps();
}

private void setupUI() {
private void setupUi() {
setContentView(R.layout.user_get_available_apps);
errorMessageBox = findViewById(R.id.error_message);
authenticateView = findViewById(R.id.authenticate_view);
Expand Down Expand Up @@ -228,10 +221,11 @@ protected void onSaveInstanceState(Bundle savedInstanceState) {
}

/**
* Initiates remote request for an updated app list
* @return whether a request was initiated
*/
private boolean requestAppList(String username, String password) {
String urlToTry = getURLToTry();
String urlToTry = getUrlToTry();
if (urlToTry != null) {
this.lastUsernameUsed = username;
this.lastPasswordUsed = password;
Expand Down Expand Up @@ -286,7 +280,7 @@ private void setAttemptedRequestFlag() {
}
}

private String getURLToTry() {
private String getUrlToTry() {
if (!requestedFromProd) {
urlCurrentlyRequestingFrom = PROD_URL;
} else if (!requestedFromIndia) {
Expand All @@ -306,7 +300,7 @@ private void enterErrorState(String message) {
}

@Override
public void processSuccess(int responseCode, InputStream responseData) {
public void processSuccess(int responseCode, InputStream responseData, String apiVersion) {
processResponseIntoAppsList(responseData);
saveLastSuccessfulCredentials();
repeatRequestOrShowResultsAfterSuccess();
Expand All @@ -317,7 +311,8 @@ private void processResponseIntoAppsList(InputStream responseData) {
KXmlParser baseParser = ElementParser.instantiateParser(responseData);
List<AppAvailableToInstall> apps = (new AvailableAppsParser(baseParser)).parse();
availableApps.addAll(apps);
} catch (IOException | InvalidStructureException | XmlPullParserException | UnfullfilledRequirementsException e) {
} catch (IOException | InvalidStructureException |
XmlPullParserException |UnfullfilledRequirementsException e) {
Logger.log(LogTypes.TYPE_RESOURCES, "Error encountered while parsing apps available for install");
}
}
Expand Down Expand Up @@ -346,7 +341,8 @@ public void processOther(int responseCode) {
@Override
public void handleIOException(IOException exception) {
if (exception instanceof AuthenticationInterceptor.PlainTextPasswordException) {
Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE, "Encountered PlainTextPasswordException while sending get available apps request: Sending password over HTTP");
Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE,
"Encountered PlainTextPasswordException while sending get available apps request: Sending password over HTTP");
new UserfacingErrorHandling<>().createErrorDialog(this, Localization.get("auth.over.http"), true);
} else if (exception instanceof IOException) {
Logger.log(LogTypes.TYPE_ERROR_SERVER_COMMS,
Expand Down Expand Up @@ -418,7 +414,8 @@ public View getView(int position, View convertView, ViewGroup parent) {
}

private void sortAppList() {
Collections.sort(this.availableApps, (o1, o2) -> o1.getAppName().toLowerCase().compareTo(o2.getAppName().toLowerCase()));
Collections.sort(this.availableApps,
(o1, o2) -> o1.getAppName().toLowerCase().compareTo(o2.getAppName().toLowerCase()));
}

@Override
Expand Down
13 changes: 7 additions & 6 deletions app/src/org/commcare/activities/PostRequestActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public void onCreateSessionSafe(Bundle savedInstanceState) {
loadStateFromSavedInstance(savedInstanceState);
loadStateFromIntent(getIntent());

setupUI();
setupUi();

if (!inErrorState) {
makePostRequest();
Expand All @@ -95,7 +95,7 @@ private void loadStateFromIntent(Intent intent) {
}
}

private void setupUI() {
private void setupUi() {
if (inErrorState) {
enterErrorState();
} else {
Expand All @@ -115,7 +115,7 @@ private void makePostRequest() {
RequestBody requestBody = ModernHttpRequester.getPostBody(params);
ModernHttpTask postTask =
new ModernHttpTask(this, url.toString(), ImmutableMultimap.of(),
getContentHeadersForXFormPost(requestBody), requestBody,
getContentHeadersForXformPost(requestBody), requestBody,
HTTPMethod.POST, new AuthInfo.CurrentAuth());
postTask.connect((CommCareTaskConnector)this);
postTask.executeParallel();
Expand Down Expand Up @@ -146,7 +146,7 @@ private void retryPost() {
makePostRequest();
}

private HashMap<String, String> getContentHeadersForXFormPost(RequestBody postBody) throws IOException {
private HashMap<String, String> getContentHeadersForXformPost(RequestBody postBody) throws IOException {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Content-Length", String.valueOf(postBody.contentLength()));
Expand Down Expand Up @@ -174,7 +174,7 @@ protected void updateUiAfterDataPullOrSend(String message, boolean success) {
}

@Override
public void processSuccess(int responseCode, InputStream responseData) {
public void processSuccess(int responseCode, InputStream responseData, String apiVersion) {
performSync();
}

Expand Down Expand Up @@ -223,7 +223,8 @@ public void onBackPressed() {

@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
String title, message;
String title;
String message;
switch (taskId) {
case DataPullTask.DATA_PULL_TASK_ID:
title = Localization.get("sync.communicating.title");
Expand Down
8 changes: 5 additions & 3 deletions app/src/org/commcare/activities/QueryRequestActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ protected void onSaveInstanceState(Bundle savedInstanceState) {
}

@Override
public void processSuccess(int responseCode, InputStream responseData) {
public void processSuccess(int responseCode, InputStream responseData, String apiVersion) {
// todo pass url and requestData to this callback
Pair<ExternalDataInstance, String> instanceOrError = remoteQuerySessionManager.buildExternalDataInstance(
responseData,
Expand Down Expand Up @@ -190,15 +190,17 @@ public void processOther(int responseCode) {
@Override
public void handleIOException(IOException exception) {
if (exception instanceof AuthenticationInterceptor.PlainTextPasswordException) {
enterErrorState(Localization.get("auth.request.not.using.https", remoteQuerySessionManager.getBaseUrl().toString()));
enterErrorState(Localization.get("auth.request.not.using.https",
remoteQuerySessionManager.getBaseUrl().toString()));
} else if (exception instanceof IOException) {
enterErrorState(Localization.get("post.io.error", exception.getMessage()));
}
}

@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
String title, message;
String title;
String message;
switch (taskId) {
case ModernHttpTask.SIMPLE_HTTP_TASK_ID:
title = Localization.get("query.dialog.title");
Expand Down
8 changes: 5 additions & 3 deletions app/src/org/commcare/network/GetAndParseActor.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,15 @@ public void makeRequest() {
protected final HttpResponseProcessor responseProcessor = new HttpResponseProcessor() {

@Override
public void processSuccess(int responseCode, InputStream responseStream) {
public void processSuccess(int responseCode, InputStream responseStream, String apiVersion) {
try {
String responseAsString = new String(StreamsUtil.inputStreamToByteArray(responseStream));
JSONObject jsonResponse = new JSONObject(responseAsString);
parseResponse(jsonResponse);
} catch (JSONException e) {
Logger.log(LogTypes.TYPE_ERROR_SERVER_COMMS,
String.format("%s response was not properly-formed JSON: %s", requestName, e.getMessage()));
String.format("%s response was not properly-formed JSON: %s",
requestName, e.getMessage()));
} catch (IOException e) {
Logger.log(LogTypes.TYPE_ERROR_SERVER_COMMS,
String.format("IO error while processing %s response: %s", requestName, e.getMessage()));
Expand Down Expand Up @@ -128,7 +129,8 @@ protected boolean checkForAppIdMatch(JSONObject responseAsJson) {
String.format("%s response did not have required app_id param", this.requestName));
} catch (JSONException e) {
Logger.log(LogTypes.TYPE_ERROR_SERVER_COMMS,
String.format("App id in %s response was not properly formatted: %s", this.requestName, e.getMessage()));
String.format("App id in %s response was not properly formatted: %s",
this.requestName, e.getMessage()));
}
return false;
}
Expand Down
24 changes: 14 additions & 10 deletions app/src/org/commcare/tasks/ModernHttpTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import android.content.Context;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import org.commcare.CommCareApplication;
Expand All @@ -29,8 +28,7 @@
* @author Phillip Mates ([email protected])
*/
public class ModernHttpTask
extends CommCareTask<Void, Void, Void, HttpResponseProcessor>
implements ResponseStreamAccessor {
extends CommCareTask<Void, Void, Void, HttpResponseProcessor> {

public static final int SIMPLE_HTTP_TASK_ID = 11;

Expand Down Expand Up @@ -62,7 +60,7 @@ public ModernHttpTask(Context context, String url, Multimap<String, String> para
method,
authInfo,
null,
method.equals(HTTPMethod.GET) ? true : false);
method.equals(HTTPMethod.GET));
}

@Override
Expand All @@ -75,6 +73,7 @@ protected Void doTaskBackground(Void... params) {
} catch (IOException e) {
mException = e;
}

return null;
}

Expand All @@ -89,7 +88,17 @@ protected void deliverResult(HttpResponseProcessor httpResponseProcessor,
ModernHttpRequester.processResponse(
httpResponseProcessor,
mResponse.code(),
this);
new ResponseStreamAccessor() {
@Override
public InputStream getResponseStream() {
return responseDataStream;
}

@Override
public String getApiVersion() {
return requester.getApiVersion();
}
});
}
}

Expand All @@ -102,9 +111,4 @@ protected void deliverUpdate(HttpResponseProcessor httpResponseProcessor,
protected void deliverError(HttpResponseProcessor httpResponseProcessor,
Exception e) {
}

@Override
public InputStream getResponseStream() {
return responseDataStream;
}
}
Loading