Example usage for org.json JSONObject getLong

List of usage examples for org.json JSONObject getLong

Introduction

In this page you can find the example usage for org.json JSONObject getLong.

Prototype

public long getLong(String key) throws JSONException 

Source Link

Document

Get the long value associated with a key.

Usage

From source file:com.hichinaschool.flashcards.libanki.Note.java

public Note(Collection col, JSONObject model, long id) {
    mCol = col;//from   www. java  2s .co m
    if (id != 0) {
        mId = id;
        load();
    } else {
        mId = Utils.timestampID(mCol.getDb(), "notes");
        mGuId = Utils.guid64();
        mModel = model;
        try {
            mMid = model.getLong("id");
            mTags = new ArrayList<String>();
            mFields = new String[model.getJSONArray("flds").length()];
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < mFields.length; i++) {
            mFields[i] = "";
        }
        mData = "";
        mFMap = mCol.getModels().fieldMap(mModel);
        mScm = mCol.getScm();
    }
}

From source file:com.acrutiapps.browser.tasks.HistoryBookmarksImportTask.java

private String readAsJSON(File file) {
    List<ContentValues> insertValues = null;

    try {/*w ww.  jav  a  2 s  . c o  m*/
        insertValues = new ArrayList<ContentValues>();

        publishProgress(1, 0, 0);

        FileInputStream fis = new FileInputStream(file);

        StringBuilder sb = new StringBuilder();
        String line;

        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }

        JSONObject data = new JSONObject(sb.toString());

        Map<Long, Folder> folders = new HashMap<Long, Folder>();

        if (data.has("folders")) {
            JSONArray foldersArray = data.getJSONArray("folders");

            int progress = 0;
            int total = foldersArray.length();

            for (int i = 0; i < foldersArray.length(); i++) {

                publishProgress(3, progress, total);

                JSONObject folder = foldersArray.getJSONObject(i);

                long id = folder.getLong("id");
                long parentId = folder.getLong("parentId");
                String title = URLDecoder.decode(folder.getString("title"), "UTF-8");

                ContentValues values = new ContentValues();
                values.put(BookmarksProvider.Columns.TITLE, title);
                values.put(BookmarksProvider.Columns.BOOKMARK, 0);
                values.put(BookmarksProvider.Columns.IS_FOLDER, 1);
                values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, -1);

                Uri insertionUri = mContext.getContentResolver().insert(BookmarksProvider.BOOKMARKS_URI,
                        values);
                String insertionString = insertionUri.toString();

                // Get the new id for the current folder.
                long insertionId = -1;
                try {
                    insertionId = Long
                            .parseLong(insertionString.substring(insertionString.lastIndexOf('/') + 1));
                } catch (NumberFormatException e) {
                    insertionId = -1;
                }

                // Keep a relation between the id of the folder in the export file, its parent id (in the export file), and its new id.
                folders.put(id, new Folder(insertionId, parentId));

                progress++;
            }

            publishProgress(4, 0, 0);

            // Correct folders parent ids.
            if (!folders.isEmpty()) {
                for (Folder folder : folders.values()) {
                    // For each folder previously inserted, check if it had a parent folder in the export file.
                    long oldParentId = folder.getOldParentId();

                    if (oldParentId != -1) {
                        // Get the parent folder by its old Id, key of folders map.
                        Folder parentFolder = folders.get(oldParentId);
                        if (parentFolder != null) {

                            ContentValues values = new ContentValues();
                            values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId());

                            String whereClause = BookmarksProvider.Columns._ID + " = " + folder.getNewId();

                            mContext.getContentResolver().update(BookmarksProvider.BOOKMARKS_URI, values,
                                    whereClause, null);
                        }
                    }
                }
            }
        }

        if (data.has("bookmarks")) {
            JSONArray bookmarksArray = data.getJSONArray("bookmarks");

            int progress = 0;
            int total = bookmarksArray.length();

            for (int i = 0; i < bookmarksArray.length(); i++) {

                publishProgress(5, progress, total);

                JSONObject bookmark = bookmarksArray.getJSONObject(i);

                long folderId = bookmark.getLong("folderId");
                Folder parentFolder = null;
                if (folderId != -1) {
                    parentFolder = folders.get(folderId);
                }

                String title = URLDecoder.decode(bookmark.getString("title"), "UTF-8");
                String url = URLDecoder.decode(bookmark.getString("url"), "UTF-8");

                ContentValues values = createContentValues(title, url, bookmark.getInt("visits"),
                        bookmark.getLong("visitedDate"), bookmark.getLong("creationDate"), 1);

                if (parentFolder != null) {
                    values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId());
                }

                insertValues.add(values);

                progress++;
            }
        }

        if (data.has("history")) {
            JSONArray historyArray = data.getJSONArray("history");

            int progress = 0;
            int total = historyArray.length();

            for (int i = 0; i < historyArray.length(); i++) {

                publishProgress(6, progress, total);

                JSONObject history = historyArray.getJSONObject(i);

                String title = URLDecoder.decode(history.getString("title"), "UTF-8");
                String url = URLDecoder.decode(history.getString("url"), "UTF-8");

                ContentValues values = createContentValues(title, url, history.getInt("visits"),
                        history.getLong("visitedDate"), 0, 0);

                insertValues.add(values);

                progress++;
            }
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (JSONException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return e.getMessage();
    }

    if (insertValues != null) {
        publishProgress(7, 0, 0);
        mContext.getContentResolver().bulkInsert(BookmarksProvider.BOOKMARKS_URI,
                insertValues.toArray(new ContentValues[insertValues.size()]));
    }

    return null;
}

