Example usage for java.io FileNotFoundException getCause

List of usage examples for java.io FileNotFoundException getCause

Introduction

In this page you can find the example usage for java.io FileNotFoundException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * Writes an exam to an XML file/*w w  w  . ja  v a  2s  .  co  m*/
 *
 * @param exam      the exam to be written
 * @param examFile  the target file
 * @param password  the passphrase locking the restricted content
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeExam(@Nonnull Exam exam, @Nonnull File examFile, @Nonnull String password,
        boolean overwrite) throws VaSolSimException {
    logger.info("beginning exam export -> " + exam.getTestName());

    logger.debug("checking export destination...");

    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        logger.trace("exam file exists, checking overwrite...");

        //can't overwrite
        if (!overwrite) {
            logger.error("file already present and cannot overwrite");
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            logger.trace("overwriting...");
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                logger.error("internal file presence check failed", e);
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        logger.trace("exam file does not exist, creating...");

        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            logger.error("could not create empty directories for export");
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            logger.trace("creating files...");
            if (!examFile.createNewFile()) {
                logger.error("could not create empty file for export");
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            logger.error("io error on empty file creation", e);
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    logger.debug("initializing weak cryptography scheme...");

    /*
     * initialize the cryptography system
     */
    String encryptedHash;
    Cipher encryptionCipher;
    try {
        logger.trace("hashing password into key...");
        //hash the password
        byte[] hash;
        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(password.getBytes());
        hash = GenericUtils.validate512HashTo128Hash(msgDigest.digest());

        logger.trace("initializing cipher");
        encryptionCipher = GenericUtils.initCrypto(hash, Cipher.ENCRYPT_MODE);

        encryptedHash = GenericUtils
                .convertBytesToHexString(GenericUtils.applyCryptographicCipher(hash, encryptionCipher));
    } catch (NoSuchAlgorithmException e) {
        logger.error("FAILED. could not initialize crypto", e);
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    }

    logger.debug("initializing the document builder...");

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        logger.trace("create document builder factory instance -> create new doc");
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        logger.trace("set document properties");
        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        logger.error("parser was not configured correctly", e);
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        logger.error("transformer was not configured properly");
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    logger.debug("building document...");

    /*
     * build exam info
     */
    logger.trace("attaching root...");
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    logger.trace("attaching info...");
    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    logger.trace("attaching exam info...");
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);
    GenericUtils.appendSubNode(XML_DATE_ELEMENT_NAME, exam.getDate(), info, examDoc);

    //start security xml section
    logger.trace("attaching security...");
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_ENCRYPTED_VALIDATION_HASH_ELEMENT_NAME, encryptedHash, security, examDoc);
    GenericUtils.appendSubNode(XML_PARAMETRIC_INITIALIZATION_VECTOR_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(encryptionCipher.getIV()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsDestinationEmail() == null ? GenericUtils.NO_EMAIL.getBytes()
                            : exam.getStatsDestinationEmail().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderEmail() == null ? GenericUtils.NO_EMAIL.getBytes()
                            : exam.getStatsSenderEmail().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_PASSWORD_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderPassword() == null ? GenericUtils.NO_DATA.getBytes()
                            : exam.getStatsSenderPassword().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderSMTPAddress() == null ? GenericUtils.NO_SMTP.getBytes()
                            : exam.getStatsSenderSMTPAddress().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    Integer.toString(exam.getStatsSenderSMTPPort()).getBytes(), encryptionCipher)),
            security, examDoc);

    logger.debug("checking exam content integrity...");
    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.checkExamIntegrity(exam).size() == 0) {
        logger.debug("exporting exam content...");
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);
            logger.trace("exporting question set -> " + qSet.getName());

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResourceType() != GenericUtils.ResourceType.NONE && qSet.getResources() != null) {
                logger.debug("exporting question set resources...");
                for (BufferedImage img : qSet.getResources()) {
                    if (img != null) {
                        try {
                            logger.trace("writing image...");
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            ImageIO.write(img, "png", out);
                            out.flush();
                            GenericUtils.appendCDATASubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                    new String(Base64.encodeBase64(out.toByteArray())), qSetElement, examDoc);
                        } catch (IOException e) {
                            throw new VaSolSimException(
                                    "Error: cannot write images to byte array for transport");
                        }
                    }
                }
            }

            //TODO export problem in this subroutine
            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);
                logger.trace("exporting question -> " + question.getName());

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                logger.trace("question id -> " + setIndex);
                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                logger.trace("question name -> " + question.getName());
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(),
                        qElement, examDoc);
                logger.trace("question test -> " + question.getQuestion());
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                logger.trace("question answer scramble -> " + Boolean.toString(question.getScrambleAnswers()));
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                logger.trace("question answer order matters -> "
                        + Boolean.toString(question.getAnswerOrderMatters()));
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                logger.debug("exporting correct answer choices...");
                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    logger.trace("exporting correct answer choice(s) -> " + answer.getAnswerText());
                    GenericUtils
                            .appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH,
                                    GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                                            answer.getAnswerText().getBytes(), encryptionCipher)),
                                    qElement, examDoc);
                }

                logger.debug("exporting answer choices...");
                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    if (question.getAnswerChoices().get(questionIndex).isActive()) {
                        AnswerChoice ac = question.getAnswerChoices().get(questionIndex);
                        logger.trace("exporting answer choice -> " + ac.getAnswerText());

                        Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                        qElement.appendChild(acElement);

                        logger.trace("answer choice id -> " + questionIndex);
                        GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                                Integer.toString(questionIndex + 1), acElement, examDoc);
                        logger.trace("answer choice visible id -> " + ac.getVisibleChoiceID());
                        GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                                ac.getVisibleChoiceID(), acElement, examDoc);
                        logger.trace("answer text -> " + ac.getAnswerText());
                        GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                                examDoc);
                    }
                }
            }
        }
    } else {
        logger.error("integrity check failed");
        PopupManager.showMessage(errorsToOutput(GenericUtils.checkExamIntegrity(exam)));
        return false;
    }

    logger.debug("transforming exam...");
    try {
        examTransformer.transform(new DOMSource(examDoc), new StreamResult(examFile));
    } catch (TransformerException e) {
        logger.error("exam export failed (transformer error)", e);
        return false;
    }
    logger.debug("transformation done");

    logger.info("exam export successful");
    return true;
}

