@Override public Iterator<String> getConflictedDocumentIds() { // the "SELECT DISTINCT ..." subquery selects all the parent // sequence, and so the outer "SELECT ..." practically selects // all the leaf nodes. The "GROUP BY" and "HAVING COUNT(*) > 1" // make sure only those document with more than one leafs are // returned. final String sql = "SELECT docs.docid, COUNT(*) FROM docs,revs " + "WHERE revs.doc_id = docs.doc_id " + "AND deleted = 0 AND revs.sequence NOT IN " + "(SELECT DISTINCT parent FROM revs WHERE parent NOT NULL) " + "GROUP BY docs.docid HAVING COUNT(*) > 1"; List<String> conflicts = new ArrayList<String>(); Cursor cursor = null; try { cursor = this.sqlDb.rawQuery(sql, new String[] {}); while (cursor.moveToNext()) { String docId = cursor.getString(0); conflicts.add(docId); } } catch (SQLException e) { Log.e(LOG_TAG, "Error getting conflicted document: ", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return conflicts.iterator(); }
private DocumentRevisionTree getAllRevisionsOfDocument(long docNumericID) { String sql = "SELECT " + FULL_DOCUMENT_COLS + " FROM revs, docs " + "WHERE revs.doc_id=? AND revs.doc_id = docs.doc_id ORDER BY sequence ASC"; String[] args = {Long.toString(docNumericID)}; Cursor cursor = null; try { DocumentRevisionTree tree = new DocumentRevisionTree(); cursor = this.sqlDb.rawQuery(sql, args); while (cursor.moveToNext()) { DocumentRevision rev = SQLDatabaseUtils.getFullRevisionFromCurrentCursor(cursor); Log.v(LOG_TAG, "Rev: " + rev); tree.add(rev); } return tree; } catch (SQLException e) { Log.e(LOG_TAG, "Error getting all revisions of document", e); return null; } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
@Override public Changes changes(long since, int limit) { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(limit > 0, "Limit must be positive number"); since = since >= 0 ? since : 0; String[] args = {Long.toString(since), Long.toString(since + limit)}; Cursor cursor = null; try { Long lastSequence = since; List<Long> ids = new ArrayList<Long>(); cursor = this.sqlDb.rawQuery(SQL_CHANGE_IDS_SINCE_LIMIT, args); while (cursor.moveToNext()) { ids.add(cursor.getLong(0)); lastSequence = Math.max(lastSequence, cursor.getLong(1)); } List<DocumentRevision> results = this.getDocumentsWithInternalIds(ids); if (results.size() != ids.size()) { throw new IllegalStateException( "The number of document does not match number of ids, " + "something must be wrong here."); } return new Changes(lastSequence, results); } catch (SQLException e) { throw new IllegalStateException( "Error querying all changes since: " + since + ", limit: " + limit, e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
// Keep in mind we do not keep local document revision history private BasicDocumentRevision doGetLocalDocument(String docId, String revId) { assert !Strings.isNullOrEmpty(docId); Cursor cursor = null; try { String[] args = {docId}; cursor = this.sqlDb.rawQuery("SELECT revid, json FROM localdocs WHERE docid=?", args); if (cursor.moveToFirst()) { String gotRevID = cursor.getString(0); if (revId != null && !revId.equals(gotRevID)) { // throw new DocumentNotFoundException("No local document found with // id: " + docId + ", revId: " + revId); return null; } byte[] json = cursor.getBlob(1); DocumentRevisionBuilder builder = new DocumentRevisionBuilder() .setDocId(docId) .setRevId(gotRevID) .setBody(BasicDocumentBody.bodyWith(json)); return builder.buildBasicDBObjectLocalDocument(); } else { return null; } } catch (SQLException e) { throw new SQLRuntimeException("Error getting local document with id: " + docId, e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
/** * Removes revisions present in the datastore from the input map. * * @param revisions an multimap from document id to set of revisions. The map is modified in place * for performance consideration. */ void revsDiffBatch(Multimap<String, String> revisions) { final String sql = String.format( "SELECT docs.docid, revs.revid FROM docs, revs " + "WHERE docs.doc_id = revs.doc_id AND docs.docid IN (%s) AND revs.revid IN (%s) " + "ORDER BY docs.docid", SQLDatabaseUtils.makePlaceholders(revisions.keySet().size()), SQLDatabaseUtils.makePlaceholders(revisions.size())); String[] args = new String[revisions.keySet().size() + revisions.size()]; String[] keys = revisions.keySet().toArray(new String[revisions.keySet().size()]); String[] values = revisions.values().toArray(new String[revisions.size()]); System.arraycopy(keys, 0, args, 0, revisions.keySet().size()); System.arraycopy(values, 0, args, revisions.keySet().size(), revisions.size()); Cursor cursor = null; try { cursor = this.sqlDb.rawQuery(sql, args); while (cursor.moveToNext()) { String docId = cursor.getString(0); String revId = cursor.getString(1); revisions.remove(docId, revId); } } catch (SQLException e) { e.printStackTrace(); } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
public ServiceResult<List<Page>> searchPageLike(String queryString) { queryString = DatabaseUtils.preventSQLInjection(queryString); List<Page> listPages = null; ServiceResult<List<Page>> result = new ServiceResult<List<Page>>(); listPages = DatabaseUtils.searchByQuery(queryString, Page.class); if (listPages.size() > 0) { result.setResult(listPages); result.setOK(true); result.setMessage(Global.messages.getString("search_page_by_query_successfully")); } else { result.setOK(false); result.setMessage(Global.messages.getString("search_page_by_query_fail")); } return result; }
@Override public int getDocumentCount() { Preconditions.checkState(this.isOpen(), "Database is closed"); String sql = "SELECT COUNT(DISTINCT doc_id) FROM revs WHERE current=1 AND deleted=0"; Cursor cursor = null; int result = 0; try { cursor = this.sqlDb.rawQuery(sql, null); if (cursor.moveToFirst()) { result = cursor.getInt(0); } } catch (SQLException e) { Log.e(LOG_TAG, "Error getting document count", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return result; }
@Override public long getDocNumericId(String docId) { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument( !Strings.isNullOrEmpty(docId), "Input document id can not be empty"); Cursor cursor = null; try { cursor = this.sqlDb.rawQuery("SELECT doc_id FROM docs WHERE docid = ?", new String[] {docId}); if (cursor.moveToFirst()) { return cursor.getLong(0); } } catch (SQLException e) { Log.e(LOG_TAG, "Error getting doc numeric id", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return -1; }
private List<DocumentRevision> getRevisionsFromRawQuery(String sql, String[] args) { List<DocumentRevision> result = new ArrayList<DocumentRevision>(); Cursor cursor = null; try { cursor = this.sqlDb.rawQuery(sql, args); while (cursor.moveToNext()) { DocumentRevision row = SQLDatabaseUtils.getFullRevisionFromCurrentCursor(cursor); result.add(row); } } catch (SQLException e) { e .printStackTrace(); // To change bodyOne of catch statement use File | Settings | File // Templates. } finally { DatabaseUtils.closeCursorQuietly(cursor); } return result; }
public ServiceResult<List<Page>> getListPageFromUsername(String username) { username = DatabaseUtils.preventSQLInjection(username); ServiceResult<List<Page>> result = new ServiceResult<List<Page>>(); PersistenceManager pm = PMF.get().getPersistenceManager(); if (username == null || username.equals("")) { result.setMessage(Global.messages.getString("cannot_handle_with_null")); return result; } boolean isNotFound = false; UserInfo userInfo = null; try { userInfo = pm.getObjectById(UserInfo.class, username); } catch (JDOObjectNotFoundException e) { isNotFound = true; } catch (NucleusObjectNotFoundException e) { isNotFound = true; } if (isNotFound || userInfo == null) { // Not found userinfo result.setMessage(Global.messages.getString("not_found") + " " + username); } else { Query query = pm.newQuery(Page.class); query.setFilter("username == us"); query.declareParameters("String us"); query.setOrdering("date_post DESC"); List<Page> listPages = (List<Page>) query.execute(username); if (listPages.size() > 0) { result.setOK(true); result.setMessage( String.format( Global.messages.getString("get_pages_by_username_successfully"), username)); result.setResult(listPages); } else { result.setOK(false); result.setMessage( String.format(Global.messages.getString("get_pages_by_username_fail"), username)); } } pm.close(); return result; }
@Override public String getPublicIdentifier() { Preconditions.checkState(this.isOpen(), "Database is closed"); Cursor cursor = null; try { cursor = this.sqlDb.rawQuery("SELECT value FROM info WHERE key='publicUUID'", null); if (cursor.moveToFirst()) { return "touchdb_" + cursor.getString(0); } else { throw new IllegalStateException( "Error querying PublicUUID, " + "it is probably because the sqlDatabase is not probably initialized."); } } catch (SQLException e) { throw new SQLRuntimeException("Error querying publicUUID: ", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
@Override public BasicDocumentRevision getDocument(String id, String rev) { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument( !Strings.isNullOrEmpty(id), "DocumentRevisionTree id can not be empty"); Cursor cursor = null; try { String[] args = (rev == null) ? new String[] {id} : new String[] {id, rev}; String sql = (rev == null) ? GET_DOCUMENT_CURRENT_REVISION : GET_DOCUMENT_GIVEN_REVISION; cursor = this.sqlDb.rawQuery(sql, args); if (cursor.moveToFirst()) { return SQLDatabaseUtils.getFullRevisionFromCurrentCursor(cursor); } else { return null; } } catch (SQLException e) { throw new SQLRuntimeException("Error getting document with id: " + id + "and rev" + rev, e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } }
void handleIntent() { ContentResolver cr = getContentResolver(); long providerId = Imps.Provider.getProviderIdForName(cr, mProviderName); long accountId; mConn = mApp.getConnection(providerId); if (mConn == null) { Cursor c = DatabaseUtils.queryAccountsForProvider(cr, ACCOUNT_PROJECTION, providerId); if (c == null) { addAccount(providerId); } else { accountId = c.getLong(ACCOUNT_ID_COLUMN); if (c.isNull(ACCOUNT_PW_COLUMN)) { editAccount(accountId); } else { signInAccount(accountId); } } } else { try { int state = mConn.getState(); accountId = mConn.getAccountId(); if (state < ImConnection.LOGGED_IN) { signInAccount(accountId); } else if (state == ImConnection.LOGGED_IN || state == ImConnection.SUSPENDED) { if (!isValidToAddress()) { showContactList(accountId); } else { openChat(providerId, accountId); } } } catch (RemoteException e) { // Ouch! Service died! We'll just disappear. Log.w("ImUrlActivity", "Connection disappeared!"); } } finish(); }
@Override public long getLastSequence() { Preconditions.checkState(this.isOpen(), "Database is closed"); String sql = "SELECT MAX(sequence) FROM revs"; Cursor cursor = null; long result = 0; try { cursor = this.sqlDb.rawQuery(sql, null); if (cursor.moveToFirst()) { if (cursor.columnType(0) == Cursor.FIELD_TYPE_INTEGER) { result = cursor.getLong(0); } else if (cursor.columnType(0) == Cursor.FIELD_TYPE_NULL) { result = SEQUENCE_NUMBER_START; } else { throw new IllegalStateException("SQLite return an unexpected value."); } } } catch (SQLException e) { Log.e(LOG_TAG, "Error getting last sequence", e); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return result; }
public static void importCsvToDb(File file) throws ClassNotFoundException { if (file.getName().matches("^.*.bak*$")) { if (DatabaseUtils.checkIfDatabaseExists() == true) { int dialogResult = JOptionPane.showConfirmDialog(null, "Replace all records'Yes' Or merge all'No'?"); if (dialogResult == JOptionPane.YES_OPTION) { try { try { DataInputStream drr = new DataInputStream(new FileInputStream(file)); BufferedReader dr = new BufferedReader( new InputStreamReader( drr, "ISO-8859-7")); // to read greek chars iso-8859-7 needed String temp; String prs[] = new String[10]; ArrayList pr = new ArrayList(); int i = 1; while ((temp = dr.readLine()) != null) { if (temp.equals("promithiatablestart")) { break; } if (i <= 9) { prs[i] = temp; i++; if (i == 10) { pr.add( new Pelates( prs[1], prs[2], prs[3], prs[4], prs[5], prs[6], prs[7], prs[8], prs[9])); i = 1; } } } i = 1; while ((temp = dr.readLine()) != null) { if (temp.equals("recordsend")) { break; } if (i <= 9) { prs[i] = temp; i++; if (i == 10) { pr.add( new Promithia( prs[1], prs[2], prs[3], prs[4], prs[5], prs[6], prs[7], prs[8], prs[9])); i = 1; } } } dr.close(); Class.forName(classForName); con = DriverManager.getConnection(url); sql = "delete from pelates "; pst = con.prepareStatement(sql); pst.execute(); sql = "delete from promithia "; pst = con.prepareStatement(sql); pst.execute(); sql = "insert into pelates(eponimia, onomateponimo, tilefono, kinito, fax, address, email, taxkodikas, afm) values(?, ?, ?, ?, ?, ?, ?, ?, ?)"; pst = con.prepareStatement(sql); for (Object pr1 : pr) { if (pr1 instanceof Pelates) { pst.setString(1, ((Pelates) pr1).getEponimia()); pst.setString(2, ((Pelates) pr1).getOnomateponimo()); pst.setString(3, ((Pelates) pr1).getTilefono()); pst.setString(4, ((Pelates) pr1).getKinito()); pst.setString(5, ((Pelates) pr1).getFax()); pst.setString(6, ((Pelates) pr1).getAddress()); pst.setString(7, ((Pelates) pr1).getEmail()); pst.setString(8, ((Pelates) pr1).getTaxkodikas()); pst.setString(9, ((Pelates) pr1).getAfm()); pst.executeUpdate(); } } sql = "insert into promithia(eponimia, onomateponimo, tilefono, kinito, fax, address, email, taxkodikas, afm) values(?, ?, ?, ?, ?, ?, ?, ?, ?)"; pst = con.prepareStatement(sql); for (Object pr1 : pr) { if (pr1 instanceof Promithia) { pst.setString(1, ((Promithia) pr1).getEponimia()); pst.setString(2, ((Promithia) pr1).getOnomateponimo()); pst.setString(3, ((Promithia) pr1).getTilefono()); pst.setString(4, ((Promithia) pr1).getKinito()); pst.setString(5, ((Promithia) pr1).getFax()); pst.setString(6, ((Promithia) pr1).getAddress()); pst.setString(7, ((Promithia) pr1).getEmail()); pst.setString(8, ((Promithia) pr1).getTaxkodikas()); pst.setString(9, ((Promithia) pr1).getAfm()); pst.executeUpdate(); } } } catch (IOException ex) { } } catch (SQLException ex) { Logger.getLogger(ImportToDb.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (pst != null) { pst.close(); } if (con != null) { con.close(); } sql = " "; } catch (SQLException ex) { } } } else if (dialogResult == JOptionPane.NO_OPTION) { try { try { DataInputStream drr = new DataInputStream(new FileInputStream(file)); BufferedReader dr = new BufferedReader( new InputStreamReader( drr, "ISO-8859-7")); // to read greek chars iso-8859-7 needed String temp; String prs[] = new String[10]; ArrayList pr = new ArrayList(); int i = 1; while ((temp = dr.readLine()) != null) { if (temp.equals("promithiatablestart")) { break; } if (i <= 9) { prs[i] = temp; i++; if (i == 10) { pr.add( new Pelates( prs[1], prs[2], prs[3], prs[4], prs[5], prs[6], prs[7], prs[8], prs[9])); i = 1; } } } i = 1; while ((temp = dr.readLine()) != null) { if (temp.equals("recordsend")) { break; } if (i <= 9) { prs[i] = temp; i++; if (i == 10) { pr.add( new Promithia( prs[1], prs[2], prs[3], prs[4], prs[5], prs[6], prs[7], prs[8], prs[9])); i = 1; } } } dr.close(); Class.forName(classForName); con = DriverManager.getConnection(url); sql = "insert into pelates(eponimia, onomateponimo, tilefono, kinito, fax, address, email, taxkodikas, afm) values(?, ?, ?, ?, ?, ?, ?, ?, ?)"; pst = con.prepareStatement(sql); for (Object pr1 : pr) { if (pr1 instanceof Pelates) { pst.setString(1, ((Pelates) pr1).getEponimia()); pst.setString(2, ((Pelates) pr1).getOnomateponimo()); pst.setString(3, ((Pelates) pr1).getTilefono()); pst.setString(4, ((Pelates) pr1).getKinito()); pst.setString(5, ((Pelates) pr1).getFax()); pst.setString(6, ((Pelates) pr1).getAddress()); pst.setString(7, ((Pelates) pr1).getEmail()); pst.setString(8, ((Pelates) pr1).getTaxkodikas()); pst.setString(9, ((Pelates) pr1).getAfm()); pst.executeUpdate(); } } sql = "insert into promithia(eponimia, onomateponimo, tilefono, kinito, fax, address, email, taxkodikas, afm) values(?, ?, ?, ?, ?, ?, ?, ?, ?)"; pst = con.prepareStatement(sql); for (Object pr1 : pr) { if (pr1 instanceof Promithia) { pst.setString(1, ((Promithia) pr1).getEponimia()); pst.setString(2, ((Promithia) pr1).getOnomateponimo()); pst.setString(3, ((Promithia) pr1).getTilefono()); pst.setString(4, ((Promithia) pr1).getKinito()); pst.setString(5, ((Promithia) pr1).getFax()); pst.setString(6, ((Promithia) pr1).getAddress()); pst.setString(7, ((Promithia) pr1).getEmail()); pst.setString(8, ((Promithia) pr1).getTaxkodikas()); pst.setString(9, ((Promithia) pr1).getAfm()); pst.executeUpdate(); } } } catch (IOException ex) { } } catch (SQLException ex) { Logger.getLogger(ImportToDb.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (pst != null) { pst.close(); } if (con != null) { con.close(); } sql = " "; } catch (SQLException ex) { } } } } } else { JOptionPane.showMessageDialog(null, " *Αρχειο bak μονο"); } }
public static void preventSQLInjPage(Page page) { page.setName(DatabaseUtils.preventSQLInjection(page.getName())); page.setContent(DatabaseUtils.preventSQLInjection(page.getContent())); }
public boolean downloadFormAndSubmissionFiles(List<FormStatus> formsToTransfer) { boolean allSuccessful = true; // boolean error = false; int total = formsToTransfer.size(); for (int i = 0; i < total; i++) { FormStatus fs = formsToTransfer.get(i); if (isCancelled()) { fs.setStatusString("aborted. Skipping fetch of form and submissions...", true); EventBus.publish(new FormStatusEvent(fs)); return false; } RemoteFormDefinition fd = (RemoteFormDefinition) fs.getFormDefinition(); fs.setStatusString("Fetching form definition", true); EventBus.publish(new FormStatusEvent(fs)); try { File tmpdl = FileSystemUtils.getTempFormDefinitionFile(); AggregateUtils.commonDownloadFile(serverInfo, tmpdl, fd.getDownloadUrl()); fs.setStatusString("resolving against briefcase form definitions", true); EventBus.publish(new FormStatusEvent(fs)); boolean successful = false; BriefcaseFormDefinition briefcaseLfd; DatabaseUtils formDatabase = null; try { try { briefcaseLfd = BriefcaseFormDefinition.resolveAgainstBriefcaseDefn(tmpdl); if (briefcaseLfd.needsMediaUpdate()) { if (fd.getManifestUrl() != null) { File mediaDir = FileSystemUtils.getMediaDirectory(briefcaseLfd.getFormDirectory()); String error = downloadManifestAndMediaFiles(mediaDir, fs); if (error != null) { allSuccessful = false; fs.setStatusString("Error fetching form definition: " + error, false); EventBus.publish(new FormStatusEvent(fs)); continue; } } } formDatabase = new DatabaseUtils(FileSystemUtils.getFormDatabase(briefcaseLfd.getFormDirectory())); } catch (BadFormDefinition e) { e.printStackTrace(); allSuccessful = false; fs.setStatusString("Error parsing form definition: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } fs.setStatusString("preparing to retrieve instance data", true); EventBus.publish(new FormStatusEvent(fs)); File formInstancesDir = FileSystemUtils.getFormInstancesDirectory(briefcaseLfd.getFormDirectory()); // this will publish events successful = downloadAllSubmissionsForForm(formInstancesDir, formDatabase, briefcaseLfd, fs); } catch (FileSystemException e) { e.printStackTrace(); allSuccessful = false; fs.setStatusString("unable to open form database: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } finally { if (formDatabase != null) { try { formDatabase.close(); } catch (SQLException e) { e.printStackTrace(); allSuccessful = false; fs.setStatusString("unable to close form database: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } } } allSuccessful = allSuccessful && successful; // on success, we haven't actually set a success event (because we don't know we're done) if (successful) { fs.setStatusString("SUCCESS!", true); EventBus.publish(new FormStatusEvent(fs)); } else { fs.setStatusString("FAILED.", true); EventBus.publish(new FormStatusEvent(fs)); } } catch (SocketTimeoutException se) { se.printStackTrace(); allSuccessful = false; fs.setStatusString( "Communications to the server timed out. Detailed message: " + se.getLocalizedMessage() + " while accessing: " + fd.getDownloadUrl() + " A network login screen may be interfering with the transmission to the server.", false); EventBus.publish(new FormStatusEvent(fs)); continue; } catch (IOException e) { e.printStackTrace(); allSuccessful = false; fs.setStatusString( "Unexpected error: " + e.getLocalizedMessage() + " while accessing: " + fd.getDownloadUrl() + " A network login screen may be interfering with the transmission to the server.", false); EventBus.publish(new FormStatusEvent(fs)); continue; } catch (FileSystemException e) { e.printStackTrace(); allSuccessful = false; fs.setStatusString( "Unexpected error: " + e.getLocalizedMessage() + " while accessing: " + fd.getDownloadUrl(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } catch (URISyntaxException e) { e.printStackTrace(); allSuccessful = false; fs.setStatusString( "Unexpected error: " + e.getLocalizedMessage() + " while accessing: " + fd.getDownloadUrl(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } catch (TransmissionException e) { e.printStackTrace(); allSuccessful = false; fs.setStatusString( "Unexpected error: " + e.getLocalizedMessage() + " while accessing: " + fd.getDownloadUrl(), false); EventBus.publish(new FormStatusEvent(fs)); continue; } } return allSuccessful; }
private void downloadSubmission( File formInstancesDir, DatabaseUtils formDatabase, BriefcaseFormDefinition lfd, FormStatus fs, String uri) throws Exception { if (formDatabase.hasRecordedInstance(uri) != null) { logger.info("already present - skipping fetch: " + uri); return; } String formId = lfd.getSubmissionKey(uri); if (isCancelled()) { fs.setStatusString("aborting fetch of submission...", true); EventBus.publish(new FormStatusEvent(fs)); throw new SubmissionDownloadException("Transfer cancelled by user."); } String baseUrl = serverInfo.getUrl() + "/view/downloadSubmission"; Map<String, String> params = new HashMap<String, String>(); params.put("formId", formId); String fullUrl = WebUtils.createLinkWithProperties(baseUrl, params); AggregateUtils.DocumentFetchResult result; try { DocumentDescription submissionDescription = new DocumentDescription( "Fetch of a submission failed. Detailed error: ", "Fetch of a submission failed.", "submission", terminationFuture); result = AggregateUtils.getXmlDocument(fullUrl, serverInfo, false, submissionDescription, null); } catch (XmlDocumentFetchException e) { throw new SubmissionDownloadException(e.getMessage()); } // and parse the document... SubmissionManifest submissionManifest; try { submissionManifest = XmlManipulationUtils.parseDownloadSubmissionResponse(result.doc); } catch (ParsingException e) { throw new SubmissionDownloadException(e.getMessage()); } String msg = "Fetched instanceID=" + submissionManifest.instanceID; logger.info(msg); if (FileSystemUtils.hasFormSubmissionDirectory( formInstancesDir, submissionManifest.instanceID)) { // create instance directory... File instanceDir = FileSystemUtils.assertFormSubmissionDirectory( formInstancesDir, submissionManifest.instanceID); // fetch attachments for (MediaFile m : submissionManifest.attachmentList) { downloadMediaFileIfChanged(instanceDir, m, fs); } // write submission file -- we rely on instanceId being unique... File submissionFile = new File(instanceDir, "submission.xml"); OutputStreamWriter fo = new OutputStreamWriter(new FileOutputStream(submissionFile), "UTF-8"); fo.write(submissionManifest.submissionXml); fo.close(); // if we get here and it was a legacy server (0.9.x), we don't // actually know whether the submission was complete. Otherwise, // if we get here, we know that this is a completed submission // (because it was in /view/submissionList) and that we safely // copied it into the storage area (because we didn't get any // exceptions). if (serverInfo.isOpenRosaServer()) { formDatabase.assertRecordedInstanceDirectory(uri, instanceDir); } } else { // create instance directory... File instanceDir = FileSystemUtils.assertFormSubmissionDirectory( formInstancesDir, submissionManifest.instanceID); // fetch attachments for (MediaFile m : submissionManifest.attachmentList) { downloadMediaFileIfChanged(instanceDir, m, fs); } // write submission file File submissionFile = new File(instanceDir, "submission.xml"); OutputStreamWriter fo = new OutputStreamWriter(new FileOutputStream(submissionFile), "UTF-8"); fo.write(submissionManifest.submissionXml); fo.close(); // if we get here and it was a legacy server (0.9.x), we don't // actually know whether the submission was complete. Otherwise, // if we get here, we know that this is a completed submission // (because it was in /view/submissionList) and that we safely // copied it into the storage area (because we didn't get any // exceptions). if (serverInfo.isOpenRosaServer()) { formDatabase.assertRecordedInstanceDirectory(uri, instanceDir); } } }
@Override public void fillWindow(int position, CursorWindow window) { DatabaseUtils.cursorFillWindow(this, position, window); }