Search in sources :

Example 1 with InstancesRepository

use of org.odk.collect.forms.instances.InstancesRepository in project collect by opendatakit.

the class InstanceUploaderTask method onPostExecute.

@Override
protected void onPostExecute(Outcome outcome) {
    synchronized (this) {
        if (outcome != null && stateListener != null) {
            if (outcome.authRequestingServer != null) {
                stateListener.authRequest(outcome.authRequestingServer, outcome.messagesByInstanceId);
            } else {
                stateListener.uploadingComplete(outcome.messagesByInstanceId);
                // Delete instances that were successfully sent and that need to be deleted
                // either because app-level auto-delete is enabled or because the form
                // specifies it.
                Set<String> instanceIds = outcome.messagesByInstanceId.keySet();
                boolean isFormAutoDeleteOptionEnabled;
                // the app preferences set for delete after submission
                if (deleteInstanceAfterSubmission != null) {
                    isFormAutoDeleteOptionEnabled = deleteInstanceAfterSubmission;
                } else {
                    isFormAutoDeleteOptionEnabled = settingsProvider.getUnprotectedSettings().getBoolean(ProjectKeys.KEY_DELETE_AFTER_SEND);
                }
                Stream<Instance> instancesToDelete = instanceIds.stream().map(id -> new InstancesRepositoryProvider(Collect.getInstance()).get().get(Long.parseLong(id))).filter(instance -> instance.getStatus().equals(Instance.STATUS_SUBMITTED)).filter(instance -> shouldFormBeDeleted(formsRepository, instance.getFormId(), instance.getFormVersion(), isFormAutoDeleteOptionEnabled));
                DeleteInstancesTask dit = new DeleteInstancesTask(instancesRepository, formsRepository);
                dit.execute(instancesToDelete.map(Instance::getDbId).toArray(Long[]::new));
            }
        }
    }
}
Also used : InstancesRepository(org.odk.collect.forms.instances.InstancesRepository) ProjectKeys(org.odk.collect.settings.keys.ProjectKeys) SettingsProvider(org.odk.collect.settings.SettingsProvider) Instance(org.odk.collect.forms.instances.Instance) AsyncTask(android.os.AsyncTask) InstanceUploaderListener(org.odk.collect.android.listeners.InstanceUploaderListener) InstanceUploaderUtils.shouldFormBeDeleted(org.odk.collect.android.utilities.InstanceUploaderUtils.shouldFormBeDeleted) Uri(android.net.Uri) Set(java.util.Set) HashMap(java.util.HashMap) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) FormsRepository(org.odk.collect.forms.FormsRepository) Stream(java.util.stream.Stream) Collect(org.odk.collect.android.application.Collect) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) Instance(org.odk.collect.forms.instances.Instance)

Example 2 with InstancesRepository

use of org.odk.collect.forms.instances.InstancesRepository in project collect by opendatakit.

the class SaveFormToDisk method exportData.

/**
 * Write's the data to the sdcard, and updates the instances content provider.
 * In theory we don't have to write to disk, and this is where you'd add
 * other methods.
 */
