Search in sources :

Example 6 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class MediaLoadingTask method doInBackground.

@Override
protected File doInBackground(Uri... uris) {
    FormController formController = Collect.getInstance().getFormController();
    if (formController != null) {
        File instanceFile = formController.getInstanceFile();
        if (instanceFile != null) {
            String extension = ContentUriHelper.getFileExtensionFromUri(uris[0]);
            File newFile = FileUtils.createDestinationMediaFile(instanceFile.getParent(), extension);
            FileUtils.saveAnswerFileFromUri(uris[0], newFile, Collect.getInstance());
            QuestionWidget questionWidget = formEntryActivity.get().getWidgetWaitingForBinaryData();
            // apply image conversion if the widget is an image widget
            if (questionWidget instanceof BaseImageWidget) {
                String imageSizeMode = settingsProvider.getUnprotectedSettings().getString(KEY_IMAGE_SIZE);
                ImageConverter.execute(newFile.getPath(), questionWidget, formEntryActivity.get(), imageSizeMode);
            }
            return newFile;
        }
    }
    return null;
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) QuestionWidget(org.odk.collect.android.widgets.QuestionWidget) File(java.io.File) BaseImageWidget(org.odk.collect.android.widgets.BaseImageWidget)

Example 7 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class SaveFormIndexTask method doInBackground.

@Override
protected String doInBackground(Void... params) {
    long start = System.currentTimeMillis();
    FormController formController = Collect.getInstance().getFormController();
    try {
        File tempFormIndexFile = SaveFormToDisk.getFormIndexFile(formController.getInstanceFile().getName());
        exportFormIndexToFile(formIndex, tempFormIndexFile);
        long end = System.currentTimeMillis();
        Timber.i("SaveFormIndex ms: %s to %s", Long.toString(end - start), tempFormIndexFile.toString());
        return null;
    } catch (Exception e) {
        String msg = e.getMessage();
        Timber.e(e);
        return msg;
    }
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) File(java.io.File)

Example 8 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class SavePointTask method doInBackground.

@Override
protected String doInBackground(Void... params) {
    synchronized (LOCK) {
        if (priority < lastPriorityUsed) {
            Timber.w("Savepoint thread (p=%d) was cancelled (a) because another one is waiting (p=%d)", priority, lastPriorityUsed);
            return null;
        }
        long start = System.currentTimeMillis();
        try {
            FormController formController = Collect.getInstance().getFormController();
            File temp = SaveFormToDisk.getSavepointFile(formController.getInstanceFile().getName());
            ByteArrayPayload payload = formController.getFilledInFormXml();
            if (priority < lastPriorityUsed) {
                Timber.w("Savepoint thread (p=%d) was cancelled (b) because another one is waiting (p=%d)", priority, lastPriorityUsed);
                return null;
            }
            // write out xml
            SaveFormToDisk.writeFile(payload, temp.getAbsolutePath());
            long end = System.currentTimeMillis();
            Timber.i("Savepoint ms: %s to %s", Long.toString(end - start), temp.toString());
            return null;
        } catch (Exception e) {
            String msg = e.getMessage();
            Timber.e(e);
            return msg;
        }
    }
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) ByteArrayPayload(org.javarosa.core.services.transport.payload.ByteArrayPayload) File(java.io.File)

Example 9 with FormController

use of org.odk.collect.android.javarosawrapper.FormController 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 10 with FormController

use of org.odk.collect.android.javarosawrapper.FormController in project collect by opendatakit.

the class FormNavigationTest method testIndices.

private void testIndices(String formName, String[] expectedIndices) throws ExecutionException, InterruptedException {
    try {
        copyToStorage(formName);
    } catch (IOException e) {
        Timber.i(e);
    }
    FormLoaderTask formLoaderTask = new FormLoaderTask(formPath(formName), null, null);
    formLoaderTask.setFormLoaderListener(new FormLoaderListener() {

        @Override
        public void loadingComplete(FormLoaderTask task, FormDef fd, String warningMsg) {
            try {
                // form and then swiping back once. Verify the expected indices before and after each swipe.
                for (int i = 0; i < expectedIndices.length - 1; i++) {
                    FormController formController = task.getFormController();
                    // check the current index
                    assertEquals(expectedIndices[i], formController.getFormIndex().toString());
                    if (i < expectedIndices.length - 2) {
                        formController.stepToNextScreenEvent();
                    } else {
                        formController.stepToPreviousScreenEvent();
                    }
                    // check the index again after navigating
                    assertEquals(expectedIndices[i + 1], formController.getFormIndex().toString());
                }
            } catch (Exception e) {
                Timber.i(e);
            }
        }

        @Override
        public void loadingError(String errorMsg) {
        }

        @Override
        public void onProgressStep(String stepMessage) {
        }
    });
    formLoaderTask.execute(formPath(formName)).get();
}
Also used : FormController(org.odk.collect.android.javarosawrapper.FormController) FormDef(org.javarosa.core.model.FormDef) FormLoaderListener(org.odk.collect.android.listeners.FormLoaderListener) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) FormLoaderTask(org.odk.collect.android.tasks.FormLoaderTask)

Aggregations

FormController (org.odk.collect.android.javarosawrapper.FormController)53 FormIndex (org.javarosa.core.model.FormIndex)11 File (java.io.File)9 JavaRosaException (org.odk.collect.android.exception.JavaRosaException)9 FormDef (org.javarosa.core.model.FormDef)4 FormEntryPrompt (org.javarosa.form.api.FormEntryPrompt)4 Collect (org.odk.collect.android.application.Collect)4 RepeatsInFieldListException (org.odk.collect.android.javarosawrapper.RepeatsInFieldListException)4 LocalizedApplicationKt.getLocalizedString (org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString)4 TextView (android.widget.TextView)3 ArrayList (java.util.ArrayList)3 FormInstance (org.javarosa.core.model.instance.FormInstance)3 TreeReference (org.javarosa.core.model.instance.TreeReference)3 FormEntryCaption (org.javarosa.form.api.FormEntryCaption)3 Before (org.junit.Before)3 Test (org.junit.Test)3 Form (org.odk.collect.forms.Form)3 Intent (android.content.Intent)2 View (android.view.View)2 WebView (android.webkit.WebView)2