Beispiel #1
0
        public void reportSyncStatus(String status, int error, String strDetails)
        {
            lock (m_mxSyncNotifications)
            {
                if (m_syncStatusListener != null && (isReportingEnabled() || error == RhoAppAdapter.ERR_SYNCVERSION))
                {
                    if (error == RhoAppAdapter.ERR_SYNCVERSION)
                    {
                        status = RhoAppAdapter.getErrorText(error);
                    }
                    else
                    {
                        if (strDetails.length() == 0)
                        {
                            strDetails = RhoAppAdapter.getErrorText(error);
                        }
                        status += (strDetails.length() > 0 ? RhoAppAdapter.getMessageText("details") + strDetails: "");
                    }

                    LOG.INFO("Status: " + status);

                    m_syncStatusListener.reportStatus(status, error);
                }
            }
        }
Beispiel #2
0
        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());
        }
Beispiel #3
0
        public void fireAllSyncNotifications(boolean bFinish, int nErrCode, String strError, String strServerError)
        {
            if (getSync().getState() == SyncEngine.esExit)
            {
                return;
            }

            if (nErrCode != RhoAppAdapter.ERR_NONE)
            {
                if (!getSync().isSearch())
                {
                    String strMessage = RhoAppAdapter.getMessageText("sync_failed_for") + "all.";

                    reportSyncStatus(strMessage, nErrCode, strError);
                }
            }

            lock (m_mxSyncNotifications)
            {
                SyncNotification pSN = getSyncNotifyBySrc(null);
                if (pSN != null)
                {
                    doFireSyncNotification(null, bFinish, nErrCode, strError, "", strServerError);
                }
            }
        }
Beispiel #4
0
        boolean downloadBlob(CAttrValue value)
        {
            String fName  = makeFileName(value);
            String url    = value.m_strValue;
            int    nQuest = url.lastIndexOf('?');

            if (nQuest > 0)
            {
                url += "&";
            }
            else
            {
                url += "?";
            }
            url += "client_id=" + getSync().getClientID();

            try{
                NetResponse resp = getNet().pullFile(url, fName, getSync(), null);
                if (!resp.isOK())
                {
                    getSync().stopSync();
                    m_nErrCode = RhoAppAdapter.getErrorFromResponse(resp);
                    return(false);
                }
            }catch (Exception exc)
            {
                m_nErrCode = RhoAppAdapter.getNetErrorCode(exc);
                throw exc;
            }

            value.m_strValue = CFilePath.getRelativePath(fName, CRhodesApp.getRhoRootPath());

            return(true);
        }
Beispiel #5
0
 public static void doSyncSourceByName(String strSrcName, boolean bShowStatus)
 {
     if (bShowStatus && (m_statusListener != null))
     {
         m_statusListener.createStatusPopup(RhoAppAdapter.getMessageText("syncronizing_data"));
     }
     getInstance().addQueueCommand(new SyncCommand(SyncThread.scSyncOne, strSrcName, (int)0, bShowStatus));
 }
Beispiel #6
0
        void checkShowStatus(SyncCommand oSyncCmd)
        {
            boolean bShowStatus = oSyncCmd.m_bShowStatus && !this.isNoThreadedMode();

            m_oSyncEngine.getNotify().enableReporting(bShowStatus);
            if (m_oSyncEngine.getNotify().isReportingEnabled())
            {
                m_statusListener.createStatusPopup(RhoAppAdapter.getMessageText("syncronizing_data"));
            }
        }
Beispiel #7
0
        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());
        }
Beispiel #8
0
        void syncAllSources(String strQueryParams)
        {
//	        boolean bError = false;

//	        int nStartSrc = getStartSource();
//	        if ( nStartSrc >= 0 )
//	            bError = !syncOneSource(nStartSrc);

            //TODO: do not stop on error source
            for (int i = 0; i < (int)m_sources.size() && isContinueSync(); i++)
            {
                /*bError = !*/ syncOneSource(i, strQueryParams);
            }

            if (!isSchemaChanged() && getState() != SyncEngine.esStop)
            {
                getNotify().fireSyncNotification(null, true, RhoAppAdapter.ERR_NONE, RhoAppAdapter.getMessageText("sync_completed"));
            }
        }
Beispiel #9
0
        public void fireBulkSyncNotification(boolean bFinish, String status, String partition, int nErrCode)
        {
            if (getSync().getState() == SyncEngine.esExit)
            {
                return;
            }

            if (nErrCode != RhoAppAdapter.ERR_NONE)
            {
                String strMessage = RhoAppAdapter.getMessageText("sync_failed_for") + "bulk.";
                reportSyncStatus(strMessage, nErrCode, "");
            }

            String strParams = "";

            strParams += "partition=" + partition;
            strParams += "&bulk_status=" + status;
            strParams += "&sync_type=bulk";

            doFireSyncNotification(null, bFinish, nErrCode, "", strParams, "");
        }
Beispiel #10
0
        public void fireSyncNotification(SyncSource src, boolean bFinish, int nErrCode, String strMessage)
        {
            if (getSync().getState() == SyncEngine.esExit)
            {
                return;
            }

            if (strMessage.length() > 0 || nErrCode != RhoAppAdapter.ERR_NONE)
            {
                if (!getSync().isSearch())
                {
                    if (src != null && (strMessage == null || strMessage.length() == 0))
                    {
                        strMessage = RhoAppAdapter.getMessageText("sync_failed_for") + src.getName() + ".";
                    }

                    reportSyncStatus(strMessage, nErrCode, src != null?src.m_strError:"");
                }
            }

            doFireSyncNotification(src, bFinish, nErrCode, "", "", "");
        }
