List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:net.portalblockz.portalbot.serverdata.JSONConfigManager.java
public JSONConfigManager(File file) { instance = this; try {//from www. java 2 s .co m if (!file.exists()) { Path path = file.toPath(); Files.copy(getClass().getClassLoader().getResourceAsStream("config.json"), path); } } catch (Exception e) { e.printStackTrace(); } String s; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); StringBuilder jsonObjectBuilder = new StringBuilder(); while ((s = reader.readLine()) != null) { jsonObjectBuilder.append(s); } configObject = new JSONObject(jsonObjectBuilder.toString()); reader.close(); } catch (Exception e) { } for (int i = 0; i < getJSONServers().length(); i++) { JSONObject server = getJSONServers().getJSONObject(i); serverList.add(new Server(server.getString("host"), server.getString("username"), server.getString("password"), server.getInt("port"), getList(server, "channels"), getList(server, "staff"), server.getString("prefix").charAt(0))); System.out.println(String.format("%s %s %s %s %s", server.getString("host"), server.getString("username"), server.getString("password"), server.getInt("port"), server.getString("prefix").charAt(0))); } serializeRepos(); serializeBlacklist(); }
From source file:com.trellmor.berrytube.ChatUser.java
/** * Constructs a <code>ChatUser</code> from a <code>JSONObject</code> * //from w w w . j av a2s .com * @param user * <code>JSONObject<code> containing user data * @throws JSONException */ public ChatUser(JSONObject user) throws JSONException { this(user.getString("nick")); if (user.has("type")) this.type = user.getInt("type"); }
From source file:com.atinternet.tracker.LifeCycleTest.java
public void lifecycleContainedInHitTest() throws JSONException { LifeCycle.firstSessionInit(preferences, null); JSONObject obj = new JSONObject(LifeCycle.getMetrics(preferences).execute()); JSONObject life = obj.getJSONObject("lifecycle"); assertEquals(1, life.getInt("fs")); assertEquals(0, life.getInt("fsau")); assertEquals(1, life.getInt("sc")); assertEquals(Integer.parseInt(today), life.getInt("fsd")); assertEquals(0, life.getInt("dsls")); assertEquals(0, life.getInt("dsfs")); assertTrue(life.isNull("dsu")); assertTrue(life.isNull("scsu")); assertTrue(life.isNull("fsdau")); }
From source file:com.atinternet.tracker.LifeCycleTest.java
@Test public void afterUpdateTest() throws JSONException { LifeCycle.firstSessionInit(preferences, null); preferences.edit().putString(LifeCycle.VERSION_CODE_KEY, "test").apply(); LifeCycle.isInitialized = false;/*from w ww . j ava2 s .c o m*/ LifeCycle.updateFirstSession(preferences); LifeCycle.newSessionInit(preferences); JSONObject obj = new JSONObject(LifeCycle.getMetrics(preferences).execute()); JSONObject life = obj.getJSONObject("lifecycle"); assertEquals(0, life.getInt("fs")); assertEquals(1, life.getInt("fsau")); assertEquals(2, life.getInt("sc")); assertEquals(Integer.parseInt(today), life.getInt("fsd")); assertEquals(0, life.getInt("dsls")); assertEquals(0, life.getInt("dsfs")); assertEquals(0, life.getInt("dsu")); assertEquals(1, life.getInt("scsu")); assertEquals(Integer.parseInt(today), life.getInt("fsdau")); }
From source file:ai.susi.mind.SusiSkill.java
/** * Create a skill by parsing of the skill description * @param json the skill description//from w w w . j a v a 2 s.co m * @throws PatternSyntaxException */ private SusiSkill(JSONObject json) throws PatternSyntaxException { // extract the phrases and the phrases subscore if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0); JSONArray p = (JSONArray) json.remove("phrases"); this.phrases = new ArrayList<>(p.length()); p.forEach(q -> this.phrases.add(new SusiPhrase((JSONObject) q))); // extract the actions and the action subscore if (!json.has("actions")) throw new PatternSyntaxException("actions missing", "", 0); p = (JSONArray) json.remove("actions"); this.actions = new ArrayList<>(p.length()); p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q))); // extract the inferences and the process subscore; there may be no inference at all if (json.has("process")) { p = (JSONArray) json.remove("process"); this.inferences = new ArrayList<>(p.length()); p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q))); } else { this.inferences = new ArrayList<>(0); } // extract (or compute) the keys; there may be none key given, then they will be computed this.keys = new HashSet<>(); JSONArray k; if (json.has("keys")) { k = json.getJSONArray("keys"); if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0)) k = computeKeysFromPhrases(this.phrases); } else { k = computeKeysFromPhrases(this.phrases); } k.forEach(o -> this.keys.add((String) o)); this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE; this.score = null; // calculate this later if required // extract the comment this.comment = json.has("comment") ? json.getString("comment") : ""; // calculate the id String ids0 = this.actions.toString(); String ids1 = this.phrases.toString(); this.id = ids0.hashCode() + ids1.hashCode(); }
From source file:drusy.ui.panels.WifiStatePanel.java
public void update(final Updater updater) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_WIFI_ID, output, "Getting WiFi id", false); task.addListener(new HttpUtils.DownloadListener() { @Override//from www.j a va2 s .co m public void onComplete() { String json = output.toString(); JSONObject obj = new JSONObject(json); boolean success = obj.getBoolean("success"); if (success == true) { JSONArray result = obj.getJSONArray("result"); JSONObject wifi = result.getJSONObject(0); int id = wifi.getInt("id"); addUsersForWifiId(id, updater); } else { String msg = obj.getString("msg"); Log.Debug("Freebox Wi-Fi State (get id)", msg); } } }); task.addListener(new HttpUtils.DownloadListener() { @Override public void onError(IOException ex) { Log.Debug("Freebox Wi-Fi State (get id)", ex.getMessage()); } }); }
From source file:net.zionsoft.obadiah.model.translations.TranslationHelper.java
public static List<TranslationInfo> toTranslationList(JSONArray jsonArray) throws Exception { final int length = jsonArray.length(); final List<TranslationInfo> translations = new ArrayList<TranslationInfo>(length); for (int i = 0; i < length; ++i) { final JSONObject translationObject = jsonArray.getJSONObject(i); final String name = translationObject.getString("name"); final String shortName = translationObject.getString("shortName"); final String language = translationObject.getString("language"); final String blobKey = translationObject.optString("blobKey", null); final int size = translationObject.getInt("size"); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(shortName) || TextUtils.isEmpty(language) || size <= 0) {/*from ww w. j av a 2s.c om*/ throw new Exception("Illegal translation info."); } translations.add(new TranslationInfo(name, shortName, language, blobKey, size)); } return translations; }
From source file:edu.umass.cs.gigapaxos.paxospackets.FindReplicaGroupPacket.java
public FindReplicaGroupPacket(JSONObject msg) throws JSONException { super(msg);/* w w w.j a v a 2 s. c om*/ this.packetType = PaxosPacketType.FIND_REPLICA_GROUP; this.nodeID = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString()); JSONArray jsonGroup = null; if (msg.has(PaxosPacket.NodeIDKeys.GROUP.toString())) { jsonGroup = msg.getJSONArray(PaxosPacket.NodeIDKeys.GROUP.toString()); } if (jsonGroup != null && jsonGroup.length() > 0) { this.group = new int[jsonGroup.length()]; for (int i = 0; i < jsonGroup.length(); i++) { this.group[i] = Integer.valueOf(jsonGroup.getString(i)); } } else this.group = null; }
From source file:edu.umass.cs.gigapaxos.paxospackets.FindReplicaGroupPacket.java
public static int getNodeID(JSONObject msg) throws JSONException { int id = -1;//from w ww. j a v a 2 s .co m if (msg.has(PaxosPacket.Keys.PT.toString())) { PaxosPacketType msgType = PaxosPacketType .getPaxosPacketType(msg.getInt(PaxosPacket.Keys.PT.toString())); switch (msgType) { case ACCEPT: id = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString()); break; case ACCEPT_REPLY: id = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString()); break; case PREPARE: id = (new Ballot(msg.getString(PaxosPacket.NodeIDKeys.B.toString()))).coordinatorID; // msg.getInt(PaxosPacket.NodeIDKeys.COORDINATOR.toString()); break; case DECISION: id = (new Ballot(msg.getString(PaxosPacket.NodeIDKeys.B.toString()))).coordinatorID; break; default: break; } } return id; }
From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java
private void handleIncomingMessage(final IncomingMessage incoming) { final SignedObj contents = incoming.contents(); final long hash = contents.getHash(); if (contents.getSender() == null) { Log.e(TAG, "Null sender for " + contents.getType() + ", " + contents.getJson()); return;// w ww . j a v a2s. co m } final String personId = contents.getSender().getId(); // final String personId = incoming.from(); /** * TODO: This needs to be updated with the POSI standards to accept a * SignedObj. */ if (DBG) Log.i(TAG, "Localized contents: " + contents); try { JSONObject in_obj = contents.getJson(); String feedName = contents.getFeedName(); String type = contents.getType(); Uri feedPreUri = Feed.uriForName(feedName); if (mMessageDropHandler.preFiltersObj(mContext, feedPreUri)) { return; } if (mHelper.queryAlreadyReceived(hash)) { if (DBG) Log.i(TAG, "Message already received: " + hash); return; } Maybe<Contact> contact = mHelper.contactForPersonId(personId); final DbEntryHandler objHandler = DbObjects.getObjHandler(in_obj); byte[] extracted_data = null; if (objHandler instanceof UnprocessedMessageHandler) { Pair<JSONObject, byte[]> r = ((UnprocessedMessageHandler) objHandler).handleUnprocessed(mContext, in_obj); if (r != null) { in_obj = r.first; extracted_data = r.second; } } final JSONObject obj = in_obj; final byte[] raw = extracted_data; /** * TODO STFAN BJDODSON KANAKB * * See FriendAcceptObj.handleUnprocessed as template, code is something like: * * if (!mPublicKeyDirectory.verify(in_obj.getString("email"), in_obj.getPublicKey())) { * Log.w("Spammer trying to claim public key for email address"); * return; * } * if (inAddressBook(email)) { * // auto-accept and notify of new friend * } else { * // notification to accept friend * } */ if (!contact.isKnown()) { Log.i(TAG, "Message from unknown contact. " + contents); return; } /** * Run handlers over all received objects: */ long objId; final Contact realContact = contact.get(); long contactId = realContact.id; if (DBG) Log.d(TAG, "Msg from " + contactId + " ( " + realContact.name + ")"); // Insert into the database. (TODO: Handler, both android.os and // musubi.core) if (!objHandler.handleObjFromNetwork(mContext, realContact, obj)) { return; } Integer intKey = null; if (obj.has(DbObjects.JSON_INT_KEY)) { intKey = obj.getInt(DbObjects.JSON_INT_KEY); obj.remove(DbObjects.JSON_INT_KEY); } objId = mHelper.addObjectByJson(contact.otherwise(Contact.NA()).id, obj, hash, raw, intKey); Uri feedUri; if (feedName.equals("friend")) { feedUri = Feed.uriForName("friend/" + contactId); } else { feedUri = Feed.uriForName(feedName); } mContext.getContentResolver().notifyChange(feedUri, null); if (feedName.equals("direct") || feedName.equals("friend")) { long time = obj.optLong(DbObject.TIMESTAMP); Helpers.updateLastPresence(mContext, realContact, time); objHandler.handleDirectMessage(mContext, realContact, obj); } /** * Run handlers over all received objects: */ // TODO: framework code. DbObj signedObj = App.instance().getMusubi().objForId(objId); getFromNetworkHandlers().handleObj(mContext, DbObjects.forType(type), signedObj); objHandler.afterDbInsertion(mContext, signedObj); } catch (Exception e) { Log.e(TAG, "Error handling incoming message.", e); } }