void loadAllSources() { if (isNoThreadedMode()) { RhoRuby.loadAllSyncSources(); } else { getNet().pushData(getNet().resolveUrl("/system/loadallsyncsources"), "", null); } m_sources.removeAllElements(); Vector <String> arPartNames = DBAdapter.getDBAllPartitionNames(); for (int i = 0; i < (int)arPartNames.size(); i++) { DBAdapter dbPart = DBAdapter.getDB((String)arPartNames.elementAt(i)); IDBResult res = dbPart.executeSQL("SELECT source_id,sync_type,name from sources ORDER BY sync_priority"); for ( ; !res.isEnd(); res.next()) { String strShouldSync = res.getStringByIdx(1); if (strShouldSync.compareTo("none") == 0) { continue; } String strName = res.getStringByIdx(2); m_sources.addElement(new SyncSource(res.getIntByIdx(0), strName, strShouldSync, dbPart, this)); } } checkSourceAssociations(); }
public SyncSource(int id, String name, String strSyncType, DBAdapter db, SyncEngine syncEngine) { m_syncEngine = syncEngine; m_dbAdapter = db; m_nID = id; m_strName = name; m_strSyncType = strSyncType; m_nCurPageCount = 0; m_nInserted = 0; m_nDeleted = 0; m_nTotalCount = 0; m_bGetAtLeastOnePage = false; m_nErrCode = RhoAppAdapter.ERR_NONE; IDBResult res = db.executeSQL("SELECT token,associations from sources WHERE source_id=?", m_nID); if (!res.isEnd()) { m_token = res.getLongByIdx(0); m_bTokenFromDB = true; } else { m_token = 0; m_bTokenFromDB = true; } m_bSchemaSource = db.isTableExist(m_strName); parseAssociations(res.getStringByIdx(1)); }
public override int getLastPollInterval() { try{ long nowTime = (TimeInterval.getCurrentTime().toULong()) / 1000; long latestTimeUpdated = 0; Vector <String> arPartNames = DBAdapter.getDBAllPartitionNames(); for (int i = 0; i < (int)arPartNames.size(); i++) { DBAdapter dbPart = DBAdapter.getDB((String)arPartNames.elementAt(i)); IDBResult res = dbPart.executeSQL("SELECT last_updated from sources"); for ( ; !res.isEnd(); res.next()) { long timeUpdated = res.getLongByIdx(0); if (latestTimeUpdated < timeUpdated) { latestTimeUpdated = timeUpdated; } } } return(latestTimeUpdated > 0 ? (int)(nowTime - latestTimeUpdated) : 0); }catch (Exception exc) { LOG.ERROR("isStartSyncNow failed.", exc); } return(0); }
boolean processBlob(String strCmd, String strObject, CAttrValue oAttrValue) { //TODO: when server return delete with rhoblob postfix - delete isBlobAttr if (!(oAttrValue.m_strBlobSuffix.length() > 0 || getDB().getAttrMgr().isBlobAttr(getID(), oAttrValue.m_strAttrib))) { return(true); } boolean bDownload = true; String strDbValue = ""; if (!getDB().getAttrMgr().isOverwriteBlobFromServer(getID(), oAttrValue.m_strAttrib)) { if (m_bSchemaSource) { String strSelect = "SELECT " + oAttrValue.m_strAttrib + " FROM " + getName() + " WHERE object=?"; IDBResult res = getDB().executeSQL(strSelect, strObject); if (!res.isEnd()) { strDbValue = res.getStringByIdx(0); bDownload = strDbValue == null || strDbValue.length() == 0; } } else { IDBResult res = getDB().executeSQL( "SELECT value FROM object_values WHERE object=? and attrib=? and source_id=?", strObject, oAttrValue.m_strAttrib, getID()); if (!res.isEnd()) { strDbValue = res.getStringByIdx(0); bDownload = strDbValue == null || strDbValue.length() == 0; } } } if (bDownload) { boolean bRes = false; getDB().endTransaction(); try{ bRes = downloadBlob(oAttrValue); }finally { getDB().startTransaction(); } return(bRes); } /* * String fName = makeFileName( oAttrValue ); * String fOldName = RHODESAPP().resolveDBFilesPath(strDbValue); * RhoClassFactory.createFile().renameOverwrite(fOldName, fName); * * oAttrValue.m_strValue = FilePath.getRelativePath( fName, RhodesApp.getInstance().getRhoRootPath()); */ oAttrValue.m_strValue = strDbValue; return(true); }
public static RubyArray Execute(RhoDatabase /*!*/ self, MutableString /*!*/ sqlStatement, Boolean isBatch, RubyArray args) { try { RubyArray retArr = new RubyArray(); if (isBatch) { self.m_db.executeBatchSQL(sqlStatement.ToString()); } else { Object[] values = null; if (args != null && args.Count > 0) { if (args[0] != null && args[0] is RubyArray) { values = ((RubyArray)args[0]).ToArray(); } else { values = args.ToArray(); } } using (IDBResult rows = self.m_db.executeSQL(sqlStatement.ToString(), values, true)) { if (rows != null) { MutableString[] colNames = null; for (; !rows.isEnd(); rows.next()) { IDictionary <object, object> map = new Dictionary <object, object>(); Hash row = new Hash(map); for (int nCol = 0; nCol < rows.getColCount(); nCol++) { if (colNames == null) { colNames = getOrigColNames(rows); } row.Add(colNames[nCol], rows.getRubyValueByIdx(nCol)); } retArr.Add(row); } } } } return(retArr); }catch (Exception exc) { //TODO: throw ruby exception throw exc; } }
public CSqliteCopyResult(IDBResult res) { for( int i = 0; i < res.getColCount(); i++) m_arColumns.addElement(res.getColName(i)); for( ; !res.isEnd(); res.next() ) { m_arRows.addElement(res.getCurData()); } }
public boolean isTableExists(string strName) { Object[] vals = { strName }; IDBResult res = executeSQL("SELECT name FROM sqlite_master WHERE type='table' AND name=?", vals, false, false); boolean bRes = !res.isEnd(); res.close(); return(bRes); }
public String loadSession() { m_strSession = ""; IDBResult res = getUserDB().executeSQL("SELECT session FROM client_info"); if (!res.isEnd()) { m_strSession = res.getStringByIdx(0); } return(m_strSession); }
public CSqliteCopyResult(IDBResult res) { for (int i = 0; i < res.getColCount(); i++) { m_arColumns.addElement(res.getColName(i)); } for ( ; !res.isEnd(); res.next()) { m_arRows.addElement(res.getCurData()); } }
public boolean isLoggedIn() { String strRes = ""; IDBResult res = getUserDB().executeSQL("SELECT session FROM client_info"); if (!res.isEnd()) { strRes = res.getStringByIdx(0); } return(strRes.length() > 0); }
private boolean doRegister(SyncEngine oSync) { String session = oSync.loadSession(); if (session == null || session.length() == 0) { m_nPollInterval = POLL_INTERVAL_INFINITE; return(false); } m_nPollInterval = POLL_INTERVAL_SECONDS; String client_id = oSync.loadClientID(); if (client_id == null || client_id.length() == 0) { return(false); } IDBResult res = DBAdapter.getUserDB().executeSQL("SELECT token,token_sent from client_info"); if (!res.isEnd()) { String token = res.getStringByIdx(0); boolean token_sent = res.getIntByIdx(1) > 0 && !RHOCONF().getBool("register_push_at_startup"); if (m_strDevicePin.equals(token) && token_sent) { //token in db same as new one and it was already send to the server //so we do nothing return(true); } } String strBody = getRegisterBody(client_id); NetResponse resp = getNet().pushData(oSync.getProtocol().getClientRegisterUrl(), strBody, oSync); if (resp.isOK()) { try { DBAdapter.getUserDB().executeSQL("UPDATE client_info SET token_sent=?, token=?", 1, m_strDevicePin); } catch (Exception ex) { LOG.ERROR("Error saving token_sent to the DB...", ex); } LOG.INFO("Registered client sucessfully..."); return(true); } else { LOG.INFO("Network error POST-ing device pin to the server..."); } return(false); }
public String loadClientID() { String clientID = ""; lock ( m_mxLoadClientID ) { boolean bResetClient = false; { IDBResult res = getUserDB().executeSQL("SELECT client_id,reset from client_info"); if (!res.isEnd()) { clientID = res.getStringByIdx(0); bResetClient = res.getIntByIdx(1) > 0; } } if (clientID.length() == 0) { clientID = requestClientIDByNet(); IDBResult res = getUserDB().executeSQL("SELECT * FROM client_info"); if (!res.isEnd()) { getUserDB().executeSQL("UPDATE client_info SET client_id=?", clientID); } else { getUserDB().executeSQL("INSERT INTO client_info (client_id) values (?)", clientID); } if (ClientRegister.getInstance() != null) { ClientRegister.getInstance().startUp(); } } else if (bResetClient) { if (!resetClientIDByNet(clientID)) { stopSync(); } else { getUserDB().executeSQL("UPDATE client_info SET reset=? where client_id=?", 0, clientID); } } } return(clientID); }
static void loadAttrs(DBAdapter db, Hashtable <int, Hashtable <String, int> > mapAttrs, String strDBAttr, Hashtable <String, int> mapSrcNames) { mapAttrs.clear(); String strSql = "SELECT source_id,"; strSql += strDBAttr + ",name from sources"; IDBResult res = db.executeSQL(strSql); for ( ; !res.isEnd(); res.next()) { int nSrcID = res.getIntByIdx(0); String strAttribs = res.getStringByIdx(1); if (strAttribs.length() == 0) { continue; } Tokenizer oTokenizer = new Tokenizer(strAttribs, ","); Hashtable <String, int> mapAttr = new Hashtable <String, int>(); String strAttr = ""; while (oTokenizer.hasMoreTokens()) { String tok = oTokenizer.nextToken(); if (tok.length() == 0) { continue; } if (strAttr.length() > 0) { mapAttr.put(strAttr, int.Parse(tok)); strAttr = ""; } else { strAttr = tok; } } mapAttrs.put(nSrcID, mapAttr); if (mapSrcNames != null) { mapSrcNames.put(res.getStringByIdx(2).toUpperCase(), nSrcID); } } }
private void copyTable(String tableName, IDBStorage dbFrom, IDBStorage dbTo) { IDBResult res = dbFrom.executeSQL("SELECT * from " + tableName, null, false, false); String strInsert = ""; for ( ; !res.isEnd(); res.next()) { if (strInsert.length() == 0) { strInsert = createInsertStatement(res, tableName); } dbTo.executeSQL(strInsert, res.getCurData(), false, false); } }
public String readClientID() { String clientID = ""; lock ( m_mxLoadClientID ) { IDBResult res = getUserDB().executeSQL("SELECT client_id,reset from client_info"); if (!res.isEnd()) { clientID = res.getStringByIdx(0); } } return(clientID); }
public void applyChangedValues(DBAdapter db) { IDBResult resSrc = db.executeSQL("SELECT DISTINCT(source_id) FROM changed_values"); for ( ; !resSrc.isEnd(); resSrc.next()) { int nSrcID = resSrc.getIntByIdx(0); IDBResult res = db.executeSQL("SELECT source_id,sync_type,name, partition from sources WHERE source_id=?", nSrcID); if (res.isEnd()) { continue; } SyncSource src = new SyncSource(res.getIntByIdx(0), res.getStringByIdx(2), "none", db, this); src.applyChangedValues(); } }
public string[] getAllTableNames() { IDBResult res = executeSQL("SELECT name FROM sqlite_master WHERE type='table'", null, false, false); Vector <Object> arTables = new Vector <Object>(); for (; !res.isEnd(); res.next()) { arTables.addElement(res.getCurData()[0]); } String[] vecTables = new String[arTables.size()]; for (int i = 0; i < arTables.size(); i++) { vecTables[i] = (String)arTables.elementAt(i); } return(vecTables); }
private void openDB(String strDBName, boolean bTemp) { if (m_bIsOpen) { return; } initFilePaths(strDBName); if (!bTemp) { checkDBVersion(); } m_dbStorage.open(m_strDBPath, getSqlScript(), getEncryptionInfo()); m_bIsOpen = true; //getAttrMgr().load(this); m_dbStorage.setDbCallback(new DBCallback(this)); //m_dbAdapters.addElement(this); //copy client_info table if (!bTemp && m_strClientInfoInsert != null && m_strClientInfoInsert.length() > 0 && m_dataClientInfo != null) { LOG.INFO("Copy client_info table from old database"); m_dbStorage.executeSQL(m_strClientInfoInsert, m_dataClientInfo, false, false); IDBResult res = executeSQL("SELECT client_id FROM client_info"); if (!res.isEnd() && res.getStringByIdx(0).length() > 0) { LOG.INFO("Set reset=1 in client_info"); executeSQL("UPDATE client_info SET reset=1"); } } }
void copyChangedValues(DBAdapter db) { updateAllAttribChanges(); copyTable("changed_values", m_dbStorage, db.m_dbStorage); { Vector <int> arOldSrcs = new Vector <int>(); { IDBResult resSrc = db.executeSQL("SELECT DISTINCT(source_id) FROM changed_values"); for ( ; !resSrc.isEnd(); resSrc.next()) { arOldSrcs.addElement(resSrc.getIntByIdx(0)); } } for (int i = 0; i < arOldSrcs.size(); i++) { int nOldSrcID = arOldSrcs.elementAt(i); IDBResult res = executeSQL("SELECT name from sources WHERE source_id=?", nOldSrcID); if (!res.isEnd()) { String strSrcName = res.getStringByIdx(0); IDBResult res2 = db.executeSQL("SELECT source_id from sources WHERE name=?", strSrcName); if (!res2.isEnd()) { if (nOldSrcID != res2.getIntByIdx(0)) { db.executeSQL("UPDATE changed_values SET source_id=? WHERE source_id=?", res2.getIntByIdx(0), nOldSrcID); } continue; } } //source not exist in new partition, remove this changes db.executeSQL("DELETE FROM changed_values WHERE source_id=?", nOldSrcID); } } }
public boolean syncClientChanges() { boolean bSyncedServer = false; if (isPendingClientChanges()) { LOG.INFO("Client has unconfirmed created items. Call server to update them."); syncServerChanges(); bSyncedServer = true; } if (bSyncedServer && isPendingClientChanges()) { LOG.INFO("Server does not sent created items. Stop sync."); getSync().setState(SyncEngine.esStop); } else { PROF.START("Pull"); boolean bSyncClient = false; { IDBResult res = getDB().executeSQL("SELECT object FROM changed_values WHERE source_id=? LIMIT 1 OFFSET 0", getID()); bSyncClient = !res.isEnd(); } if (bSyncClient) { doSyncClientChanges(); bSyncedServer = false; } PROF.STOP("Pull"); } return(bSyncedServer); }
public void updateAllAttribChanges() { //Check for attrib = object IDBResult res = executeSQL("SELECT object, source_id, update_type " + "FROM changed_values where attrib = 'object' and sent=0"); if (res.isEnd()) { return; } startTransaction(); Vector <String> arObj = new Vector <String>(), arUpdateType = new Vector <String>(); Vector <int> arSrcID = new Vector <int>(); for ( ; !res.isEnd(); res.next()) { arObj.addElement(res.getStringByIdx(0)); arSrcID.addElement(res.getIntByIdx(1)); arUpdateType.addElement(res.getStringByIdx(2)); } for (int i = 0; i < (int)arObj.size(); i++) { IDBResult resSrc = executeSQL("SELECT name, schema FROM sources where source_id=?", arSrcID.elementAt(i)); boolean bSchemaSource = false; String strTableName = "object_values"; if (!resSrc.isEnd()) { bSchemaSource = resSrc.getStringByIdx(1).length() > 0; if (bSchemaSource) { strTableName = resSrc.getStringByIdx(0); } } if (bSchemaSource) { IDBResult res2 = executeSQL("SELECT * FROM " + strTableName + " where object=?", arObj.elementAt(i)); for (int j = 0; j < res2.getColCount(); j++) { String strAttrib = res2.getColName(j); String value = res2.getStringByIdx(j); String attribType = getAttrMgr().isBlobAttr(arSrcID.elementAt(i), strAttrib) ? "blob.file" : ""; executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)", arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, 0); } } else { IDBResult res2 = executeSQL("SELECT attrib, value FROM " + strTableName + " where object=? and source_id=?", arObj.elementAt(i), arSrcID.elementAt(i)); for ( ; !res2.isEnd(); res2.next()) { String strAttrib = res2.getStringByIdx(0); String value = res2.getStringByIdx(1); String attribType = getAttrMgr().isBlobAttr(arSrcID.elementAt(i), strAttrib) ? "blob.file" : ""; executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)", arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, 0); } } } executeSQL("DELETE FROM changed_values WHERE attrib='object'"); endTransaction(); }
void checkDBVersion() { DBVersion dbNewVer = new DBVersion(); dbNewVer.m_strRhoVer = RhoRuby.getRhoDBVersion(); dbNewVer.m_strAppVer = RhoConf.getInstance().getString("app_db_version"); String strEncryptionInfo = getEncryptionInfo(); dbNewVer.m_bEncrypted = strEncryptionInfo != null && strEncryptionInfo.length() > 0; dbNewVer.m_bSqlite = true; DBVersion dbVer = new DBVersion(); dbVer.fromFile(m_strDbVerPath); if (dbVer.m_strRhoVer.length() == 0) { dbNewVer.toFile(m_strDbVerPath); return; } boolean bRhoReset = dbVer.isRhoVerChanged(dbNewVer); boolean bAppReset = dbVer.isAppVerChanged(dbNewVer); boolean bDbFormatChanged = dbVer.isDbFormatChanged(dbNewVer); if (!bDbFormatChanged && dbVer.m_bEncrypted) { //TODO: check encryption key //if (!com.rho.RhoCrypto.isKeyExist(strEncryptionInfo) ) // bDbFormatChanged = true; } if (bDbFormatChanged) { LOG.INFO("Reset Database( format changed ):" + m_strDBPath); } if (bRhoReset && !bAppReset && !bDbFormatChanged) { bRhoReset = !migrateDB(dbVer, dbNewVer); } if (bRhoReset || bAppReset || bDbFormatChanged) { if (!bDbFormatChanged) { IDBStorage db = null; try { db = RhoClassFactory.createDBStorage(); if (db.isDbFileExists(m_strDBPath)) { db.open(m_strDBPath, "", strEncryptionInfo); IDBResult res = db.executeSQL("SELECT * FROM client_info", null, false, false); if (!res.isEnd()) { m_strClientInfoInsert = createInsertStatement(res, "client_info"); m_dataClientInfo = res.getCurData(); } } }catch (Exception exc) { LOG.ERROR("Copy client_info table failed.", exc); }finally { if (db != null) { try { db.close(); } catch (Exception) { } } } } m_dbStorage.deleteAllFiles(m_strDBPath); if (this.m_strDbPartition.compareTo("user") == 0) //do it only once { String fName = makeBlobFolderName(); CRhoFile.deleteDirectory(fName); makeBlobFolderName(); //Create folder back } dbNewVer.toFile(m_strDbVerPath); if (RhoConf.getInstance().isExist("bulksync_state") && RhoConf.getInstance().getInt("bulksync_state") != 0) { RhoConf.getInstance().setInt("bulksync_state", 0, true); } } }
private void processDelete(String tableName, IDBResult rows2Delete, int[] cols) { if (tableName.equalsIgnoreCase("changed_values") || tableName.equalsIgnoreCase("sources") || tableName.equalsIgnoreCase("client_info")) { return; } boolean bProcessTable = tableName.equalsIgnoreCase("object_values"); boolean bSchemaSrc = false; int nSrcID = 0; if (!bProcessTable) { nSrcID = m_db.getAttrMgr().getSrcIDHasBlobsByName(tableName); bProcessTable = nSrcID != 0; bSchemaSrc = bProcessTable; } if (!bProcessTable) { return; } if (!bSchemaSrc && !isChangedCol(cols, 3)) //value { return; } for ( ; !rows2Delete.isEnd(); rows2Delete.next()) { if (!bSchemaSrc) { nSrcID = rows2Delete.getIntByIdx(0); String attrib = rows2Delete.getStringByIdx(1); String value = rows2Delete.getStringByIdx(3); //if (cols == null) //delete // m_db.getAttrMgr().remove(nSrcID, attrib); if (m_db.getAttrMgr().isBlobAttr(nSrcID, attrib)) { processBlobDelete(nSrcID, attrib, value); } } else { Object[] data = rows2Delete.getCurData(); for (int i = 0; i < rows2Delete.getColCount(); i++) { if (!isChangedCol(cols, i)) { continue; } String attrib = rows2Delete.getColName(i); if (!(data[i] is String)) { continue; } String value = (String)data[i]; if (m_db.getAttrMgr().isBlobAttr(nSrcID, attrib)) { processBlobDelete(nSrcID, attrib, value); } } } } }
public void loadBlobAttrs(DBAdapter db) { loadAttrs(db, m_mapBlobAttrs, "blob_attribs", m_mapSrcNames); String strTriggerPrefix = "rhoSchemaTrigger_"; IDBResult res = db.executeSQL("SELECT name FROM sqlite_master WHERE type='trigger'"); Hashtable <String, int> mapTriggers = new Hashtable <String, int>(); for (; !res.isEnd(); res.next()) { String strName = res.getStringByIdx(0); if (!strName.startsWith(strTriggerPrefix)) { continue; } mapTriggers[strName.Substring(strTriggerPrefix.length())] = 0; } foreach (KeyValuePair <int, Hashtable <String, int> > kvpBlobAttrs in m_mapBlobAttrs) { int nSrcID = kvpBlobAttrs.Key; res = db.executeSQL("SELECT name FROM sources WHERE source_id=?", nSrcID); if (res.isEnd()) { continue; } String strName = res.getStringByIdx(0); if (!db.isTableExist(strName)) { continue; } Hashtable <String, int> hashAttribs = kvpBlobAttrs.Value; foreach (KeyValuePair <String, int> kvpHashAttribs in hashAttribs) { String strTriggerName = strName + "_" + kvpHashAttribs.Key; if (!mapTriggers.containsKey(strTriggerName + "_delete")) { String strTrigger = "CREATE TRIGGER " + strTriggerPrefix + strTriggerName + "_delete BEFORE DELETE ON \"" + strName + "\" FOR EACH ROW \r\n" + " BEGIN \r\n" + " SELECT rhoOnDeleteSchemaRecord( OLD." + kvpHashAttribs.Key + ");\r\n" + " END;\r\n" + ";"; db.createTrigger(strTrigger); } else { mapTriggers[strTriggerName + "_delete"] = 1; } if (!mapTriggers.containsKey(strTriggerName + "_update")) { String strTrigger = "CREATE TRIGGER " + strTriggerPrefix + strTriggerName + "_update BEFORE UPDATE ON \"" + strName + "\" FOR EACH ROW\r\n" + " BEGIN \r\n" + " SELECT rhoOnUpdateSchemaRecord( OLD." + kvpHashAttribs.Key + ", NEW." + kvpHashAttribs.Key + ");\r\n" + " END;\r\n" + ";"; db.createTrigger(strTrigger); } else { mapTriggers[strTriggerName + "_update"] = 1; } } } //Remove outdated triggers foreach (KeyValuePair <string, int> kvp in mapTriggers) { if (kvp.Value != 0) { db.dropTrigger(strTriggerPrefix + kvp.Key.ToString()); } } }
private void processDelete(String tableName, IDBResult rows2Delete, int[] cols) { if ( tableName.equalsIgnoreCase("changed_values") || tableName.equalsIgnoreCase("sources") || tableName.equalsIgnoreCase("client_info")) return; boolean bProcessTable = tableName.equalsIgnoreCase("object_values"); boolean bSchemaSrc = false; int nSrcID = 0; if ( !bProcessTable ) { nSrcID = m_db.getAttrMgr().getSrcIDHasBlobsByName(tableName); bProcessTable = nSrcID != 0; bSchemaSrc = bProcessTable; } if ( !bProcessTable) return; if ( !bSchemaSrc && !isChangedCol(cols, 3))//value return; for( ; !rows2Delete.isEnd(); rows2Delete.next() ) { if ( !bSchemaSrc ) { nSrcID = rows2Delete.getIntByIdx(0); String attrib = rows2Delete.getStringByIdx(1); String value = rows2Delete.getStringByIdx(3); //if (cols == null) //delete // m_db.getAttrMgr().remove(nSrcID, attrib); if ( m_db.getAttrMgr().isBlobAttr(nSrcID, attrib) ) processBlobDelete(nSrcID, attrib, value); }else { Object[] data = rows2Delete.getCurData(); for ( int i = 0; i < rows2Delete.getColCount(); i++ ) { if (!isChangedCol(cols, i)) continue; String attrib = rows2Delete.getColName(i); if ( !(data[i] is String ) ) continue; String value = (String)data[i]; if ( m_db.getAttrMgr().isBlobAttr(nSrcID, attrib) ) processBlobDelete(nSrcID, attrib, value); } } } }
//{"source_name":"SampleAdapter","client_id":1,"create":{"1":{"brand":"Apple","name":"iPhone","price":"199.99"}}} //{"source_name":"SampleAdapter","client_id":1,"update":{"1":{"brand":"Apple","name":"iPhone","price":"199.99"}}} //{"source_name":"SampleAdapter","client_id":1,"delete":{"1":{"brand":"Apple","name":"iPhone","price":"199.99"}}} //{"source_name":"SampleAdapter","client_id":1,"delete":{"3":{"brand":"HTC","name":"Fuze","price":"299.99"}},"create":{"1":{"brand":"Apple","name":"iPhone","price":"199.99"}},"update":{"2":{"brand":"Android","name":"G2","price":"99.99"}}} String makePushBody_Ver3(String strUpdateType, boolean isSync) { String strBody = ""; getDB().Lock(); if (isSync) { getDB().updateAllAttribChanges(); } IDBResult res = getDB().executeSQL("SELECT attrib, object, value, attrib_type " + "FROM changed_values where source_id=? and update_type =? and sent<=1 ORDER BY object", getID(), strUpdateType); if (res.isEnd()) { res.close(); getDB().Unlock(); return(strBody); } String strCurObject = ""; boolean bFirst = true; for ( ; !res.isEnd(); res.next()) { String strAttrib = res.getStringByIdx(0); String strObject = res.getStringByIdx(1); String value = res.getStringByIdx(2); String attribType = res.getStringByIdx(3); if (attribType.compareTo("blob.file") == 0) { NetRequest.MultipartItem oItem = new NetRequest.MultipartItem(); oItem.m_strFilePath = RHODESAPP().resolveDBFilesPath(value); oItem.m_strContentType = "application/octet-stream"; oItem.m_strName = strAttrib + "-" + strObject; m_arBlobAttrs.addElement(strAttrib); m_arMultipartItems.addElement(oItem); } if (strBody.length() == 0) { if (!isSync) { strBody += "{"; } else { strBody += "\"" + strUpdateType + "\":{"; } } if (strObject.compareTo(strCurObject) != 0) { if (strCurObject.length() > 0) { if (!bFirst) { strBody += "}"; } strBody += ","; } bFirst = true; strBody += JSONEntry.quoteValue(strObject); strCurObject = strObject; } if (!bFirst) { strBody += ","; } if (strAttrib.length() > 0) { if (bFirst) { strBody += ":{"; } strBody += JSONEntry.quoteValue(strAttrib) + ":" + JSONEntry.quoteValue(value); bFirst = false; } } if (strBody.length() > 0) { if (!bFirst) { strBody += "}"; } strBody += "}"; } if (isSync) { getDB().executeSQL("UPDATE changed_values SET sent=1 WHERE source_id=? and update_type=? and sent=0", getID(), strUpdateType); } getDB().Unlock(); return(strBody); }
void processServerCmd_Ver3_Schema(String strCmd, String strObject, JSONStructIterator attrIter) { if (strCmd.compareTo("insert") == 0) { Vector <String> vecValues = new Vector <String>(), vecAttrs = new Vector <String>(); String strCols = "", strQuest = "", strSet = ""; for ( ; !attrIter.isEnd() && getSync().isContinueSync(); attrIter.next()) { CAttrValue oAttrValue = new CAttrValue(attrIter.getCurKey(), attrIter.getCurString()); if (!processBlob(strCmd, strObject, oAttrValue)) { continue; } if (strCols.length() > 0) { strCols += ","; } if (strQuest.length() > 0) { strQuest += ","; } if (strSet.length() > 0) { strSet += ","; } strCols += oAttrValue.m_strAttrib; strQuest += "?"; strSet += oAttrValue.m_strAttrib + "=?"; vecAttrs.addElement(oAttrValue.m_strAttrib); vecValues.addElement(oAttrValue.m_strValue); } vecValues.addElement(strObject); if (strCols.length() > 0) { strCols += ","; } if (strQuest.length() > 0) { strQuest += ","; } strCols += "object"; strQuest += "?"; String strSqlInsert = "INSERT INTO "; strSqlInsert += getName() + " ("; strSqlInsert += strCols + ") VALUES(" + strQuest + ")"; if (!getSync().isContinueSync()) { return; } IDBResult resInsert = getDB().executeSQLReportNonUniqueEx(strSqlInsert, vecValues); if (resInsert.isNonUnique()) { String strSqlUpdate = "UPDATE "; strSqlUpdate += getName() + " SET " + strSet + " WHERE object=?"; getDB().executeSQLEx(strSqlUpdate, vecValues); if (getSyncType().compareTo("none") != 0) { // oo conflicts for (int i = 0; i < (int)vecAttrs.size(); i++) { getDB().executeSQL("UPDATE changed_values SET sent=4 where object=? and attrib=? and source_id=? and sent>1", strObject, vecAttrs.elementAt(i), getID()); } // } } if (getSyncType().compareTo("none") != 0) { getNotify().onObjectChanged(getID(), strObject, SyncNotify.enUpdate); } m_nInserted++; } else if (strCmd.compareTo("delete") == 0) { Vector <String> vecAttrs = new Vector <String>(); String strSet = ""; for ( ; !attrIter.isEnd() && getSync().isContinueSync(); attrIter.next()) { CAttrValue oAttrValue = new CAttrValue(attrIter.getCurKey(), attrIter.getCurString()); if (strSet.length() > 0) { strSet += ","; } vecAttrs.addElement(oAttrValue.m_strAttrib); strSet += oAttrValue.m_strAttrib + "=NULL"; } String strSqlUpdate = "UPDATE "; strSqlUpdate += getName() + " SET " + strSet + " WHERE object=?"; if (strSet.length() == 0 || !getSync().isContinueSync()) { return; } getDB().executeSQL(strSqlUpdate, strObject); //Remove item if all nulls String strSelect = "SELECT * FROM " + getName() + " WHERE object=?"; IDBResult res = getDB().executeSQL(strSelect, strObject); if (!res.isEnd()) { boolean bAllNulls = true; for (int i = 0; i < res.getColCount(); i++) { if (!res.isNullByIdx(i) && res.getColName(i).compareTo("object") != 0) { bAllNulls = false; break; } } if (bAllNulls) { String strDelete = "DELETE FROM " + getName() + " WHERE object=?"; getDB().executeSQL(strDelete, strObject); } } if (getSyncType().compareTo("none") != 0) { getNotify().onObjectChanged(getID(), strObject, SyncNotify.enDelete); // oo conflicts for (int i = 0; i < (int)vecAttrs.size(); i++) { getDB().executeSQL("UPDATE changed_values SET sent=3 where object=? and attrib=? and source_id=?", strObject, vecAttrs.elementAt(i), getID()); } // } m_nDeleted++; } else if (strCmd.compareTo("links") == 0) { String strValue = attrIter.getCurString(); processAssociations(strObject, strValue); String strSqlUpdate = "UPDATE "; strSqlUpdate += getName() + " SET object=? WHERE object=?"; getDB().executeSQL(strSqlUpdate, strValue, strObject); getDB().executeSQL("UPDATE changed_values SET object=?,sent=3 where object=? and source_id=?", strValue, strObject, getID()); getNotify().onObjectChanged(getID(), strObject, SyncNotify.enCreate); } }
boolean isPendingClientChanges() { IDBResult res = getDB().executeSQL("SELECT object FROM changed_values WHERE source_id=? and update_type='create' and sent>1 LIMIT 1 OFFSET 0", getID()); return(!res.isEnd()); }
public void login(String name, String password, SyncNotify.SyncNotification oNotify) { try { /* * processServerSources("{\"sources\":{ \"ProductEx\":{ "+ * "\"sync_type\":\"incremental\", \"partition\":\"application\", \"source_id\":\"7\","+ * " \"sync_priority\":\"0\", \"model_type\":\"fixed_schema\", "+ * " \"schema\":{\"version\":\"1.1\", \"property\":{\"brand\":\"string\", \"price\":\"string\", \"quantity\":\"string\", \"name\":\"string\", "+ * " \"image_url\":\"blob\", \"image_url_ex\":\"blob,overwrite\"}, "+ * " \"index\":[{\"by_brand_price1\":\"brand,price\"}, {\"by_quantity1\":\"quantity\"}], \"unique_index\":[{\"by_name1\":\"name\"}]}, "+ * " \"belongs_to\":{\"brand\":\"Customer\"}}}}");//, \"schema_version\":\"1.0\" */ NetResponse resp = null; m_bStopByUser = false; try{ resp = getNet().pullCookies(getProtocol().getLoginUrl(), getProtocol().getLoginBody(name, password), this); int nErrCode = RhoAppAdapter.getErrorFromResponse(resp); if (nErrCode != RhoAppAdapter.ERR_NONE) { getNotify().callLoginCallback(oNotify, nErrCode, resp.getCharData()); return; } }catch (Exception exc) { LOG.ERROR("Login failed.", exc); getNotify().callLoginCallback(oNotify, RhoAppAdapter.getNetErrorCode(exc), ""); return; } String strSession = resp.getCharData(); if (strSession == null || strSession.length() == 0) { LOG.ERROR("Return empty session."); getNotify().callLoginCallback(oNotify, RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE, ""); return; } if (isStoppedByUser()) { return; } IDBResult res = getUserDB().executeSQL("SELECT * FROM client_info"); if (!res.isEnd()) { getUserDB().executeSQL("UPDATE client_info SET session=?", strSession); } else { getUserDB().executeSQL("INSERT INTO client_info (session) values (?)", strSession); } if (RHOCONF().isExist("rho_sync_user")) { String strOldUser = RHOCONF().getString("rho_sync_user"); if (name.compareTo(strOldUser) != 0) { if (isNoThreadedMode()) { RhoRuby.resetDBOnSyncUserChanged(); } else { NetResponse resp1 = getNet().pushData(getNet().resolveUrl("/system/resetDBOnSyncUserChanged"), "", null); } } } RHOCONF().setString("rho_sync_user", name, true); getNotify().callLoginCallback(oNotify, RhoAppAdapter.ERR_NONE, ""); if (ClientRegister.getInstance() != null) { getUserDB().executeSQL("UPDATE client_info SET token_sent=?", 0); ClientRegister.getInstance().startUp(); } }catch (Exception exc) { LOG.ERROR("Login failed.", exc); getNotify().callLoginCallback(oNotify, RhoAppAdapter.ERR_RUNTIME, ""); } }