use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.
the class ExternalAppsUtils method getValueRepresentedBy.
public static Object getValueRepresentedBy(String text, TreeReference reference) throws XPathSyntaxException {
if (text.startsWith("'")) {
// treat this as a constant parameter but not require an ending quote
return text.endsWith("'") ? text.substring(1, text.length() - 1) : text.substring(1);
}
FormDef formDef = Collect.getInstance().getFormController().getFormDef();
FormInstance formInstance = formDef.getInstance();
EvaluationContext evaluationContext = new EvaluationContext(formDef.getEvaluationContext(), reference);
if (text.startsWith("/")) {
// treat this is an xpath
XPathPathExpr pathExpr = XPathReference.getPathExpr(text);
XPathNodeset xpathNodeset = pathExpr.eval(formInstance, evaluationContext);
return XPathFuncExpr.unpack(xpathNodeset);
} else if (text.equals("instanceProviderID()")) {
// instanceProviderID returns -1 if the current instance has not been saved to disk already
String path = Collect.getInstance().getFormController().getInstanceFile().getAbsolutePath();
String instanceProviderID = "-1";
Instance instance = new InstancesRepositoryProvider(Collect.getInstance()).get().getOneByPath(path);
if (instance != null) {
instanceProviderID = instance.getDbId().toString();
}
return instanceProviderID;
} else {
// treat this as a function
XPathExpression xpathExpression = XPathParseTool.parseXPath(text);
return xpathExpression.eval(formInstance, evaluationContext);
}
}
use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.
the class InstanceSubmitter method submitInstances.
public Pair<Boolean, String> submitInstances(List<Instance> toUpload) throws SubmitException {
if (toUpload.isEmpty()) {
throw new SubmitException(Type.NOTHING_TO_SUBMIT);
}
String protocol = generalSettings.getString(ProjectKeys.KEY_PROTOCOL);
InstanceUploader uploader;
Map<String, String> resultMessagesByInstanceId = new HashMap<>();
String deviceId = null;
boolean anyFailure = false;
if (protocol.equals(ProjectKeys.PROTOCOL_GOOGLE_SHEETS)) {
if (permissionsProvider.isGetAccountsPermissionGranted()) {
String googleUsername = googleAccountsManager.getLastSelectedAccountIfValid();
if (googleUsername.isEmpty()) {
throw new SubmitException(Type.GOOGLE_ACCOUNT_NOT_SET);
}
googleAccountsManager.selectAccount(googleUsername);
uploader = new InstanceGoogleSheetsUploader(googleApiProvider.getDriveApi(googleUsername), googleApiProvider.getSheetsApi(googleUsername));
} else {
throw new SubmitException(Type.GOOGLE_ACCOUNT_NOT_PERMITTED);
}
} else {
OpenRosaHttpInterface httpInterface = Collect.getInstance().getComponent().openRosaHttpInterface();
uploader = new InstanceServerUploader(httpInterface, new WebCredentialsUtils(generalSettings), new HashMap<>(), generalSettings);
deviceId = new PropertyManager().getSingularProperty(PropertyManager.PROPMGR_DEVICE_ID);
}
for (Instance instance : toUpload) {
try {
String destinationUrl;
if (protocol.equals(ProjectKeys.PROTOCOL_GOOGLE_SHEETS)) {
destinationUrl = uploader.getUrlToSubmitTo(instance, null, null, generalSettings.getString(KEY_GOOGLE_SHEETS_URL));
if (!InstanceUploaderUtils.doesUrlRefersToGoogleSheetsFile(destinationUrl)) {
anyFailure = true;
resultMessagesByInstanceId.put(instance.getDbId().toString(), SPREADSHEET_UPLOADED_TO_GOOGLE_DRIVE);
continue;
}
} else {
destinationUrl = uploader.getUrlToSubmitTo(instance, deviceId, null, null);
}
String customMessage = uploader.uploadOneSubmission(instance, destinationUrl);
resultMessagesByInstanceId.put(instance.getDbId().toString(), customMessage != null ? customMessage : getLocalizedString(Collect.getInstance(), R.string.success));
// communicated to the user. Maybe successful delete should also be communicated?
if (InstanceUploaderUtils.shouldFormBeDeleted(formsRepository, instance.getFormId(), instance.getFormVersion(), generalSettings.getBoolean(ProjectKeys.KEY_DELETE_AFTER_SEND))) {
new InstanceDeleter(new InstancesRepositoryProvider(Collect.getInstance()).get(), new FormsRepositoryProvider(Collect.getInstance()).get()).delete(instance.getDbId());
}
String action = protocol.equals(ProjectKeys.PROTOCOL_GOOGLE_SHEETS) ? "HTTP-Sheets auto" : "HTTP auto";
String label = Collect.getFormIdentifierHash(instance.getFormId(), instance.getFormVersion());
analytics.logEvent(SUBMISSION, action, label);
} catch (UploadException e) {
Timber.d(e);
anyFailure = true;
resultMessagesByInstanceId.put(instance.getDbId().toString(), e.getDisplayMessage());
}
}
return new Pair<>(anyFailure, InstanceUploaderUtils.getUploadResultMessage(instancesRepository, Collect.getInstance(), resultMessagesByInstanceId));
}
use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.
the class FormEntryActivity method loadFromIntent.
private void loadFromIntent(Intent intent) {
Uri uri = intent.getData();
String uriMimeType = null;
if (uri != null) {
uriMimeType = getContentResolver().getType(uri);
}
if (uriMimeType != null && uriMimeType.equals(InstancesContract.CONTENT_ITEM_TYPE)) {
Instance instance = new InstancesRepositoryProvider(Collect.getInstance()).get().get(ContentUriHelper.getIdFromUri(uri));
if (instance == null) {
createErrorDialog(getString(R.string.bad_uri, uri), true);
return;
}
instancePath = instance.getInstanceFilePath();
if (!new File(instancePath).exists()) {
analytics.logEvent(AnalyticsEvents.OPEN_DELETED_INSTANCE);
new InstanceDeleter(new InstancesRepositoryProvider(Collect.getInstance()).get(), formsRepository).delete(instance.getDbId());
createErrorDialog(getString(R.string.instance_deleted_message), true);
return;
}
List<Form> candidateForms = formsRepository.getAllByFormIdAndVersion(instance.getFormId(), instance.getFormVersion());
if (candidateForms.isEmpty()) {
createErrorDialog(getString(R.string.parent_form_not_present, instance.getFormId()) + ((instance.getFormVersion() == null) ? "" : "\n" + getString(R.string.version) + " " + instance.getFormVersion()), true);
return;
} else if (candidateForms.stream().filter(f -> !f.isDeleted()).count() > 1) {
createErrorDialog(getString(R.string.survey_multiple_forms_error), true);
return;
}
formPath = candidateForms.get(0).getFormFilePath();
} else if (uriMimeType != null && uriMimeType.equals(FormsContract.CONTENT_ITEM_TYPE)) {
Form form = formsRepositoryProvider.get().get(ContentUriHelper.getIdFromUri(uri));
if (form != null) {
formPath = form.getFormFilePath();
}
if (formPath == null) {
createErrorDialog(getString(R.string.bad_uri, uri), true);
return;
} else {
/**
* This is the fill-blank-form code path.See if there is a savepoint for this form
* that has never been explicitly saved by the user. If there is, open this savepoint(resume this filled-in form).
* Savepoints for forms that were explicitly saved will be recovered when that
* explicitly saved instance is edited via edit-saved-form.
*/
instancePath = loadSavePoint();
}
} else {
Timber.i("Unrecognized URI: %s", uri);
createErrorDialog(getString(R.string.unrecognized_uri, uri), true);
return;
}
formLoaderTask = new FormLoaderTask(instancePath, null, null);
showIfNotShowing(FormLoadingDialogFragment.class, getSupportFragmentManager());
formLoaderTask.execute(formPath);
}
use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.
the class InstancesDaoHelper method isInstanceComplete.
/**
* Checks the database to determine if the current instance being edited has
* already been 'marked completed'. A form can be 'unmarked' complete and
* then resaved.
*
* @return true if form has been marked completed, false otherwise.
* <p>
* TODO: replace with method in {@link InstancesRepository}
* that returns an {@link Instance} object from a path.
*/
public static boolean isInstanceComplete(boolean end, boolean completedByDefault) {
// default to false if we're mid form
boolean complete = false;
FormController formController = Collect.getInstance().getFormController();
if (formController != null && formController.getInstanceFile() != null) {
// First check if we're at the end of the form, then check the preferences
complete = end && completedByDefault;
// Then see if we've already marked this form as complete before
String path = formController.getInstanceFile().getAbsolutePath();
Instance instance = new InstancesRepositoryProvider(Collect.getInstance()).get().getOneByPath(path);
if (instance != null && instance.getStatus().equals(Instance.STATUS_COMPLETE)) {
complete = true;
}
} else {
Timber.w("FormController or its instanceFile field has a null value");
}
return complete;
}
use of org.odk.collect.android.utilities.InstancesRepositoryProvider in project collect by opendatakit.
the class SaveFormToDisk method updateInstanceDatabase.
/**
* Updates the status and editability for the database row corresponding to the instance that is
* currently managed by the {@link FormController}. There are three cases:
* - the instance was opened for edit so its database row already exists
* - a new instance was just created so its database row doesn't exist and needs to be created
* - a new instance was created at the start of this editing session but the user has already
* saved it so its database row already exists
* <p>
* Post-condition: the uri field is set to the URI of the instance database row that matches
* the instance currently managed by the {@link FormController}.
*/
private void updateInstanceDatabase(boolean incomplete, boolean canEditAfterCompleted) {
FormController formController = Collect.getInstance().getFormController();
FormInstance formInstance = formController.getFormDef().getInstance();
String instancePath = formController.getInstanceFile().getAbsolutePath();
InstancesRepository instances = new InstancesRepositoryProvider(Collect.getInstance()).get();
Instance instance = instances.getOneByPath(instancePath);
Instance.Builder instanceBuilder;
if (instance != null) {
instanceBuilder = new Instance.Builder(instance);
} else {
instanceBuilder = new Instance.Builder();
}
if (instanceName != null) {
instanceBuilder.displayName(instanceName);
}
if (incomplete || !shouldFinalize) {
instanceBuilder.status(Instance.STATUS_INCOMPLETE);
} else {
instanceBuilder.status(Instance.STATUS_COMPLETE);
}
instanceBuilder.canEditWhenComplete(canEditAfterCompleted);
if (instance != null) {
String geometryXpath = getGeometryXpathForInstance(instance);
Pair<String, String> geometryContentValues = extractGeometryContentValues(formInstance, geometryXpath);
if (geometryContentValues != null) {
instanceBuilder.geometryType(geometryContentValues.first);
instanceBuilder.geometry(geometryContentValues.second);
}
Instance newInstance = new InstancesRepositoryProvider(Collect.getInstance()).get().save(instanceBuilder.build());
uri = InstancesContract.getUri(currentProjectId, newInstance.getDbId());
} else {
Timber.i("No instance found, creating");
Form form = new FormsRepositoryProvider(Collect.getInstance()).get().get(ContentUriHelper.getIdFromUri(uri));
// add missing fields into values
instanceBuilder.instanceFilePath(instancePath);
instanceBuilder.submissionUri(form.getSubmissionUri());
if (instanceName != null) {
instanceBuilder.displayName(instanceName);
} else {
instanceBuilder.displayName(form.getDisplayName());
}
instanceBuilder.formId(form.getFormId());
instanceBuilder.formVersion(form.getVersion());
Pair<String, String> geometryContentValues = extractGeometryContentValues(formInstance, form.getGeometryXpath());
if (geometryContentValues != null) {
instanceBuilder.geometryType(geometryContentValues.first);
instanceBuilder.geometry(geometryContentValues.second);
}
}
Instance newInstance = new InstancesRepositoryProvider(Collect.getInstance()).get().save(instanceBuilder.build());
uri = InstancesContract.getUri(currentProjectId, newInstance.getDbId());
}
Aggregations