From source file:com.hichinaschool.flashcards.anki.servicelayer.NoteService.java

/**
 * Creates an empty Note from given Model
 * /* ww w .j av  a  2s . c  om*/
 * @param model the model in JSOBObject format
 * @return a new note instance
 */
public static MultimediaEditableNote createEmptyNote(JSONObject model) {
    try {
        JSONArray fieldsArray = model.getJSONArray("flds");
        int numOfFields = fieldsArray.length();
        if (numOfFields > 0) {
            MultimediaEditableNote note = new MultimediaEditableNote();
            note.setNumFields(numOfFields);

            for (int i = 0; i < numOfFields; i++) {
                JSONObject fieldObject = fieldsArray.getJSONObject(i);
                TextField uiTextField = new TextField();
                uiTextField.setName(fieldObject.getString("name"));
                uiTextField.setText(fieldObject.getString("name"));
                note.setField(i, uiTextField);
            }
            note.setModelId(model.getLong("id"));
            return note;
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) {
    Object param = null;// w  ww .  j a v  a  2  s  .c o  m
    Throwable ex = null;
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        if (m.getName().equals(name)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            if (paramTypes.length == 1 && jo.has(key)) {
                Class<?> tparam = paramTypes[0];
                boolean allowNull = false;
                try {
                    if (jo.isNull(key)) {
                        // do nothing because param is already null : lets us not null on other types
                    } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) {
                        param = new Long(jo.getLong(key));
                    } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) {
                        param = new Double(jo.getDouble(key));
                    } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) {
                        param = new Integer(jo.getInt(key));
                    } else if (String.class.isAssignableFrom(tparam)) {
                        param = jo.getString(key);
                    } else if (Enum.class.isAssignableFrom(tparam)) {
                        param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key));
                    } else if (Boolean.class.isAssignableFrom(tparam)) {
                        param = new Boolean(jo.getBoolean(key));
                    } else if (jo.isNull(key)) {
                        param = null;
                        allowNull = true;
                    } else if (Collection.class.isAssignableFrom(tparam)) {

                        if (m.getGenericParameterTypes().length > 0) {
                            Type t = m.getGenericParameterTypes()[0];
                            if (t instanceof ParameterizedType) {
                                ParameterizedType tv = (ParameterizedType) t;
                                if (tv.getActualTypeArguments().length > 0
                                        && tv.getActualTypeArguments()[0] == String.class) {

                                    List<String> ls = new ArrayList<String>();
                                    JSONArray ja = jo.optJSONArray(key);
                                    if (ja != null) {
                                        for (int j = 0; j < ja.length(); j++) {
                                            ls.add(ja.getString(j));
                                        }
                                    }
                                    param = ls;
                                } else if (tv.getActualTypeArguments().length == 1) {
                                    ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0];
                                    Class itemClass = (Class) type.getRawType();
                                    if (itemClass == Map.class && type.getActualTypeArguments().length == 2
                                            && type.getActualTypeArguments()[0] == String.class
                                            && type.getActualTypeArguments()[1] == Object.class) {

                                        List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

                                        JSONArray ja = jo.optJSONArray(key);
                                        if (ja != null) {
                                            for (int j = 0; j < ja.length(); j++) {
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                JSONObject mo = ja.getJSONObject(j);
                                                Iterator<String> keys = mo.keys();
                                                while (keys.hasNext()) {
                                                    String okey = keys.next();
                                                    Object ovalue = null;
                                                    // make sure we don't get JSONObject$Null
                                                    if (!mo.isNull(okey)) {
                                                        ovalue = mo.get(okey);
                                                    }
                                                    map.put(okey, ovalue);
                                                }
                                                ls.add(map);
                                            }
                                        }
                                        param = ls;
                                    } else {
                                        getLogger().warning(
                                                "Don't know how to handle Collection of type : " + itemClass);
                                    }

                                } else {
                                    getLogger().warning("Don't know how to handle Collection of type : "
                                            + tv.getActualTypeArguments()[0]);
                                }
                            }
                        }
                    } else {
                        getLogger().warning(
                                "Unable to serialize " + key + " :  Don't know how to handle " + tparam);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (param != null || allowNull) {

                    try {

                        if (m != null) {
                            Object[] args = { param };
                            m.invoke(targetObject, args);
                            ex = null;
                            break;
                        }
                    } catch (SecurityException e) {
                        ex = e;
                    } catch (IllegalArgumentException e) {
                        ex = e;
                    } catch (IllegalAccessException e) {
                        ex = e;
                    } catch (InvocationTargetException e) {
                        ex = e;
                    }
                }
            }
        }
    }
    if (ex != null) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException(ex);
        }
    }
}

