boolean callNotify(SyncNotification oNotify, String strBody) { if (getSync().isNoThreadedMode()) { m_strNotifyBody = strBody; return(false); } if (oNotify.m_strUrl.length() == 0) { return(true); } NetResponse resp = getNet().pushData(oNotify.m_strUrl, strBody, null); if (!resp.isOK()) { LOG.ERROR("Fire object notification failed. Code: " + resp.getRespCode() + "; Error body: " + resp.getCharData()); } else { String szData = resp.getCharData(); return(szData != null && szData.equals("stop")); } return(false); }
boolean resetClientIDByNet(String strClientID) { //String strBody = ""; //TODO: send client register info in client reset // if ( ClientRegister.getInstance() != null ) // strBody += ClientRegister.getInstance().getRegisterBody(); NetResponse resp = getNetClientID().pullData(getProtocol().getClientResetUrl(strClientID), this); /* * processServerSources("{\"server_sources\":[{\"name\":\"Product\",\"partition\":\"application\",\"source_id\":\"2\",\"sync_priority\":\"0\","+ * "\"schema_version\":\"7.0\",\"schema\":{"+ * "\"columns\":[\'brand\',\'created_at\',\'name\',\'price\',\'quantity\',\'sku\',\'updated_at\']"+ * "}}]}"); */ if (!resp.isOK()) { m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); m_strError = resp.getCharData(); } /*else * { * processServerSources(resp.getCharData()); * }*/ return(resp.isOK()); }
String requestClientIDByNet() { //String strBody = ""; //TODO: send client register info in client create // if ( ClientRegister.getInstance() != null ) // strBody += ClientRegister.getInstance().getRegisterBody(); NetResponse resp = getNetClientID().pullData(getProtocol().getClientCreateUrl(), this); if (resp.isOK() && resp.getCharData() != null) { String szData = resp.getCharData(); JSONEntry oJsonEntry = new JSONEntry(szData); //if (oJsonEntry.hasName("sources") ) // processServerSources(szData); JSONEntry oJsonObject = oJsonEntry.getEntry("client"); if (!oJsonObject.isEmpty()) { return(oJsonObject.getString("client_id")); } } else { m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); if (m_nErrCode == RhoAppAdapter.ERR_NONE) { m_nErrCode = RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE; m_strError = resp.getCharData(); } } return(""); }
boolean resetClientIDByNet(String strClientID) { NetResponse resp = getNetClientID().pullData(getProtocol().getClientResetUrl(strClientID), this); if (!resp.isOK()) { m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); m_strError = resp.getCharData(); } else { RHOCONF().setString("reset_models", "", true); } return(resp.isOK()); }
void loadBulkPartition(String strPartition) { DBAdapter dbPartition = getDB(strPartition); String serverUrl = RhoConf.getInstance().getPath("syncserver"); String strUrl = serverUrl + "bulk_data"; String strQuery = "?client_id=" + m_clientID + "&partition=" + strPartition; String strDataUrl = "", strCmd = "", strCryptKey = ""; getNotify().fireBulkSyncNotification(false, "start", strPartition, RhoAppAdapter.ERR_NONE); while (strCmd.length() == 0 && isContinueSync()) { NetResponse resp = getNet().pullData(strUrl + strQuery, this); if (!resp.isOK() || resp.getCharData() == null) { LOG.ERROR("Bulk sync failed: server return an error."); stopSync(); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.getErrorFromResponse(resp)); return; } LOG.INFO("Bulk sync: got response from server: " + resp.getCharData()); String szData = resp.getCharData(); JSONEntry oJsonEntry = new JSONEntry(szData); strCmd = oJsonEntry.getString("result"); if (oJsonEntry.hasName("url")) { strDataUrl = oJsonEntry.getString("url"); } if (strCmd.compareTo("wait") == 0) { int nTimeout = RhoConf.getInstance().getInt("bulksync_timeout_sec"); if (nTimeout == 0) { nTimeout = 5; } SyncThread.getInstance().wait(nTimeout); strCmd = ""; } } if (strCmd.compareTo("nop") == 0) { LOG.INFO("Bulk sync return no data."); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.ERR_NONE); return; } if (!isContinueSync()) { return; } getNotify().fireBulkSyncNotification(false, "download", strPartition, RhoAppAdapter.ERR_NONE); String fDataName = makeBulkDataFileName(strDataUrl, dbPartition.getDBPath(), ""); String strZip = ".rzip"; String strSqlDataUrl = CFilePath.join(getHostFromUrl(serverUrl), strDataUrl) + strZip; LOG.INFO("Bulk sync: download data from server: " + strSqlDataUrl); { NetResponse resp1 = getNet().pullFile(strSqlDataUrl, fDataName + strZip, this, null); if (!resp1.isOK()) { LOG.ERROR("Bulk sync failed: cannot download database file."); stopSync(); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.getErrorFromResponse(resp1)); return; } } if (!isContinueSync()) { return; } LOG.INFO("Bulk sync: unzip db"); if (!RHODESAPP().unzip_file(fDataName + strZip)) { CRhoFile.deleteFile(fDataName + strZip); LOG.ERROR("Bulk sync failed: cannot unzip database file."); stopSync(); getNotify().fireBulkSyncNotification(true, "", strPartition, RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE); return; } CRhoFile.deleteFile(fDataName + strZip); LOG.INFO("Bulk sync: start change db"); getNotify().fireBulkSyncNotification(false, "change_db", strPartition, RhoAppAdapter.ERR_NONE); dbPartition.setBulkSyncDB(fDataName, strCryptKey); processServerSources("{\"partition\":\"" + strPartition + "\"}"); LOG.INFO("Bulk sync: end change db"); getNotify().fireBulkSyncNotification(false, "", strPartition, RhoAppAdapter.ERR_NONE); }
public void doSearch(Vector <String> arSources, String strParams, String strAction, boolean bSearchSyncChanges, int nProgressStep) { try { prepareSync(esSearch, null); if (!isContinueSync()) { if (getState() != esExit) { setState(esNone); } return; } TimeInterval startTime = TimeInterval.getCurrentTime(); if (bSearchSyncChanges) { for (int i = 0; i < (int)arSources.size(); i++) { SyncSource pSrc = findSourceByName((String)arSources.elementAt(i)); if (pSrc != null) { pSrc.syncClientChanges(); } } } while (isContinueSync()) { int nSearchCount = 0; String strUrl = getProtocol().getServerQueryUrl(strAction); String strQuery = getProtocol().getServerQueryBody("", getClientID(), getSyncPageSize()); if (strParams.length() > 0) { strQuery += strParams; } String strTestResp = ""; for (int i = 0; i < (int)arSources.size(); i++) { SyncSource pSrc = findSourceByName((String)arSources.elementAt(i)); if (pSrc != null) { strQuery += "&sources[][name]=" + pSrc.getName(); if (!pSrc.isTokenFromDB() && pSrc.getToken() > 1) { strQuery += "&sources[][token]=" + pSrc.getToken(); } strTestResp = getSourceOptions().getProperty(pSrc.getID(), "rho_server_response"); } } LOG.INFO("Call search on server. Url: " + (strUrl + strQuery)); NetResponse resp = getNet().pullData(strUrl + strQuery, this); if (!resp.isOK()) { stopSync(); m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); m_strError = resp.getCharData(); continue; } String szData = null; if (strTestResp != null && strTestResp.length() > 0) { szData = strTestResp; } else { szData = resp.getCharData(); } JSONArrayIterator oJsonArr = new JSONArrayIterator(szData); for ( ; !oJsonArr.isEnd() && isContinueSync(); oJsonArr.next()) { JSONArrayIterator oSrcArr = oJsonArr.getCurArrayIter(); //new JSONArrayIterator(oJsonArr.getCurItem()); if (oSrcArr.isEnd()) { break; } int nVersion = 0; if (!oSrcArr.isEnd() && oSrcArr.getCurItem().hasName("version")) { nVersion = oSrcArr.getCurItem().getInt("version"); oSrcArr.next(); } if (nVersion != getProtocol().getVersion()) { LOG.ERROR("Sync server send search data with incompatible version. Client version: " + getProtocol().getVersion() + "; Server response version: " + nVersion); stopSync(); m_nErrCode = RhoAppAdapter.ERR_SYNCVERSION; continue; } if (!oSrcArr.isEnd() && oSrcArr.getCurItem().hasName("token")) { oSrcArr.next(); } if (!oSrcArr.getCurItem().hasName("source")) { LOG.ERROR("Sync server send search data without source name."); stopSync(); m_nErrCode = RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE; m_strError = szData; continue; } String strSrcName = oSrcArr.getCurItem().getString("source"); SyncSource pSrc = findSourceByName(strSrcName); if (pSrc == null) { LOG.ERROR("Sync server send search data for unknown source name:" + strSrcName); stopSync(); m_nErrCode = RhoAppAdapter.ERR_UNEXPECTEDSERVERRESPONSE; m_strError = szData; continue; } oSrcArr.reset(0); pSrc.setProgressStep(nProgressStep); pSrc.processServerResponse_ver3(oSrcArr); nSearchCount += pSrc.getCurPageCount(); if (pSrc.getServerError().length() > 0) { if (m_strServerError.length() > 0) { m_strServerError += "&"; } m_strServerError += pSrc.getServerError(); m_nErrCode = pSrc.getErrorCode(); } } if (nSearchCount == 0) { for (int i = 0; i < (int)arSources.size(); i++) { SyncSource pSrc = findSourceByName((String)arSources.elementAt(i)); if (pSrc != null) { pSrc.processToken(0); } } break; } } getNotify().fireAllSyncNotifications(true, m_nErrCode, m_strError, m_strServerError); //update db info TimeInterval endTime = TimeInterval.getCurrentTime(); //unsigned long timeUpdated = CLocalTime().toULong(); for (int i = 0; i < (int)arSources.size(); i++) { SyncSource oSrc = findSourceByName((String)arSources.elementAt(i)); if (oSrc == null) { continue; } oSrc.getDB().executeSQL("UPDATE sources set last_updated=?,last_inserted_size=?,last_deleted_size=?, " + "last_sync_duration=?,last_sync_success=?, backend_refresh_time=? WHERE source_id=?", endTime.toULong() / 1000, oSrc.getInsertedCount(), oSrc.getDeletedCount(), endTime.minus(startTime).toULong(), oSrc.getGetAtLeastOnePage()?1:0, oSrc.getRefreshTime(), oSrc.getID()); } // getNotify().cleanCreateObjectErrors(); if (getState() != esExit) { setState(esNone); } } catch (Exception exc) { LOG.ERROR("Search failed.", exc); getNotify().fireAllSyncNotifications(true, RhoAppAdapter.ERR_RUNTIME, "", ""); } }
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, ""); } }
void syncServerChanges() { LOG.INFO("Sync server changes source ID :" + getID()); while (getSync().isContinueSync()) { setCurPageCount(0); String strUrl = getProtocol().getServerQueryUrl(""); String strQuery = getProtocol().getServerQueryBody(getName(), getSync().getClientID(), getSync().getSyncPageSize()); if (!m_bTokenFromDB && getToken() > 1) { strQuery += "&token=" + getToken(); } LOG.INFO("Pull changes from server. Url: " + (strUrl + strQuery)); NetResponse resp = null; try{ PROF.START("Net"); resp = getNet().pullData(strUrl + strQuery, getSync()); PROF.STOP("Net"); if (!resp.isOK()) { getSync().stopSync(); m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp); m_strError = resp.getCharData(); continue; } }catch (Exception exc) { m_nErrCode = RhoAppAdapter.getNetErrorCode(exc); throw exc; } String szData = null; String strTestResp = SyncEngine.getSourceOptions().getProperty(getID(), "rho_server_response"); if (strTestResp != null && strTestResp.length() > 0) { szData = strTestResp; } else { szData = resp.getCharData(); } PROF.START("Parse"); JSONArrayIterator oJsonArr = new JSONArrayIterator(szData); PROF.STOP("Parse"); processServerResponse_ver3(oJsonArr); if (SyncEngine.getSourceOptions().getBoolProperty(getID(), "pass_through")) { processToken(0); } if (getToken() == 0) { break; } } if (getSync().isSchemaChanged()) { getSync().stopSync(); } }
void doSyncClientChanges() { String[] arUpdateTypes = { "create", "update", "delete" }; boolean[] arUpdateSent = { false, false, false }; m_arMultipartItems.removeAllElements(); m_arBlobAttrs.removeAllElements(); String strBody = "{\"source_name\":" + JSONEntry.quoteValue(getName()) + ",\"client_id\":" + JSONEntry.quoteValue(getSync().getClientID()); boolean bSend = false; int i = 0; for (i = 0; i < 3 && getSync().isContinueSync(); i++) { String strBody1; strBody1 = makePushBody_Ver3(arUpdateTypes[i], true); if (strBody1.length() > 0) { strBody += "," + strBody1; String strBlobAttrs = ""; for (int j = 0; j < (int)m_arBlobAttrs.size(); j++) { if (strBlobAttrs.length() > 0) { strBlobAttrs += ","; } strBlobAttrs += JSONEntry.quoteValue((String)m_arBlobAttrs.elementAt(j)); } if (strBlobAttrs.length() > 0) { strBody += ",\"blob_fields\":[" + strBlobAttrs + "]"; } arUpdateSent[i] = true; bSend = true; } } strBody += "}"; if (bSend) { LOG.INFO("Push client changes to server. Source: " + getName() + "Size :" + strBody.length()); LOG.TRACE("Push body: " + strBody); try{ if (m_arMultipartItems.size() > 0) { NetRequest.MultipartItem oItem = new NetRequest.MultipartItem(); oItem.m_strBody = strBody; //oItem.m_strContentType = getProtocol().getContentType(); oItem.m_strName = "cud"; m_arMultipartItems.addElement(oItem); NetResponse resp = getNet().pushMultipartData(getProtocol().getClientChangesUrl(), m_arMultipartItems, getSync(), null); if (!resp.isOK()) { getSync().setState(SyncEngine.esStop); m_nErrCode = RhoAppAdapter.ERR_REMOTESERVER; m_strError = resp.getCharData(); } } else { NetResponse resp = getNet().pushData(getProtocol().getClientChangesUrl(), strBody, getSync()); if (!resp.isOK()) { getSync().setState(SyncEngine.esStop); m_nErrCode = RhoAppAdapter.ERR_REMOTESERVER; m_strError = resp.getCharData(); } } }catch (Exception exc) { m_nErrCode = RhoAppAdapter.getNetErrorCode(exc); throw exc; } } for (i = 0; i < 3 && getSync().isContinueSync(); i++) { if (arUpdateSent[i]) { //oo conflicts if (i < 1) //create { getDB().executeSQL("UPDATE changed_values SET sent=2 WHERE source_id=? and update_type=? and sent=1", getID(), arUpdateTypes[i]); } else { // getDB().executeSQL("DELETE FROM changed_values WHERE source_id=? and update_type=? and sent=1", getID(), arUpdateTypes[i]); } } } m_arMultipartItems.removeAllElements(); m_arBlobAttrs.removeAllElements(); }