private void exportData(boolean markCompleted, FormSaver.ProgressListener progressListener) throws IOException, EncryptionException {
    FormController formController = Collect.getInstance().getFormController();
    progressListener.onProgressUpdate(getLocalizedString(Collect.getInstance(), R.string.survey_saving_collecting_message));
    ByteArrayPayload payload = formController.getFilledInFormXml();
    // write out xml
    String instancePath = formController.getInstanceFile().getAbsolutePath();
    for (String fileName : tempFiles) {
        mediaUtils.deleteMediaFile(fileName);
    }
    progressListener.onProgressUpdate(getLocalizedString(Collect.getInstance(), R.string.survey_saving_saving_message));
    writeFile(payload, instancePath);
    // Write last-saved instance
    String lastSavedPath = formController.getLastSavedPath();
    writeFile(payload, lastSavedPath);
    // update the uri. We have exported the reloadable instance, so update status...
    // Since we saved a reloadable instance, it is flagged as re-openable so that if any error
    // occurs during the packaging of the data for the server fails (e.g., encryption),
    // we can still reopen the filled-out form and re-save it at a later time.
    updateInstanceDatabase(true, true);
    if (markCompleted) {
        // now see if the packaging of the data for the server would make it
        // non-reopenable (e.g., encryption or other fraction of the form).
        boolean canEditAfterCompleted = formController.isSubmissionEntireForm();
        boolean isEncrypted = false;
        // build a submission.xml to hold the data being submitted
        // and (if appropriate) encrypt the files on the side
        // pay attention to the ref attribute of the submission profile...
        File instanceXml = formController.getInstanceFile();
        File submissionXml = new File(instanceXml.getParentFile(), "submission.xml");
        payload = formController.getSubmissionXml();
        // write out submission.xml -- the data to actually submit to aggregate
        progressListener.onProgressUpdate(getLocalizedString(Collect.getInstance(), R.string.survey_saving_finalizing_message));
        writeFile(payload, submissionXml.getAbsolutePath());
        // see if the form is encrypted and we can encrypt it...
        EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(uri, formController.getSubmissionMetadata());
        if (formInfo != null) {
            // if we are encrypting, the form cannot be reopened afterward
            canEditAfterCompleted = false;
            // and encrypt the submission (this is a one-way operation)...
            progressListener.onProgressUpdate(getLocalizedString(Collect.getInstance(), R.string.survey_saving_encrypting_message));
            EncryptionUtils.generateEncryptedSubmission(instanceXml, submissionXml, formInfo);
            isEncrypted = true;
            analytics.logEvent(ENCRYPT_SUBMISSION, AnalyticsUtils.getFormHash(Collect.getInstance().getFormController()), "");
        }
        // At this point, we have:
        // 1. the saved original instanceXml,
        // 2. all the plaintext attachments
        // 2. the submission.xml that is the completed xml (whether encrypting or not)
        // 3. all the encrypted attachments if encrypting (isEncrypted = true).
        // 
        // NEXT:
        // 1. Update the instance database (with status complete).
        // 2. Overwrite the instanceXml with the submission.xml
        // and remove the plaintext attachments if encrypting
        updateInstanceDatabase(false, canEditAfterCompleted);
        if (!canEditAfterCompleted) {
            manageFilesAfterSavingEncryptedForm(instanceXml, submissionXml);
        } else {
            // (we don't need to delete and rename anything).
            if (!submissionXml.delete()) {
                String msg = "Error deleting " + submissionXml.getAbsolutePath() + " (instance is re-openable)";
                Timber.w(msg);
            }
        }
        // (anything not named instanceXml or anything not ending in .enc)
        if (isEncrypted) {
            InstancesRepository instancesRepository = new InstancesRepositoryProvider(Collect.getInstance()).get();
            Instance instance = instancesRepository.get(ContentUriHelper.getIdFromUri(uri));
            // Clear the geometry. Done outside of updateInstanceDatabase to avoid multiple
            // branches and because it has no knowledge of encryption status.
            instancesRepository.save(new Instance.Builder(instance).geometry(null).geometryType(null).build());
            ContentValues values = new ContentValues();
            values.put(DatabaseInstanceColumns.GEOMETRY, (String) null);
            values.put(DatabaseInstanceColumns.GEOMETRY_TYPE, (String) null);
            if (!EncryptionUtils.deletePlaintextFiles(instanceXml, new File(lastSavedPath))) {
                Timber.e("Error deleting plaintext files for %s", instanceXml.getAbsolutePath());
            }
        }
    }
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) ContentValues(android.content.ContentValues) InstancesRepositoryProvider(org.odk.collect.android.utilities.InstancesRepositoryProvider) ByteArrayPayload(org.javarosa.core.services.transport.payload.ByteArrayPayload) FormInstance(org.javarosa.core.model.instance.FormInstance) Instance(org.odk.collect.forms.instances.Instance) InstancesRepository(org.odk.collect.forms.instances.InstancesRepository) LocalizedApplicationKt.getLocalizedString(org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString) EncryptedFormInformation(org.odk.collect.android.utilities.EncryptionUtils.EncryptedFormInformation) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 3 with InstancesRepository