From source file:com.pk.wallpapermanager.PkWallpaperManager.java

/**
 * Loads wallpapers stored on your cloud repository.
 * May throw an exception so watch out and handle it carefully.
 * /* w  ww .  ja  va  2s.c om*/
 * Note: Do NOT call this from the main UI thread of it will force close!
 *        Call this from a separate thread instead.
 * 
 * @throws ClientProtocolException
 * @throws IOException
 * @throws JSONException
 */
public void fetchCloudWallpapers() throws ClientProtocolException, IOException, JSONException {
    // Cancel if not enabled
    if (!mSettings.getWebEnabled()) {
        if (debugEnabled)
            Log.d(LOG_TAG, "Cloud wallpapers aren't enabled in settings! Canceling task...");

        return;
    }

    // Retrieve Metadata URL or build default (if null)
    String metadataURL = mSettings.getMetadataURL();
    if (metadataURL == null) {
        metadataURL = mSettings.getStorageURL() + "/" + mSettings.getWallpaperPath() + "/"
                + DEFAULT_METADATA_FILE_NAME;
    }

    // Make a request to the Metadata URL and wait for the JSON response
    HttpGet get = new HttpGet(metadataURL);

    if (debugEnabled)
        Log.d(LOG_TAG, "Sending wallpaper info data request to " + metadataURL + "...");

    String response = "";
    try {
        response = httpClient.execute(get, new BasicResponseHandler());

        if (debugEnabled)
            Log.d(LOG_TAG, "Response: " + response);
    } catch (Exception e) {
        if (debugEnabled) {
            Log.d(LOG_TAG,
                    "Unable to make a request to metadata URL! Are you sure you specified your metadata URL in settings correctly?");
        }
    }

    // Loop through all listeners notifying them
    for (CloudWallpaperListener mListener : mCloudWallpaperListeners) {
        mListener.onCloudWallpapersLoading();
    }

    // Convert response into JSONArray and loop through it
    JSONArray jsonResponse = new JSONArray(response);
    int responseLength = jsonResponse.length();
    mCloudWallpapers.clear();
    Wallpaper mWall = null;

    for (int index = 0; index < responseLength; index++) {
        JSONObject jsonWallpaper = jsonResponse.getJSONObject(index);

        mWall = new Wallpaper();
        mWall.setPathURL(mSettings.getStorageURL() + "/" + mSettings.getWallpaperPath() + "/");
        mWall.setRelativeFullURL(jsonWallpaper.getString(FULL_SRC));
        mWall.setRelativeThumbURL(jsonWallpaper.getString(THUMB_SRC));
        mWall.setFullUri(Uri.parse(mWall.getFullURL()));
        mWall.setThumbUri(Uri.parse(mWall.getThumbURL()));
        mWall.setTitle(jsonWallpaper.getString(TITLE));
        mWall.setByLine(jsonWallpaper.getString(BYLINE));
        mWall.setFileSize(jsonWallpaper.getLong(FILE_SIZE));
        mWall.setLocal(false);
        mCloudWallpapers.add(mWall);

        if (debugEnabled)
            Log.d(LOG_TAG, mWall.toString());

        mWall = null;
    }

    if (debugEnabled)
        Log.d(LOG_TAG, "Finished loading " + mCloudWallpapers.size() + " cloud wallpapers!");

    // Loop through all listeners notifying them
    for (CloudWallpaperListener mListener : mCloudWallpaperListeners) {
        mListener.onCloudWallpapersLoaded();
    }
}