Beispiel #11
0
        public void sync()
        {
            getNotify().reportSyncStatus(RhoAppAdapter.getMessageText("syncronizing") + getName() + "...", m_nErrCode, m_strError);

            TimeInterval startTime = TimeInterval.getCurrentTime();

            //m_bIsSearch = false;

            try{
                if (isTokenFromDB() && getToken() > 1)
                {
                    syncServerChanges();      //sync only server changes, which was paused before
                }
                else
                {
                    if (isEmptyToken())
                    {
                        processToken(1);
                    }

                    boolean bSyncedServer = syncClientChanges();
                    if (!bSyncedServer)
                    {
                        syncServerChanges();
                    }
                }
            }catch (Exception exc)
            {
                getSync().stopSync();
                throw exc;
            }finally{
                TimeInterval endTime = TimeInterval.getCurrentTime();
                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, getInsertedCount(), getDeletedCount(),
                                   endTime.minus(startTime).toULong(),
                                   m_bGetAtLeastOnePage?1:0, m_nRefreshTime, getID());
            }
        }
Beispiel #12
0
        void syncAllSources()
        {
            boolean bError = false;

            int nStartSrc = getStartSource();

            if (nStartSrc >= 0)
            {
                bError = !syncOneSource(nStartSrc);
            }

            //TODO: do not stop on error source
            for (int i = 0; i < (int)m_sources.size() && isContinueSync(); i++)
            {
                bError = !syncOneSource(i);
            }

            if (!bError && !isSchemaChanged())
            {
                getNotify().fireSyncNotification(null, true, RhoAppAdapter.ERR_NONE, RhoAppAdapter.getMessageText("sync_completed"));
            }
        }
Beispiel #13
0
        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("");
        }
Beispiel #14
0
        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);
        }
Beispiel #15
0
        public void doSyncSource(SourceID oSrcID, String strQueryParams)
        {
            SyncSource src = null;

            try
            {
                prepareSync(esSyncSource, oSrcID);

                if (isContinueSync())
                {
                    src = findSource(oSrcID);
                    if (src != null)
                    {
                        LOG.INFO("Started synchronization of the data source: " + src.getName());

                        src.m_strQueryParams = strQueryParams;
                        src.sync();

                        getNotify().fireSyncNotification(src, true, src.m_nErrCode, src.m_nErrCode == RhoAppAdapter.ERR_NONE ? RhoAppAdapter.getMessageText("sync_completed") : "");
                    }
                    else
                    {
                        //                    LOG.ERROR( "Sync one source : Unknown Source " + oSrcID.toString() );

                        src = new SyncSource(this, getUserDB());
                        //src.m_strError = "Unknown sync source.";
                        src.m_nErrCode = RhoAppAdapter.ERR_RUNTIME;

                        throw new Exception("Sync one source : Unknown Source " + oSrcID.toString());
                    }
                }
            } catch (Exception exc) {
                LOG.ERROR("Sync source " + oSrcID.toString() + " failed.", exc);

                if (src != null && src.m_nErrCode == RhoAppAdapter.ERR_NONE)
                {
                    src.m_nErrCode = RhoAppAdapter.ERR_RUNTIME;
                }

                getNotify().fireSyncNotification(src, true, src.m_nErrCode, "");
            }

            getNotify().cleanCreateObjectErrors();
            if (getState() != esExit)
            {
                setState(esNone);
            }
        }
Beispiel #16
0
        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, "", "");
            }
        }
Beispiel #17
0
        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, "");
            }
        }
Beispiel #18
0
        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();
        }
Beispiel #19
0
        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();
            }
        }
Beispiel #20
0
            void callNotify(NetResponse resp, int nError)
            {
                if (m_bInternal)
                {
                    return;
                }

                m_strResBody  = "rho_callback=1";
                m_strResBody += "&status=";
                if (nError > 0)
                {
                    m_strResBody += "error&error_code=" + nError;
                }
                else
                {
                    if (resp.isOK())
                    {
                        m_strResBody += "ok";
                    }
                    else
                    {
                        m_strResBody += "error&error_code=";
                        m_strResBody += RhoAppAdapter.getErrorFromResponse(resp);
                        //if ( resp.isResponseRecieved())
                        m_strResBody += "&http_error=" + resp.getRespCode();
                    }

                    String cookies = resp.getCookies();
                    if (cookies.length() > 0)
                    {
                        m_strResBody += "&cookies=" + URI.urlEncode(cookies);
                    }

                    String strHeaders = makeHeadersString();
                    if (strHeaders.length() > 0)
                    {
                        m_strResBody += "&" + strHeaders;
                    }

                    m_strResBody += "&" + RHODESAPP().addCallbackObject(m_valBody, "body");
                }

                if (m_strCallbackParams.length() > 0)
                {
                    m_strResBody += "&" + m_strCallbackParams;
                }

                if (m_strCallback.length() > 0)
                {
                    try{
                        String      strFullUrl = m_pNetRequest.resolveUrl(m_strCallback);
                        NetResponse resp1      = m_pNetRequest.pushData(strFullUrl, m_strResBody, null);
                        if (!resp1.isOK())
                        {
                            LOG.ERROR("AsyncHttp notification failed. Code: " + resp1.getRespCode() + "; Error body: " + resp1.getCharData());
                        }
                    }catch (Exception exc)
                    {
                        LOG.ERROR("Async http callback failed.", exc);
                    }
                }
            }