List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:com.hichinaschool.flashcards.libanki.Models.java
/** * Change a model/*from w ww . ja v a 2 s . c o m*/ * @param m The model to change. * @param nids The list of notes that the change applies to. * @param newModel For replacing the old model with another one. Should be self if the model is not changing * @param fmap Field map for switching fields. This is ord->ord and there should not be duplicate targets * @param cmap Field map for switching fields. This is ord->ord and there should not be duplicate targets */ public void change(JSONObject m, long[] nids, JSONObject newModel, Map<Integer, Integer> fmap, Map<Integer, Integer> cmap) { mCol.modSchema(); try { assert (newModel.getLong("id") == m.getLong("id")) || (fmap != null && cmap != null); } catch (JSONException e) { throw new RuntimeException(e); } if (fmap != null) { _changeNotes(nids, newModel, fmap); } if (cmap != null) { _changeCards(nids, m, newModel, cmap); } mCol.genCards(nids); }
From source file:com.hichinaschool.flashcards.libanki.Models.java
private void _changeNotes(long[] nids, JSONObject newModel, Map<Integer, Integer> map) { List<Object[]> d = new ArrayList<Object[]>(); int nfields;/*from ww w . j av a 2 s .co m*/ long mid; try { nfields = newModel.getJSONArray("flds").length(); mid = newModel.getLong("id"); } catch (JSONException e) { throw new RuntimeException(e); } Cursor cur = null; try { cur = mCol.getDb().getDatabase() .rawQuery("select id, flds from notes where id in ".concat(Utils.ids2str(nids)), null); while (cur.moveToNext()) { long nid = cur.getLong(0); String[] flds = Utils.splitFields(cur.getString(1)); Map<Integer, String> newflds = new HashMap<Integer, String>(); for (Integer old : map.keySet()) { newflds.put(map.get(old), flds[old]); } List<String> flds2 = new ArrayList<String>(); for (int c = 0; c < nfields; ++c) { if (newflds.containsKey(c)) { flds2.add(newflds.get(c)); } else { flds2.add(""); } } String joinedFlds = Utils.joinFields(flds2.toArray(new String[] {})); d.add(new Object[] { joinedFlds, mid, Utils.intNow(), mCol.usn(), nid }); } } finally { if (cur != null) { cur.close(); } } mCol.getDb().executeMany("update notes set flds=?,mid=?,mod=?,usn=? where id = ?", d); mCol.updateFieldCache(nids); }
From source file:com.hichinaschool.flashcards.libanki.Models.java
private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) { try {//from ww w . j ava2 s . c o m ArrayList<String> a = new ArrayList<String>(); ArrayList<String> b = new ArrayList<String>(); for (String f : flds) { a.add("ankiflag"); b.add(""); } Object[] data; data = new Object[] { 1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(a.toArray(new String[a.size()])) }; String full = mCol._renderQA(data).get("q"); data = new Object[] { 1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(b.toArray(new String[b.size()])) }; String empty = mCol._renderQA(data).get("q"); // if full and empty are the same, the template is invalid and there is no way to satisfy it if (full.equals(empty)) { return new Object[] { "none", new JSONArray(), new JSONArray() }; } String type = "all"; JSONArray req = new JSONArray(); ArrayList<String> tmp = new ArrayList<String>(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(a); tmp.set(i, ""); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if no field content appeared, field is required if (!mCol._renderQA(data, new ArrayList<String>()).get("q").contains("ankiflag")) { req.put(i); } } if (req.length() > 0) { return new Object[] { type, req }; } // if there are no required fields, switch to any mode type = "any"; req = new JSONArray(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(b); tmp.set(i, "1"); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); // if not the same as empty, this field can make the card non-blank if (!mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } return new Object[] { type, req }; } catch (JSONException e) { throw new RuntimeException(e); } }
From source file:com.hichinaschool.flashcards.libanki.Models.java
public HashMap<Long, HashMap<Integer, String>> getTemplateNames() { HashMap<Long, HashMap<Integer, String>> result = new HashMap<Long, HashMap<Integer, String>>(); for (JSONObject m : mModels.values()) { JSONArray templates;/*from ww w . j ava 2 s . c om*/ try { templates = m.getJSONArray("tmpls"); HashMap<Integer, String> names = new HashMap<Integer, String>(); for (int i = 0; i < templates.length(); i++) { JSONObject t = templates.getJSONObject(i); names.put(t.getInt("ord"), t.getString("name")); } result.put(m.getLong("id"), names); } catch (JSONException e) { throw new RuntimeException(e); } } return result; }
From source file:org.transdroid.daemon.DLinkRouterBT.DLinkRouterBTAdapter.java
private ArrayList<Torrent> parseJsonRetrieveTorrents(JSONObject response) throws JSONException { // Parse response ArrayList<Torrent> torrents = new ArrayList<Torrent>(); JSONArray rarray = response.getJSONArray(JSON_TORRENTS); for (int i = 0; i < rarray.length(); i++) { JSONObject tor = rarray.getJSONObject(i); // Add the parsed torrent to the list TorrentStatus status;//from w w w . jav a2 s . co m if (tor.getInt(BT_STOPPED) == 1) { status = TorrentStatus.Paused; } else { status = convertStatus(tor.getString(BT_STATE)); } int eta = (int) ((tor.getLong(BT_SIZE) - tor.getLong(BT_DONE)) / (tor.getInt(BT_DOWNLOAD_RATE) + 1)); if (0 > eta) { eta = -1; } // @formatter:off Torrent new_t = new Torrent(i, tor.getString(BT_HASH), tor.getString(BT_CAPTION), status, null, // Not supported? tor.getInt(BT_DOWNLOAD_RATE), tor.getInt(BT_UPLOAD_RATE), tor.getInt(BT_PEERS_CONNECTED), tor.getInt(BT_PEERS_TOTAL), tor.getInt(BT_SEEDS_CONNECTED), tor.getInt(BT_SEEDS_TOTAL), eta, tor.getLong(BT_DONE), tor.getLong(BT_PAYLOAD_UPLOAD), tor.getLong(BT_SIZE), tor.getLong(BT_DONE) / (float) tor.getLong(BT_SIZE), Float.parseFloat(tor.getString(BT_COPYS)), null, null, null, null, settings.getType()); // @formatter:on torrents.add(new_t); } // Return the list return torrents; }
From source file:org.transdroid.daemon.DLinkRouterBT.DLinkRouterBTAdapter.java
private ArrayList<TorrentFile> parseJsonFileList(JSONObject response, String hash) throws JSONException { // Parse response ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>(); JSONObject jobj = response.getJSONObject(JSON_TORRENTS); if (jobj != null) { JSONArray files = jobj.getJSONArray(hash); // "Hash id" for (int i = 0; i < files.length(); i++) { JSONObject file = files.getJSONObject(i); // @formatter:off torrentfiles.add(new TorrentFile(String.valueOf(i), file.getString(BT_FILE_NAME), file.getString(BT_FILE_NAME), null, // Not supported? file.getLong(BT_FILE_SIZE), file.getLong(BT_FILE_DONE), convertTransmissionPriority(file.getInt(BT_FILE_PRIORITY)))); // @formatter:on }//www . ja v a 2s .c o m } // Return the list return torrentfiles; }
From source file:com.pseudosudostudios.jdd.utils.ScoreSaves.java
/** * Returns an Entry from the JSONObject//from ww w. j a va 2 s .com */ private static Entry makeEntry(JSONObject j) { try { return new Entry(j.getString(levelKey), j.getInt(moveKey), j.getLong(timeKey), j.getInt(colorsKey), j.getString(dateKey)); } catch (JSONException e) { return null; } }
From source file:org.archive.crawler.reporting.StatisticsTracker.java
@SuppressWarnings("unchecked") public void start() { isRunning = true;/*from w w w . j a v a2 s. c om*/ boolean isRecover = (recoveryCheckpoint != null); try { this.processedSeedsRecords = bdb.getObjectCache("processedSeedsRecords", isRecover, SeedRecord.class); this.hostsDistributionTop = new TopNSet(getLiveHostReportSize()); this.hostsBytesTop = new TopNSet(getLiveHostReportSize()); this.hostsLastFinishedTop = new TopNSet(getLiveHostReportSize()); if (isRecover) { JSONObject json = recoveryCheckpoint.loadJson(beanName); crawlStartTime = json.getLong("crawlStartTime"); crawlEndTime = json.getLong("crawlEndTime"); crawlTotalPausedTime = json.getLong("crawlTotalPausedTime"); crawlPauseStarted = json.getLong("crawlPauseStarted"); tallyCurrentPause(); JSONUtils.putAllLongs(hostsDistributionTop.getTopSet(), json.getJSONObject("hostsDistributionTop")); hostsDistributionTop.updateBounds(); JSONUtils.putAllLongs(hostsBytesTop.getTopSet(), json.getJSONObject("hostsBytesTop")); hostsBytesTop.updateBounds(); JSONUtils.putAllLongs(hostsLastFinishedTop.getTopSet(), json.getJSONObject("hostsLastFinishedTop")); hostsLastFinishedTop.updateBounds(); JSONUtils.putAllAtomicLongs(mimeTypeDistribution, json.getJSONObject("mimeTypeDistribution")); JSONUtils.putAllAtomicLongs(mimeTypeBytes, json.getJSONObject("mimeTypeBytes")); JSONUtils.putAllAtomicLongs(statusCodeDistribution, json.getJSONObject("statusCodeDistribution")); JSONObject shd = json.getJSONObject("sourceHostDistribution"); Iterator<String> keyIter = shd.keys(); for (; keyIter.hasNext();) { String source = keyIter.next(); ConcurrentHashMap<String, AtomicLong> hostUriCount = new ConcurrentHashMap<String, AtomicLong>(); JSONUtils.putAllAtomicLongs(hostUriCount, shd.getJSONObject(source)); sourceHostDistribution.put(source, hostUriCount); } JSONUtils.putAllLongs(crawledBytes, json.getJSONObject("crawledBytes")); } } catch (DatabaseException e) { throw new IllegalStateException(e); } catch (JSONException e) { throw new IllegalStateException(e); } // Log the legend this.controller.logProgressStatistics(progressStatisticsLegend()); executor.scheduleAtFixedRate(this, 0, getIntervalSeconds(), TimeUnit.SECONDS); }
From source file:com.ichi2.anki.dialogs.CustomStudyDialog.java
/** * Create a custom study session/*from ww w. jav a 2s . co m*/ * @param delays delay options for scheduling algorithm * @param terms search terms * @param resched whether to reschedule the cards based on the answers given (or ignore them if false) */ private void createCustomStudySession(JSONArray delays, Object[] terms, Boolean resched) { JSONObject dyn; final AnkiActivity activity = (AnkiActivity) getActivity(); Collection col = CollectionHelper.getInstance().getCol(activity); try { long did = getArguments().getLong("did"); String deckName = col.getDecks().get(did).getString("name"); String customStudyDeck = getResources().getString(R.string.custom_study_deck_name); JSONObject cur = col.getDecks().byName(customStudyDeck); if (cur != null) { if (cur.getInt("dyn") != 1) { new MaterialDialog.Builder(getActivity()).content(R.string.custom_study_deck_exists) .negativeText(R.string.dialog_cancel).build().show(); return; } else { // safe to empty col.getSched().emptyDyn(cur.getLong("id")); // reuse; don't delete as it may have children dyn = cur; col.getDecks().select(cur.getLong("id")); } } else { long customStudyDid = col.getDecks().newDyn(customStudyDeck); dyn = col.getDecks().get(customStudyDid); } // and then set various options if (delays.length() > 0) { dyn.put("delays", delays); } else { dyn.put("delays", JSONObject.NULL); } JSONArray ar = dyn.getJSONArray("terms"); ar.getJSONArray(0).put(0, "deck:\"" + deckName + "\" " + terms[0]); ar.getJSONArray(0).put(1, terms[1]); ar.getJSONArray(0).put(2, terms[2]); dyn.put("resched", resched); // Rebuild the filtered deck DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REBUILD_CRAM, new DeckTask.TaskListener() { @Override public void onCancelled() { } @Override public void onPreExecute() { activity.showProgressBar(); } @Override public void onPostExecute(DeckTask.TaskData result) { activity.hideProgressBar(); ((CustomStudyListener) activity).onCreateCustomStudySession(); } @Override public void onProgressUpdate(DeckTask.TaskData... values) { } }); } catch (JSONException e) { throw new RuntimeException(e); } // Hide the dialogs activity.dismissAllDialogFragments(); }
From source file:waveimport.RobotApi.java
/** * Searches the user's waves. Returns at most {@code maxResults} results, * starting with the {@code startIndex}-th result (0-based index). * * Note: Google Wave's search feature may limit the overall set of result for * any given query to the first N hits (for some N, perhaps 300), regardless * of {@code startIndex} and {@code maxResults}, so don't rely on these to * iterate over all waves.//from w w w. jav a 2s. com */ public List<RobotSearchDigest> search(String query, int startIndex, int maxResults) throws IOException { log.info("search(" + query + ", " + startIndex + ", " + maxResults + ")"); JSONObject response = callRobotApi(ROBOT_API_METHOD_SEARCH, ImmutableMap.<String, Object>of("query", query, "index", startIndex, "numResults", maxResults)); System.out.println("gson :" + response.toString()); // The response looks like this: // {"searchResults": // {"query":"after:2008/01/01 before:2010/01/01", // "numResults":1, // "digests": // [{"waveId":"googlewave.com!w+aaaa", // "title":"aaaa", // "participants": // ["aaaa@googlewave.com", // "aaab@googlewave.com", // "aaaa@googlegroups.com" // ], // "lastModified":1111111111111, // "snippet":"aaaa" // "blipCount":2, // "unreadCount":1, // } // ] // } // } ImmutableList.Builder<RobotSearchDigest> digests = ImmutableList.builder(); try { JSONObject results = response.getJSONObject("searchResults"); try { if (results.getInt("numResults") != results.getJSONArray("digests").length()) { throw new RuntimeException("Mismatched numResults and digests array length: " + results.getInt("numResults") + " vs. " + results.getJSONArray("digests")); } JSONArray rawDigests = results.getJSONArray("digests"); for (int i = 0; i < rawDigests.length(); i++) { JSONObject rawDigest = rawDigests.getJSONObject(i); try { RobotSearchDigest digest = new RobotSearchDigestGsonImpl(); digest.setWaveId(WaveId.deserialise(rawDigest.getString("waveId")).serialise()); JSONArray rawParticipants = rawDigest.getJSONArray("participants"); for (int j = 0; j < rawParticipants.length(); j++) { digest.addParticipant(rawParticipants.getString(j)); } digest.setTitle(rawDigest.getString("title")); digest.setSnippet(rawDigest.getString("snippet")); digest.setLastModifiedMillis(rawDigest.getLong("lastModified")); digest.setBlipCount(rawDigest.getInt("blipCount")); digest.setUnreadBlipCount(rawDigest.getInt("unreadCount")); digests.add(digest); } catch (JSONException e) { throw new RuntimeException("Failed to parse search digest: " + rawDigest, e); } } } catch (JSONException e) { throw new RuntimeException("Failed to parse search results: " + results, e); } } catch (JSONException e) { throw new RuntimeException("Failed to parse search response: " + response, e); } return digests.build(); }