From source file:com.hichinaschool.flashcards.libanki.Stats.java

/**
 * Tools ***********************************************************************************************
 *///from w  ww .  ja v  a  2s .c  o  m

private String _limit() {
    if (mWholeCollection) {
        ArrayList<Long> ids = new ArrayList<Long>();
        for (JSONObject d : mCol.getDecks().all()) {
            try {
                ids.add(d.getLong("id"));
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
        return Utils.ids2str(Utils.arrayList2array(ids));
    } else {
        return mCol.getSched()._deckLimit();
    }
}

From source file:net.geco.model.iojson.PersistentStore.java

public void importRunnersData(JSONStore store, Registry registry, Factory factory) throws JSONException {
    final int I_RUNNER = 0;
    final int I_ECARD = 1;
    final int I_RESULT = 2;
    JSONArray runnersData = store.getJSONArray(K.RUNNERS_DATA);
    for (int i = 0; i < runnersData.length(); i++) {
        JSONArray runnerTuple = runnersData.getJSONArray(i);

        JSONObject c = runnerTuple.getJSONObject(I_RUNNER);
        Runner runner = factory.createRunner();
        runner.setStartId(c.getInt(K.START_ID));
        runner.setFirstname(c.getString(K.FIRST));
        runner.setLastname(c.getString(K.LAST));
        runner.setEcard(c.getString(K.ECARD));
        runner.setClub(store.retrieve(c.getInt(K.CLUB), Club.class));
        runner.setCategory(store.retrieve(c.getInt(K.CAT), Category.class));
        runner.setCourse(store.retrieve(c.getInt(K.COURSE), Course.class));
        runner.setRegisteredStarttime(new Date(c.getLong(K.START)));
        runner.setArchiveId((Integer) c.opt(K.ARK));
        runner.setRentedEcard(c.optBoolean(K.RENT));
        runner.setNC(c.optBoolean(K.NC));
        registry.addRunner(runner);//from  www.j a  va 2s . c  om

        JSONObject d = runnerTuple.getJSONObject(I_ECARD);
        RunnerRaceData raceData = factory.createRunnerRaceData();
        raceData.setStarttime(new Date(d.getLong(K.START)));
        raceData.setFinishtime(new Date(d.getLong(K.FINISH)));
        raceData.setControltime(new Date(d.getLong(K.CHECK)));
        raceData.setReadtime(new Date(d.getLong(K.READ)));
        JSONArray p = d.getJSONArray(K.PUNCHES);
        Punch[] punches = new Punch[p.length() / 2];
        for (int j = 0; j < punches.length; j++) {
            punches[j] = factory.createPunch();
            punches[j].setCode(p.getInt(2 * j));
            punches[j].setTime(new Date(p.getLong(2 * j + 1)));
        }
        raceData.setPunches(punches);
        raceData.setRunner(runner);
        registry.addRunnerData(raceData);

        JSONObject r = runnerTuple.getJSONObject(I_RESULT);
        TraceData traceData = factory.createTraceData();
        traceData.setNbMPs(r.getInt(K.MPS));
        traceData.setNbExtraneous(r.optInt(K.EXTRA)); // MIGR v2.x -> v2.3
        JSONArray t = r.getJSONArray(K.TRACE);
        Trace[] trace = new Trace[t.length() / 2];
        for (int j = 0; j < trace.length; j++) {
            trace[j] = factory.createTrace(t.getString(2 * j), new Date(t.getLong(2 * j + 1)));
        }
        if (r.has(K.SECTION_DATA)) {
            SectionTraceData sectionData = (SectionTraceData) traceData;
            JSONArray sections = r.getJSONArray(K.SECTION_DATA);
            for (int j = 0; j < sections.length(); j++) {
                JSONArray section = sections.getJSONArray(j);
                sectionData.putSectionAt(store.retrieve(section.getInt(0), Section.class), section.getInt(1));
            }
        }
        JSONArray neut = r.getJSONArray(K.NEUTRALIZED);
        for (int j = 0; j < neut.length(); j++) {
            trace[neut.getInt(j)].setNeutralized(true);
        }
        traceData.setTrace(trace);
        raceData.setTraceData(traceData);

        RunnerResult result = factory.createRunnerResult();
        result.setRaceTime(r.optLong(K.RACE_TIME, TimeManager.NO_TIME_l)); // MIGR v2.x -> v2.2
        result.setResultTime(r.getLong(K.TIME));
        result.setStatus(Status.valueOf(r.getString(K.STATUS)));
        result.setTimePenalty(r.getLong(K.PENALTY));
        result.setManualTimePenalty(r.optLong(K.MANUAL_PENALTY, 0)); // MIGR v2.x -> v2.3
        raceData.setResult(result);
    }
}

From source file:com.nextgis.firereporter.ScanexSubscriptionItem.java

public ScanexSubscriptionItem(GetFiresService c, JSONObject object) {
    Prepare(c);/*  w  w w .j  a  v a2  s. co  m*/
    try {
        this.nID = object.getLong("id");
        this.sTitle = object.getString("title");
        this.sLayerName = object.getString("layer_name");
        this.sWKT = object.getString("wkt");
        this.bSMSEnable = object.getBoolean("sms_enabled");

        JSONArray jsonArray = object.getJSONArray("items");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            ScanexNotificationItem Item = new ScanexNotificationItem(c, jsonObject);
            if (Item.GetId() != -1) {
                mmoItems.put(Item.GetId(), Item);
            }
        }

    } catch (JSONException e) {
        SendError(e.getLocalizedMessage());
    }
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

public Object[] sync(Connection con) {
    mSyncMsg = "";
    // if the deck has any pending changes, flush them first and bump mod time
    mCol.save();/*from   w w  w. ja  v  a 2s  . c o  m*/
    // step 1: login & metadata
    HttpResponse ret = mServer.meta();
    if (ret == null) {
        return null;
    }
    int returntype = ret.getStatusLine().getStatusCode();
    if (returntype == 403) {
        return new Object[] { "badAuth" };
    } else if (returntype != 200) {
        return new Object[] { "error", returntype, ret.getStatusLine().getReasonPhrase() };
    }
    try {
        mCol.getDb().getDatabase().beginTransaction();
        try {
            // Log.i(AnkiDroidApp.TAG, "Sync: getting meta data from server");
            JSONObject rMeta = new JSONObject(mServer.stream2String(ret.getEntity().getContent()));
            long rscm = rMeta.getLong("scm");
            int rts = rMeta.getInt("ts");
            mRMod = rMeta.getLong("mod");
            mMaxUsn = rMeta.getInt("usn");
            mMediaUsn = rMeta.getInt("musn");
            mSyncMsg = rMeta.getString("msg");
            // skip uname, AnkiDroid already stores and shows it
            if (!rMeta.getBoolean("cont")) {
                // Don't add syncMsg; it can be fetched by UI code using the accessor
                return new Object[] { "serverAbort" };
            } else {
                // don't abort, but ui should show messages after sync finishes
                // and require confirmation if it's non-empty
            }
            // Log.i(AnkiDroidApp.TAG, "Sync: building local meta data");
            JSONObject lMeta = meta();
            mLMod = lMeta.getLong("mod");
            mMinUsn = lMeta.getInt("usn");
            long lscm = lMeta.getLong("scm");
            int lts = lMeta.getInt("ts");

            long diff = Math.abs(rts - lts);
            if (diff > 300) {
                return new Object[] { "clockOff", diff };
            }
            if (mLMod == mRMod) {
                // Log.i(AnkiDroidApp.TAG, "Sync: no changes - returning");
                return new Object[] { "noChanges" };
            } else if (lscm != rscm) {
                // Log.i(AnkiDroidApp.TAG, "Sync: full sync necessary - returning");
                return new Object[] { "fullSync" };
            }
            mLNewer = mLMod > mRMod;
            // step 2: deletions
            publishProgress(con, R.string.sync_deletions_message);

            // Log.i(AnkiDroidApp.TAG, "Sync: collection removed data");
            JSONObject lrem = removed();
            JSONObject o = new JSONObject();
            o.put("minUsn", mMinUsn);
            o.put("lnewer", mLNewer);
            o.put("graves", lrem);

            // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving removed data");
            JSONObject rrem = mServer.start(o);
            if (rrem == null) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return null;
            }
            if (rrem.has("errorType")) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return new Object[] { "error", rrem.get("errorType"), rrem.get("errorReason") };
            }

            // Log.i(AnkiDroidApp.TAG, "Sync: applying removed data");
            remove(rrem);
            // ... and small objects
            publishProgress(con, R.string.sync_small_objects_message);

            // Log.i(AnkiDroidApp.TAG, "Sync: collection small changes");
            JSONObject lchg = changes();
            JSONObject sch = new JSONObject();
            sch.put("changes", lchg);

            // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving small changes");
            JSONObject rchg = mServer.applyChanges(sch);
            if (rchg == null) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return null;
            }
            if (rchg.has("errorType")) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return new Object[] { "error", rchg.get("errorType"), rchg.get("errorReason") };
            }

            // Log.i(AnkiDroidApp.TAG, "Sync: merging small changes");
            mergeChanges(lchg, rchg);
            // step 3: stream large tables from server
            publishProgress(con, R.string.sync_download_chunk);
            while (true) {
                // Log.i(AnkiDroidApp.TAG, "Sync: downloading chunked data");
                JSONObject chunk = mServer.chunk();
                if (chunk == null) {
                    // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                    return null;
                }
                if (chunk.has("errorType")) {
                    // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                    return new Object[] { "error", chunk.get("errorType"), chunk.get("errorReason") };
                }
                // Log.i(AnkiDroidApp.TAG, "Sync: applying chunked data");
                applyChunk(chunk);
                if (chunk.getBoolean("done")) {
                    break;
                }
            }
            // step 4: stream to server
            publishProgress(con, R.string.sync_upload_chunk);
            while (true) {
                // Log.i(AnkiDroidApp.TAG, "Sync: collecting chunked data");
                JSONObject chunk = chunk();
                JSONObject sech = new JSONObject();
                sech.put("chunk", chunk);
                // Log.i(AnkiDroidApp.TAG, "Sync: sending chunked data");
                mServer.applyChunk(sech);
                if (chunk.getBoolean("done")) {
                    break;
                }
            }
            // step 5: sanity check during beta testing
            JSONObject c = sanityCheck();
            JSONObject sanity = mServer.sanityCheck2(c);
            if (sanity == null || !sanity.optString("status", "bad").equals("ok")) {
                return new Object[] { "sanityCheckError", null };
            }
            // finalize
            publishProgress(con, R.string.sync_finish_message);
            // Log.i(AnkiDroidApp.TAG, "Sync: sending finish command");
            long mod = mServer.finish();
            if (mod == 0) {
                return new Object[] { "finishError" };
            }
            // Log.i(AnkiDroidApp.TAG, "Sync: finishing");
            finish(mod);

            publishProgress(con, R.string.sync_writing_db);
            mCol.getDb().getDatabase().setTransactionSuccessful();
        } finally {
            mCol.getDb().getDatabase().endTransaction();
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (OutOfMemoryError e) {
        AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync");
        return new Object[] { "OutOfMemoryError" };
    } catch (IOException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync");
        return new Object[] { "IOException" };
    }
    return new Object[] { "success" };
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

public void mergeChanges(JSONObject lchg, JSONObject rchg) {
    try {/*  w w w  . j a v  a  2s  .c  o m*/
        // then the other objects
        mergeModels(rchg.getJSONArray("models"));
        mergeDecks(rchg.getJSONArray("decks"));
        mergeTags(rchg.getJSONArray("tags"));
        if (rchg.has("conf")) {
            mergeConf(rchg.getJSONObject("conf"));
        }
        // this was left out of earlier betas
        if (rchg.has("crt")) {
            mCol.setCrt(rchg.getLong("crt"));
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    prepareToChunk();
}