From source file:org.rhq.enterprise.client.commands.ScriptCommand.java

public boolean execute(ClientMain client, String[] args) {
    // for a command line session we don't want to reset the bindings for each executed command line, the
    // state, e.g. exporter settings, should be maintained from line to line. Note that scriptFiles
    // executed via 'exec -f' are treated like extensions of the command line session.  They inherit the
    // current bindings and any modifications made by the script file will affect the command line session
    // after the script file has completed.
    if (null == bindings) {
        initBindings(client);/*from w w w.j  av  a2 s  .  c om*/
    }

    if (isScriptFileCommandLine(args)) {
        try {
            CmdLineParser cmdLineParser = new CmdLineParser();
            ScriptCmdLine scriptCmdLine = cmdLineParser.parse(args);

            bindScriptArgs(scriptCmdLine);
            executeUtilScripts();

            FileReader reader = new FileReader(scriptCmdLine.getScriptFileName());
            try {
                return executeScriptFile(reader, client);
            } finally {
                try {
                    reader.close();
                } catch (IOException ignore) {
                }
            }
        } catch (FileNotFoundException e) {
            client.getPrintWriter().println(e.getMessage());
            if (log.isDebugEnabled()) {
                log.debug("Unable to locate script file: " + e.getMessage());
            }
        } catch (CommandLineParseException e) {
            if (client.isInteractiveMode()) {
                client.getPrintWriter().println("parse error: " + e.getMessage());
                if (log.isDebugEnabled()) {
                    log.debug("A parse error occurred.", e);
                }
            } else {
                throw new CLIScriptException(e);
            }
        }

        return true;
    }

    isMultilineScript = "\\".equals(args[args.length - 1]);
    inMultilineScript = inMultilineScript || isMultilineScript;

    if (!isMultilineScript && !inMultilineScript) {
        script = new StringBuilder();
    }

    if (isMultilineScript) {
        args = Arrays.copyOfRange(args, 0, args.length - 1);
    }

    for (int i = ("exec".equals(args[0]) ? 1 : 0); i < args.length; i++) {
        script.append(args[i]);
        script.append(" ");
    }

    if (isMultilineScript) {
        return true;
    }

    try {

        Object result = getScriptEngine().eval(script.toString());
        inMultilineScript = false;
        script = new StringBuilder();
        if (result != null) {
            //                client.getPrintWriter().print("result: ");
            TabularWriter writer = new TabularWriter(client.getPrintWriter());

            if (client.isInteractiveMode()) {
                writer.setWidth(client.getConsoleWidth());
            }
            writer.print(result);
        }
    } catch (ScriptException e) {

        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
        message = message.replace("sun.org.mozilla.javascript.internal.EcmaError: ", "");
        message = message.replace("(<Unknown source>#1) in <Unknown source> at line number 1", "");

        client.getPrintWriter().println(message);
        client.getPrintWriter().println(script);
        for (int i = 0; i < e.getColumnNumber(); i++) {
            client.getPrintWriter().print(" ");
        }
        client.getPrintWriter().println("^");
        script = new StringBuilder();
        inMultilineScript = false;
    }
    client.getPrintWriter().println();
    return true;
}

