List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:com.hichinaschool.flashcards.libanki.Collection.java
public ArrayList<Long> genCards(long[] nids) { // build map of (nid,ord) so we don't create dupes String snids = Utils.ids2str(nids); HashMap<Long, HashMap<Integer, Long>> have = new HashMap<Long, HashMap<Integer, Long>>(); HashMap<Long, Long> dids = new HashMap<Long, Long>(); Cursor cur = null;/*from w w w. j a v a 2 s . c om*/ try { cur = mDb.getDatabase().rawQuery("SELECT id, nid, ord, did FROM cards WHERE nid IN " + snids, null); while (cur.moveToNext()) { // existing cards long nid = cur.getLong(1); if (!have.containsKey(nid)) { have.put(nid, new HashMap<Integer, Long>()); } have.get(nid).put(cur.getInt(2), cur.getLong(0)); // and their dids long did = cur.getLong(3); if (dids.containsKey(nid)) { if (dids.get(nid) != 0 && dids.get(nid) != did) { // cards are in two or more different decks; revert to model default dids.put(nid, 0l); } } else { // first card or multiple cards in same deck dids.put(nid, did); } } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // build cards for each note ArrayList<Object[]> data = new ArrayList<Object[]>(); long ts = Utils.maxID(mDb); long now = Utils.intNow(); ArrayList<Long> rem = new ArrayList<Long>(); int usn = usn(); cur = null; try { cur = mDb.getDatabase().rawQuery("SELECT id, mid, flds FROM notes WHERE id IN " + snids, null); while (cur.moveToNext()) { JSONObject model = mModels.get(cur.getLong(1)); ArrayList<Integer> avail = mModels.availOrds(model, cur.getString(2)); long nid = cur.getLong(0); long did = dids.get(nid); if (did == 0) { did = model.getLong("did"); } // add any missing cards for (JSONObject t : _tmplsFromOrds(model, avail)) { int tord = t.getInt("ord"); boolean doHave = have.containsKey(nid) && have.get(nid).containsKey(tord); if (!doHave) { // check deck is not a cram deck long ndid; try { ndid = t.getLong("did"); if (ndid != 0) { did = ndid; } } catch (JSONException e) { // do nothing } if (getDecks().isDyn(did)) { did = 1; } // if the deck doesn't exist, use default instead did = mDecks.get(did).getLong("id"); // we'd like to use the same due# as sibling cards, but we can't retrieve that quickly, so we // give it a new id instead data.add(new Object[] { ts, nid, did, tord, now, usn, nextID("pos") }); ts += 1; } } // note any cards that need removing if (have.containsKey(nid)) { for (Map.Entry<Integer, Long> n : have.get(nid).entrySet()) { if (!avail.contains(n.getKey())) { rem.add(n.getValue()); } } } } } catch (JSONException e) { throw new RuntimeException(e); } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } // bulk update mDb.executeMany("INSERT INTO cards VALUES (?,?,?,?,?,?,0,0,?,0,0,0,0,0,0,0,0,\"\")", data); return rem; }
From source file:com.hichinaschool.flashcards.libanki.Collection.java
private Card _newCard(Note note, JSONObject template, int due, boolean flush) { Card card = new Card(this); card.setNid(note.getId());// w w w . ja v a 2 s . c o m try { card.setOrd(template.getInt("ord")); } catch (JSONException e) { new RuntimeException(e); } long did; try { did = template.getLong("did"); } catch (JSONException e) { did = 0; } try { card.setDid(did != 0 ? did : note.model().getLong("did")); // if invalid did, use default instead JSONObject deck = mDecks.get(card.getDid()); if (deck.getInt("dyn") == 1) { // must not be a filtered deck card.setDid(1); } else { card.setDid(deck.getLong("id")); } } catch (JSONException e) { throw new RuntimeException(e); } card.setDue(_dueForDid(card.getDid(), due)); if (flush) { card.flush(); } return card; }
From source file:com.hichinaschool.flashcards.libanki.Collection.java
/** * DB maintenance *********************************************************** ************************************ *//*from w w w . j av a2 s . c o m*/ /* * Basic integrity check for syncing. True if ok. */ public boolean basicCheck() { // cards without notes if (mDb.queryScalar("select 1 from cards where nid not in (select id from notes) limit 1", false) > 0) { return false; } boolean badNotes = mDb.queryScalar( String.format(Locale.US, "select 1 from notes where id not in (select distinct nid from cards) " + "or mid not in %s limit 1", Utils.ids2str(mModels.ids())), false) > 0; // notes without cards or models if (badNotes) { return false; } try { // invalid ords for (JSONObject m : mModels.all()) { // ignore clozes if (m.getInt("type") != Sched.MODEL_STD) { continue; } // Make a list of valid ords for this model JSONArray tmpls = m.getJSONArray("tmpls"); int[] ords = new int[tmpls.length()]; for (int t = 0; t < tmpls.length(); t++) { ords[t] = tmpls.getJSONObject(t).getInt("ord"); } boolean badOrd = mDb.queryScalar(String.format(Locale.US, "select 1 from cards where ord not in %s and nid in ( " + "select id from notes where mid = %d) limit 1", Utils.ids2str(ords), m.getLong("id")), false) > 0; if (badOrd) { return false; } } } catch (JSONException e) { throw new RuntimeException(e); } return true; }
From source file:com.hichinaschool.flashcards.libanki.Collection.java
/** Fix possible problems and rebuild caches. */ public long fixIntegrity() { File file = new File(mPath); ArrayList<String> problems = new ArrayList<String>(); long oldSize = file.length(); try {/*from w ww . j a v a 2 s . c o m*/ mDb.getDatabase().beginTransaction(); try { save(); if (!mDb.queryString("PRAGMA integrity_check").equals("ok")) { return -1; } // note types with a missing model ArrayList<Long> ids = mDb.queryColumn(Long.class, "SELECT id FROM notes WHERE mid NOT IN " + Utils.ids2str(mModels.ids()), 0); if (ids.size() != 0) { problems.add("Deleted " + ids.size() + " note(s) with missing note type."); _remNotes(Utils.arrayList2array(ids)); } // for each model for (JSONObject m : mModels.all()) { // cards with invalid ordinal if (m.getInt("type") == Sched.MODEL_STD) { ArrayList<Integer> ords = new ArrayList<Integer>(); JSONArray tmpls = m.getJSONArray("tmpls"); for (int t = 0; t < tmpls.length(); t++) { ords.add(tmpls.getJSONObject(t).getInt("ord")); } ids = mDb.queryColumn(Long.class, "SELECT id FROM cards WHERE ord NOT IN " + Utils.ids2str(ords) + " AND nid IN ( " + "SELECT id FROM notes WHERE mid = " + m.getLong("id") + ")", 0); if (ids.size() > 0) { problems.add("Deleted " + ids.size() + " card(s) with missing template."); remCards(Utils.arrayList2array(ids)); } } // notes with invalid field counts ids = new ArrayList<Long>(); Cursor cur = null; try { cur = mDb.getDatabase() .rawQuery("select id, flds from notes where mid = " + m.getLong("id"), null); while (cur.moveToNext()) { String flds = cur.getString(1); long id = cur.getLong(0); int fldsCount = 0; for (int i = 0; i < flds.length(); i++) { if (flds.charAt(i) == 0x1f) { fldsCount++; } } if (fldsCount + 1 != m.getJSONArray("flds").length()) { ids.add(id); } } if (ids.size() > 0) { problems.add("Deleted " + ids.size() + " note(s) with wrong field count."); _remNotes(Utils.arrayList2array(ids)); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } } // delete any notes with missing cards ids = mDb.queryColumn(Long.class, "SELECT id FROM notes WHERE id NOT IN (SELECT DISTINCT nid FROM cards)", 0); if (ids.size() != 0) { problems.add("Deleted " + ids.size() + " note(s) with missing no cards."); _remNotes(Utils.arrayList2array(ids)); } // cards with missing notes ids = mDb.queryColumn(Long.class, "SELECT id FROM cards WHERE nid NOT IN (SELECT id FROM notes)", 0); if (ids.size() != 0) { problems.add("Deleted " + ids.size() + " card(s) with missing note."); remCards(Utils.arrayList2array(ids)); } // tags mTags.registerNotes(); // field cache for (JSONObject m : mModels.all()) { updateFieldCache(Utils.arrayList2array(mModels.nids(m))); } // new cards can't have a due position > 32 bits mDb.execute("UPDATE cards SET due = 1000000, mod = " + Utils.intNow() + ", usn = " + usn() + " WHERE due > 1000000 AND queue = 0"); // new card position mConf.put("nextPos", mDb.queryScalar("SELECT max(due) + 1 FROM cards WHERE type = 0", false)); // reviews should have a reasonable due ids = mDb.queryColumn(Long.class, "SELECT id FROM cards WHERE queue = 2 AND due > 10000", 0); if (ids.size() > 0) { problems.add("Reviews had incorrect due date."); mDb.execute("UPDATE cards SET due = 0, mod = " + Utils.intNow() + ", usn = " + usn() + " WHERE id IN " + Utils.ids2str(Utils.arrayList2array(ids))); } mDb.getDatabase().setTransactionSuccessful(); // DB must have indices. Older versions of AnkiDroid didn't create them for new collections. int ixs = mDb.queryScalar("select count(name) from sqlite_master where type = 'index'"); if (ixs < 7) { problems.add("Indices were missing."); Storage.addIndices(mDb); } } catch (JSONException e) { throw new RuntimeException(e); } finally { mDb.getDatabase().endTransaction(); } } catch (RuntimeException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundCheckDatabase - RuntimeException on marking card: " + e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundCheckDatabase"); return -1; } // and finally, optimize optimize(); file = new File(mPath); long newSize = file.length(); // if any problems were found, force a full sync if (problems.size() > 0) { modSchema(false); } // TODO: report problems return (long) ((oldSize - newSize) / 1024); }
From source file:com.github.koraktor.steamcondenser.community.portal2.Portal2Item.java
/** * Creates a new instance of a Portal2Item with the given data * * @param inventory The inventory this item is contained in * @param itemData The data specifying this item * @throws JSONException on invalid JSON data * @throws WebApiException on Web API errors *//*from ww w . jav a2 s . c om*/ public Portal2Item(Portal2Inventory inventory, JSONObject itemData) throws JSONException, SteamCondenserException { super(inventory, itemData); this.equipped = new HashMap<String, Boolean>(); for (int botId = 0; botId < BOTS.length; botId++) { this.equipped.put(BOTS[botId], (itemData.getLong("inventory") & (1 << 16 + botId)) != 0); } }
From source file:org.onepf.store.data.Purchase.java
public Purchase(String json) throws JSONException { JSONObject o = new JSONObject(json); _orderId = o.getString("orderId"); _packageName = o.getString("packageName"); _sku = o.getString("productId"); _purchaseTime = o.getLong("purchaseTime"); _purchaseState = o.getInt("purchaseState"); _developerPayload = o.getString("developerPayload"); _token = o.getString("purchaseToken"); }
From source file:org.akvo.flow.api.parser.json.SurveyedLocaleParser.java
public SurveyedLocale parseSurveyedLocale(JSONObject jSurveyedLocale) throws JSONException { String id = jSurveyedLocale.getString(Attrs.ID); long lastModified = jSurveyedLocale.getLong(Attrs.LAST_MODIFIED); long surveyGroupId = jSurveyedLocale.getLong(Attrs.SURVEY_GROUP_ID); Double latitude = jSurveyedLocale.has(Attrs.LATITUDE) && !jSurveyedLocale.isNull(Attrs.LATITUDE) ? jSurveyedLocale.getDouble(Attrs.LATITUDE) : null;/*from ww w . j a v a2s .c om*/ Double longitude = jSurveyedLocale.has(Attrs.LONGITUDE) && !jSurveyedLocale.isNull(Attrs.LONGITUDE) ? jSurveyedLocale.getDouble(Attrs.LONGITUDE) : null; String name = jSurveyedLocale.has(Attrs.NAME) && !jSurveyedLocale.isNull(Attrs.NAME) ? jSurveyedLocale.getString(Attrs.NAME) : null; JSONArray jSurveyInstances = jSurveyedLocale.getJSONArray(Attrs.SURVEY_INSTANCES); List<SurveyInstance> surveyInstances = new SurveyInstanceParser().parseList(jSurveyInstances); SurveyedLocale surveyedLocale = new SurveyedLocale(id, name, lastModified, surveyGroupId, latitude, longitude); surveyedLocale.setSurveyInstances(surveyInstances); return surveyedLocale; }
From source file:fr.cvlaminck.nominatim.json.PlaceJsonParser.java
@Override protected Place doParseFromJson(JSONObject json) throws JSONException, NominatimAPIResponseException { Place p = new Place(); p.setPlaceId(json.getLong(PLACE_ID)); p.setOsmId(json.getLong(PLACE_OSM_ID)); p.setType(PlaceType.typeForName(json.getString(PLACE_TYPE))); p.setOsmType(OsmType.typeForName(json.getString(PLACE_OSM_TYPE))); if (json.has(PLACE_CATEGORY)) { p.setCategory(PlaceCategory.categoryForName(json.getString(PLACE_CATEGORY))); }/*from www. j av a2s . c o m*/ if (json.has(PLACE_CLASS)) { p.setCategory(PlaceCategory.categoryForName(json.getString(PLACE_CLASS))); } p.setType(PlaceType.typeForName(json.getString(PLACE_TYPE))); if (json.has(PLACE_ICON)) { p.setIcon(json.getString(PLACE_ICON)); } p.setDisplayName(json.getString(PLACE_DISPLAY_NAME)); p.setLongitude(json.getDouble(PLACE_LONGITUDE)); p.setLatitude(json.getDouble(PLACE_LATITUDE)); if (json.has(PLACE_ADDRESS)) { p.setAddress(getAddressParser().parse(json.getJSONObject(PLACE_ADDRESS))); } //FIXME bounding box if (json.has(PLACE_RANK)) { p.setPlaceRank(json.getInt(PLACE_RANK)); } p.setImportance(json.getDouble(PLACE_IMPORTANCE)); p.setLicence(json.getString(PLACE_LICENCE)); return p; }
From source file:net.dv8tion.jda.core.requests.WebSocketClient.java
@Override public void onTextMessage(WebSocket websocket, String message) { JSONObject content = new JSONObject(message); int opCode = content.getInt("op"); if (!content.isNull("s")) { api.setResponseTotal(content.getInt("s")); }/*from ww w . ja va2s .c o m*/ switch (opCode) { case WebSocketCode.DISPATCH: handleEvent(content); break; case WebSocketCode.HEARTBEAT: LOG.debug("Got Keep-Alive request (OP 1). Sending response..."); sendKeepAlive(); break; case WebSocketCode.RECONNECT: LOG.debug("Got Reconnect request (OP 7). Closing connection now..."); close(); break; case WebSocketCode.INVALIDATE_SESSION: LOG.debug("Got Invalidate request (OP 9). Invalidating..."); final boolean isResume = content.getBoolean("d"); // When d: true we can wait a bit and then try to resume again //sending 4000 to not drop session int closeCode = isResume ? 4000 : 1000; if (isResume) LOG.debug("Session can be recovered... Closing and sending new RESUME request"); else if (!handleIdentifyRateLimit) // this can also mean we got rate limited in IDENTIFY (no need to invalidate then) invalidate(); close(closeCode); break; case WebSocketCode.HELLO: LOG.debug("Got HELLO packet (OP 10). Initializing keep-alive."); final JSONObject data = content.getJSONObject("d"); setupKeepAlive(data.getLong("heartbeat_interval")); if (!data.isNull("_trace")) updateTraces(data.getJSONArray("_trace"), "HELLO", WebSocketCode.HELLO); break; case WebSocketCode.HEARTBEAT_ACK: LOG.trace("Got Heartbeat Ack (OP 11)."); api.setPing(System.currentTimeMillis() - heartbeatStartTime); break; default: LOG.debug("Got unknown op-code: " + opCode + " with content: " + message); } }
From source file:net.dv8tion.jda.core.handle.GuildRoleUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; JSONObject rolejson = content.getJSONObject("role"); GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); if (guild == null) { api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug("Received a Role Update for a Guild that is not yet cached: " + content); return null; }// w ww . ja v a2 s. co m final long roleId = rolejson.getLong("id"); RoleImpl role = (RoleImpl) guild.getRolesMap().get(roleId); if (role == null) { api.getEventCache().cache(EventCache.Type.ROLE, roleId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug("Received a Role Update for Role that is not yet cached: " + content); return null; } String name = rolejson.getString("name"); Color color = rolejson.getInt("color") != 0 ? new Color(rolejson.getInt("color")) : null; int position = rolejson.getInt("position"); long permissions = rolejson.getLong("permissions"); boolean hoisted = rolejson.getBoolean("hoist"); boolean mentionable = rolejson.getBoolean("mentionable"); if (!Objects.equals(name, role.getName())) { String oldName = role.getName(); role.setName(name); api.getEventManager().handle(new RoleUpdateNameEvent(api, responseNumber, role, oldName)); } if (!Objects.equals(color, role.getColor())) { Color oldColor = role.getColor(); role.setColor(color); api.getEventManager().handle(new RoleUpdateColorEvent(api, responseNumber, role, oldColor)); } if (!Objects.equals(position, role.getPositionRaw())) { int oldPosition = role.getPosition(); int oldPositionRaw = role.getPositionRaw(); role.setRawPosition(position); api.getEventManager() .handle(new RoleUpdatePositionEvent(api, responseNumber, role, oldPosition, oldPositionRaw)); } if (!Objects.equals(permissions, role.getPermissionsRaw())) { long oldPermissionsRaw = role.getPermissionsRaw(); role.setRawPermissions(permissions); api.getEventManager() .handle(new RoleUpdatePermissionsEvent(api, responseNumber, role, oldPermissionsRaw)); } if (hoisted != role.isHoisted()) { boolean wasHoisted = role.isHoisted(); role.setHoisted(hoisted); api.getEventManager().handle(new RoleUpdateHoistedEvent(api, responseNumber, role, wasHoisted)); } if (mentionable != role.isMentionable()) { boolean wasMentionable = role.isMentionable(); role.setMentionable(mentionable); api.getEventManager().handle(new RoleUpdateMentionableEvent(api, responseNumber, role, wasMentionable)); } return null; }