use of org.odk.collect.forms.instances.InstancesRepository in project collect by opendatakit.

the class InstanceUploader method submissionComplete.

public void submissionComplete(Instance instance, boolean successful) {
    InstancesRepository instancesRepository = instancesRepositoryProvider.get();
    if (successful) {
        instancesRepository.save(new Instance.Builder(instance).status(Instance.STATUS_SUBMITTED).build());
    } else {
        instancesRepository.save(new Instance.Builder(instance).status(Instance.STATUS_SUBMISSION_FAILED).build());
    }
    instancesAppState.update();
}
Also used : Instance(org.odk.collect.forms.instances.Instance) InstancesRepository(org.odk.collect.forms.instances.InstancesRepository)

Example 4 with InstancesRepository

use of org.odk.collect.forms.instances.InstancesRepository in project collect by opendatakit.

the class InstancesRepositoryTest method save_whenInstanceHasDeletedDate_doesNotUpdateLastChangesStatusDate.

@Test
public void save_whenInstanceHasDeletedDate_doesNotUpdateLastChangesStatusDate() {
    Supplier<Long> clock = mock(Supplier.class);
    when(clock.get()).thenReturn(123L);
    InstancesRepository instancesRepository = buildSubject(clock);
    Instance originalInstance = instancesRepository.save(InstanceUtils.buildInstance("formid", "1", getInstancesDir()).build());
    Long originalInstanceDbId = originalInstance.getDbId();
    when(clock.get()).thenReturn(456L);
    instancesRepository.deleteWithLogging(originalInstanceDbId);
    instancesRepository.save(instancesRepository.get(originalInstanceDbId));
    assertThat(instancesRepository.get(originalInstanceDbId).getLastStatusChangeDate(), is(123L));
}
Also used : Instance(org.odk.collect.forms.instances.Instance) InstancesRepository(org.odk.collect.forms.instances.InstancesRepository) Test(org.junit.Test)

Example 5 with InstancesRepository

use of org.odk.collect.forms.instances.InstancesRepository in project collect by opendatakit.

the class InstancesRepositoryTest method save_addsUniqueId.

@Test
public void save_addsUniqueId() {
    InstancesRepository instancesRepository = buildSubject();
    instancesRepository.save(InstanceUtils.buildInstance("formid", "1", getInstancesDir()).build());
    instancesRepository.save(InstanceUtils.buildInstance("formid", "1", getInstancesDir()).build());
    Long id1 = instancesRepository.getAll().get(0).getDbId();
    Long id2 = instancesRepository.getAll().get(1).getDbId();
    assertThat(id1, notNullValue());
    assertThat(id2, notNullValue());
    assertThat(id1, not(equalTo(id2)));
}
Also used : InstancesRepository(org.odk.collect.forms.instances.InstancesRepository) Test(org.junit.Test)

Aggregations

InstancesRepository (org.odk.collect.forms.instances.InstancesRepository)25 Instance (org.odk.collect.forms.instances.Instance)23 Test (org.junit.Test)19 File (java.io.File)4 InstancesRepositoryProvider (org.odk.collect.android.utilities.InstancesRepositoryProvider)3 ContentValues (android.content.ContentValues)2 FormInstance (org.javarosa.core.model.instance.FormInstance)2 FormController (org.odk.collect.android.javarosawrapper.FormController)2 FormsRepository (org.odk.collect.forms.FormsRepository)2 LocalizedApplicationKt.getLocalizedString (org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString)2 Cursor (android.database.Cursor)1 Uri (android.net.Uri)1 AsyncTask (android.os.AsyncTask)1 RandomAccessFile (java.io.RandomAccessFile)1 HashMap (java.util.HashMap)1 Set (java.util.Set)1 Stream (java.util.stream.Stream)1 ByteArrayPayload (org.javarosa.core.services.transport.payload.ByteArrayPayload)1 Collect (org.odk.collect.android.application.Collect)1 DatabaseObjectMapper.getValuesFromInstance (org.odk.collect.android.database.DatabaseObjectMapper.getValuesFromInstance)1