From source file:com.amarinfingroup.net.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or
 * from XML. If given an instance, it will be used to fill the {@link FormDef}
 * ./*ww w  .j  a v  a  2 s. co m*/
 */
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);
    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    FormDef.EvalBehavior mode = AdminPreferencesActivity
            .getConfiguredFormProcessingLogic(Collect.getInstance());
    FormDef.setEvalBehavior(mode);

    //    FormDef.setDefaultEventNotifier(new EventNotifier() {
    //
    //      @Override
    //      public void publishEvent(Event event) {
    //        Log.d("FormDef", event.asLogLine());
    //      }
    //    });

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a
            // new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // add external data function handlers
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    fd.getEvaluationContext().addFunctionHandler(externalDataHandlerPull);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so
                        // don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of
            // https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()),
                            csv.getAbsolutePath());
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5, ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()));
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this
        // position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:cd.education.data.collector.android.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or
 * from XML. If given an instance, it will be used to fill the {@link FormDef}
 * ./*from w ww. ja v  a2 s.  c  o m*/
 */
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);
    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a
            // new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // new evaluation context for function handlers
    EvaluationContext ec = new EvaluationContext(null);
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    ec.addFunctionHandler(externalDataHandlerPull);

    fd.setEvaluationContext(ec);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so
                        // don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of
            // https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()),
                            csv.getAbsolutePath());
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5, ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()));
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this
        // position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:com.geoodk.collect.android.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
 * an instance, it will be used to fill the {@link FormDef}.
 *//*  w w w  .jav  a2 s  . com*/
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);
    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    initializeJavaRosa();

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // new evaluation context for function handlers
    EvaluationContext ec = new EvaluationContext(null);
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    ec.addFunctionHandler(externalDataHandlerPull);

    fd.setEvaluationContext(ec);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(oldmd5);
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5);
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (csvmd5 != null) {
        fc.setItemsetHash(csvmd5);
    }
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:com.kll.collect.android.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
 * an instance, it will be used to fill the {@link FormDef}.
 *//*from  w  w w. ja va  2  s .c o m*/
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);

    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    initializeJavaRosa();

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // new evaluation context for function handlers
    EvaluationContext ec = new EvaluationContext(null);
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    ec.addFunctionHandler(externalDataHandlerPull);

    fd.setEvaluationContext(ec);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);

    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        Log.i("CSVMD5", csvmd5);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(oldmd5);
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5);
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (csvmd5 != null) {
        fc.setItemsetHash(csvmd5);
    }
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:org.odk.collect.android.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
 * an instance, it will be used to fill the {@link FormDef}.
 */// ww w. j  av  a 2 s.co  m
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);
    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    initializeJavaRosa();

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // new evaluation context for function handlers
    EvaluationContext ec = new EvaluationContext(null);
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    ec.addFunctionHandler(externalDataHandlerPull);

    fd.setEvaluationContext(ec);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(oldmd5);
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5);
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (csvmd5 != null) {
        fc.setItemsetHash(csvmd5);
    }
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }

    //flikk TODO: populate savedRoot with initialData
    if (initialData != null) {
        populateWithInitialData(fc, initialData.toString());
    }

    data = new FECWrapper(fc, usedSavepoint);
    return data;

}