List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:com.chess.genesis.net.SyncClient.java
private void sync_active(final JSONObject json) { try {//from w w w .j a v a2s.c om final ArrayList<String> list_need = getNeedList(json.getJSONArray("gameids")); final ExecutorService pool = Executors.newCachedThreadPool(); for (final String item : list_need) { if (error) return; final NetworkClient nc = new NetworkClient(context, handle); nc.game_info(item); pool.submit(nc); lock++; } // don't save time if only syncing active if (syncType == ACTIVE_SYNC) return; // Save sync time final long time = json.getLong("time"); final PrefEdit pref = new PrefEdit(context); pref.putLong(R.array.pf_lastgamesync, time); pref.commit(); } catch (final JSONException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.chess.genesis.net.SyncClient.java
private void saveMsgs(final JSONObject data) { try {/*from w w w. ja v a2 s .c o m*/ final JSONArray msgs = data.getJSONArray("msglist"); final long time = data.getLong("time"); final GameDataDB db = new GameDataDB(context); for (int i = 0, len = msgs.length(); i < len; i++) { final JSONObject item = msgs.getJSONObject(i); db.insertMsg(item); } db.close(); // Save sync time final PrefEdit pref = new PrefEdit(context); pref.putLong(R.array.pf_lastmsgsync, time); pref.commit(); } catch (final JSONException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:curso.android.DAO.RespostaDAO.java
public static void insertLista(JSONArray jArray) { Resposta asw = null;/*from w ww .j a v a 2s. c om*/ JSONObject json = null; try { for (int i = 0; i < jArray.length(); i++) { json = jArray.getJSONObject(i); asw = new Resposta(); asw.setAsk_id(json.getLong("id")); asw.setAsk_id(json.getLong("pergunta")); asw.setUser_id(json.getLong("usuario")); asw.setUser_name(json.getString("user_name")); asw.setAsw_resposta(json.getString("resposta")); insert(asw); json = null; asw = null; } } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.parking.billing.Security.java
/** * Verifies that the data was signed with the given signature, and returns * the list of verified purchases. The data is in JSON format and contains * a nonce (number used once) that we generated and that was signed * (as part of the whole data string) with a private key. The data also * contains the {@link PurchaseState} and product ID of the purchase. * In the general case, there can be an array of purchase transactions * because there may be delays in processing the purchase on the backend * and then several purchases can be batched together. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key *//*from w w w . ja v a 2 s . co m*/ public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return null; } if (BillingConstants.DEBUG) { Log.i(TAG, "signedData: " + signedData); } boolean verified = false; if (!TextUtils.isEmpty(signature)) { /** * Compute your public key (that you got from the Android Market publisher site). * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an adversary to replace the public key with one * of their own and then fake messages from the server. * * Generally, encryption keys / passwords should only be kept in memory * long enough to perform the operation they need to perform. */ //Chintan's Key String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuRIrk/6nAPzZo5HKe261/ZMfoe63mtY5QUlc0A0/77RTicrS9Nk1VjtVniRpHmjasQOGsQrBpBGJUYp0ixsjJpgfjLv7OvpF8Hp/ucth2T/Bm7kl/odRDT3urAp3snvqZEzfOg1wtDU7DAnDW1zNSqVNCVczXRnNrEmGxEjamKkTTQwz37ui7AhjKXCXAJY4n5ANj1oymnjGN5FHfzcMb07wR/ucz39ZX+Raf6qBsbnYkmuDH6pJ/4ZI9+vjbgWzXCx07DefQW4dtNMQZlVlKgKnJUkafePUYJVIO4sRgeWL1e5b8dbIYMO7gB9oopyfVhZifi+pDGr5+YAxi6D3PwIDAQAB"; //Mandar's Key: //String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj7zgTswMi1ePyAK7rCnCOkpmviHZzoSn2cxtyQ5ZQRFifNGkKq3Gli3VbeIeeJR8GHzlfOPUSgtMrd17WtGJoo29rsw6UuXov+imQutGKZglcM/cIrlIdZCsse3dGYyDcKFhEHrC/nPdwlYxgIGBaZKAcbbhitkdgYaVHQvGFTagCytxDq9NDJAY7exSKKm2HimfjlcBZjhHeImZ+cRCPux+9uoBQ4mTRYjrXfcpi/OPKTKsq2AHXf/y60qsZJlgGl3tBgRQo6lOEr7UbbHKESTKvOQ4t3J1wjNz8Z3+T0PZHb5JkeTsdAE7cG7jmz2HmMxfdXcT5mBTTDei6DPDGwIDAQAB"; PublicKey key = Security.generatePublicKey(base64EncodedPublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return null; } } JSONObject jObject; JSONArray jTransactionsArray = null; int numTransactions = 0; long nonce = 0L; try { jObject = new JSONObject(signedData); // The nonce might be null if the user backed out of the buy page. nonce = jObject.optLong("nonce"); jTransactionsArray = jObject.optJSONArray("orders"); if (jTransactionsArray != null) { numTransactions = jTransactionsArray.length(); } } catch (JSONException e) { return null; } if (!Security.isNonceKnown(nonce)) { Log.w(TAG, "Nonce not found: " + nonce); return null; } ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>(); try { for (int i = 0; i < numTransactions; i++) { JSONObject jElement = jTransactionsArray.getJSONObject(i); int response = jElement.getInt("purchaseState"); PurchaseState purchaseState = PurchaseState.valueOf(response); String productId = jElement.getString("productId"); String packageName = jElement.getString("packageName"); long purchaseTime = jElement.getLong("purchaseTime"); String orderId = jElement.optString("orderId", ""); String notifyId = null; if (jElement.has("notificationId")) { notifyId = jElement.getString("notificationId"); } String developerPayload = jElement.optString("developerPayload", null); // If the purchase state is PURCHASED, then we require a // verified nonce. /** * mandarm - We are ok with no signature for our test code! */ //TODO - Take care for signed purchases. if (purchaseState == PurchaseState.PURCHASED && !verified) { continue; } purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime, developerPayload)); } } catch (JSONException e) { Log.e(TAG, "JSON exception: ", e); return null; } removeNonce(nonce); return purchases; }
From source file:org.apache.giraph.graph.BspServiceWorker.java
@Override public void setup() { // Unless doing a restart, prepare for computation: // 1. Start superstep INPUT_SUPERSTEP (no computation) // 2. Wait until the INPUT_SPLIT_ALL_READY_PATH node has been created // 3. Process input splits until there are no more. // 4. Wait until the INPUT_SPLIT_ALL_DONE_PATH node has been created // 5. Wait for superstep INPUT_SUPERSTEP to complete. if (getRestartedSuperstep() != UNSET_SUPERSTEP) { setCachedSuperstep(getRestartedSuperstep()); return;/*ww w. j ava2 s . c om*/ } JSONObject jobState = getJobState(); if (jobState != null) { try { if ((ApplicationState .valueOf(jobState.getString(JSONOBJ_STATE_KEY)) == ApplicationState.START_SUPERSTEP) && jobState.getLong(JSONOBJ_SUPERSTEP_KEY) == getSuperstep()) { if (LOG.isInfoEnabled()) { LOG.info("setup: Restarting from an automated " + "checkpointed superstep " + getSuperstep() + ", attempt " + getApplicationAttempt()); } setRestartedSuperstep(getSuperstep()); return; } } catch (JSONException e) { throw new RuntimeException("setup: Failed to get key-values from " + jobState.toString(), e); } } // Add the partitions for that this worker owns Collection<? extends PartitionOwner> masterSetPartitionOwners = startSuperstep(); workerGraphPartitioner.updatePartitionOwners(getWorkerInfo(), masterSetPartitionOwners, getPartitionMap()); commService.setup(); // Ensure the InputSplits are ready for processing before processing while (true) { Stat inputSplitsReadyStat; try { inputSplitsReadyStat = getZkExt().exists(inputSplitsAllReadyPath, true); } catch (KeeperException e) { throw new IllegalStateException("setup: KeeperException waiting on input splits", e); } catch (InterruptedException e) { throw new IllegalStateException("setup: InterruptedException waiting on input splits", e); } if (inputSplitsReadyStat != null) { break; } getInputSplitsAllReadyEvent().waitForever(); getInputSplitsAllReadyEvent().reset(); } getContext().progress(); try { VertexEdgeCount vertexEdgeCount = loadVertices(); if (LOG.isInfoEnabled()) { LOG.info("setup: Finally loaded a total of " + vertexEdgeCount); } } catch (IOException e) { throw new IllegalStateException("setup: loadVertices failed due to " + "IOException", e); } catch (ClassNotFoundException e) { throw new IllegalStateException("setup: loadVertices failed due to " + "ClassNotFoundException", e); } catch (InterruptedException e) { throw new IllegalStateException("setup: loadVertices failed due to " + "InterruptedException", e); } catch (InstantiationException e) { throw new IllegalStateException("setup: loadVertices failed due to " + "InstantiationException", e); } catch (IllegalAccessException e) { throw new IllegalStateException("setup: loadVertices failed due to " + "IllegalAccessException", e); } catch (KeeperException e) { throw new IllegalStateException("setup: loadVertices failed due to " + "KeeperException", e); } getContext().progress(); // Workers wait for each other to finish, coordinated by master String workerDonePath = inputSplitsDonePath + "/" + getWorkerInfo().getHostnameId(); try { getZkExt().createExt(workerDonePath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, true); } catch (KeeperException e) { throw new IllegalStateException("setup: KeeperException creating worker done splits", e); } catch (InterruptedException e) { throw new IllegalStateException("setup: InterruptedException creating worker done splits", e); } while (true) { Stat inputSplitsDoneStat; try { inputSplitsDoneStat = getZkExt().exists(inputSplitsAllDonePath, true); } catch (KeeperException e) { throw new IllegalStateException("setup: KeeperException waiting on worker done splits", e); } catch (InterruptedException e) { throw new IllegalStateException("setup: InterruptedException waiting on worker " + "done splits", e); } if (inputSplitsDoneStat != null) { break; } getInputSplitsAllDoneEvent().waitForever(); getInputSplitsAllDoneEvent().reset(); } // At this point all vertices have been sent to their destinations. // Move them to the worker, creating creating the empty partitions movePartitionsToWorker(commService); for (PartitionOwner partitionOwner : masterSetPartitionOwners) { if (partitionOwner.getWorkerInfo().equals(getWorkerInfo()) && !getPartitionMap().containsKey(partitionOwner.getPartitionId())) { Partition<I, V, E, M> partition = new Partition<I, V, E, M>(getConfiguration(), partitionOwner.getPartitionId()); getPartitionMap().put(partitionOwner.getPartitionId(), partition); } } // Generate the partition stats for the input superstep and process // if necessary List<PartitionStats> partitionStatsList = new ArrayList<PartitionStats>(); for (Partition<I, V, E, M> partition : getPartitionMap().values()) { PartitionStats partitionStats = new PartitionStats(partition.getPartitionId(), partition.getVertices().size(), 0, partition.getEdgeCount()); partitionStatsList.add(partitionStats); } workerGraphPartitioner.finalizePartitionStats(partitionStatsList, workerPartitionMap); finishSuperstep(partitionStatsList); }
From source file:org.apache.giraph.graph.BspServiceWorker.java
@Override protected boolean processEvent(WatchedEvent event) { boolean foundEvent = false; if (event.getPath().startsWith(masterJobStatePath) && (event.getType() == EventType.NodeChildrenChanged)) { if (LOG.isInfoEnabled()) { LOG.info("processEvent: Job state changed, checking " + "to see if it needs to restart"); }/* w w w . j ava 2 s . co m*/ JSONObject jsonObj = getJobState(); try { if ((ApplicationState .valueOf(jsonObj.getString(JSONOBJ_STATE_KEY)) == ApplicationState.START_SUPERSTEP) && jsonObj.getLong(JSONOBJ_APPLICATION_ATTEMPT_KEY) != getApplicationAttempt()) { LOG.fatal("processEvent: Worker will restart " + "from command - " + jsonObj.toString()); System.exit(-1); } } catch (JSONException e) { throw new RuntimeException( "processEvent: Couldn't properly get job state from " + jsonObj.toString()); } foundEvent = true; } else if (event.getPath().contains(PARTITION_EXCHANGE_DIR) && event.getType() == EventType.NodeChildrenChanged) { if (LOG.isInfoEnabled()) { LOG.info("processEvent : partitionExchangeChildrenChanged " + "(at least one worker is done sending partitions)"); } partitionExchangeChildrenChanged.signal(); foundEvent = true; } return foundEvent; }
From source file:net.dv8tion.jda.core.handle.MessageDeleteHandler.java
@Override protected Long handleInternally(JSONObject content) { final long messageId = content.getLong("id"); final long channelId = content.getLong("channel_id"); MessageChannel channel = api.getTextChannelById(channelId); if (channel == null) { channel = api.getPrivateChannelById(channelId); }//w w w. ja va 2 s . co m if (channel == null) { channel = api.getFakePrivateChannelMap().get(channelId); } if (channel == null && api.getAccountType() == AccountType.CLIENT) { channel = api.asClient().getGroupById(channelId); } if (channel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug( "Got message delete for a channel/group that is not yet cached. ChannelId: " + channelId); return null; } if (channel instanceof TextChannel) { TextChannelImpl tChan = (TextChannelImpl) channel; if (api.getGuildLock().isLocked(tChan.getGuild().getIdLong())) { return tChan.getGuild().getIdLong(); } if (tChan.hasLatestMessage() && messageId == channel.getLatestMessageIdLong()) tChan.setLastMessageId(-1); // Reset latest message id as it was deleted. api.getEventManager().handle(new GuildMessageDeleteEvent(api, responseNumber, messageId, tChan)); } else if (channel instanceof PrivateChannel) { PrivateChannelImpl pChan = (PrivateChannelImpl) channel; if (channel.hasLatestMessage() && messageId == channel.getLatestMessageIdLong()) pChan.setLastMessageId(-1); // Reset latest message id as it was deleted. api.getEventManager().handle(new PrivateMessageDeleteEvent(api, responseNumber, messageId, pChan)); } else { GroupImpl group = (GroupImpl) channel; if (channel.hasLatestMessage() && messageId == channel.getLatestMessageIdLong()) group.setLastMessageId(-1); // Reset latest message id as it was deleted. api.getEventManager().handle(new GroupMessageDeleteEvent(api, responseNumber, messageId, group)); } //Combo event api.getEventManager().handle(new MessageDeleteEvent(api, responseNumber, messageId, channel)); return null; }
From source file:com.poguico.palmabici.parsers.Parser.java
public static ArrayList<Station> parseNetworkJSON(String data) { ArrayList<Station> stations = new ArrayList<Station>(); JSONArray jsonArray;//from w w w . jav a 2 s .c o m JSONObject jsonObject; Long lngAcum = 0L, latAcum = 0L; int id; try { jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); lngAcum += jsonObject.getLong("lng"); latAcum += jsonObject.getLong("lat"); id = jsonObject.getInt("id"); stations.add(new Station(id, jsonObject.getString("name"), jsonObject.getDouble("lng") / 1e6, jsonObject.getDouble("lat") / 1e6, jsonObject.getInt("free"), jsonObject.getInt("bikes"), false, NetworkStationAlarm.hasAlarm(id))); } } catch (Exception e) { e.printStackTrace(); } return stations; }
From source file:org.melato.bus.otp.OTPParser.java
static Leg parseLeg(JSONObject json) throws JSONException { String mode = json.getString("mode"); Leg leg = null;/* ww w . jav a 2s . c om*/ if ("WALK".equals(mode)) { WalkLeg walk = new WalkLeg(); leg = walk; } else if ("TRANSFER".equals(mode)) { TransferLeg transfer = new TransferLeg(); transfer.from = getStop(json, "from"); transfer.to = getStop(json, "to"); leg = transfer; } else { TransitLeg transit = new TransitLeg(); transit.routeId = json.getString("routeId"); transit.label = json.getString("routeShortName"); transit.from = getStop(json, "from"); transit.to = getStop(json, "to"); leg = transit; } leg.distance = (float) json.getDouble("distance"); leg.duration = (int) (json.getLong("duration") / 1000L); leg.startTime = new Date(json.getLong("startTime")); leg.endTime = new Date(json.getLong("endTime")); leg.mode = mode; return leg; }
From source file:org.melato.bus.otp.OTPParser.java
static Itinerary parseItinerary(JSONObject json) throws JSONException { JSONArray legs = json.getJSONArray("legs"); Itinerary itinerary = new Itinerary(); itinerary.legs = new Leg[legs.length()]; itinerary.startTime = new Date(json.getLong("startTime")); itinerary.endTime = new Date(json.getLong("endTime")); for (int i = 0; i < itinerary.legs.length; i++) { itinerary.legs[i] = parseLeg(legs.getJSONObject(i)); }//from w w w .jav a 2 s. c o m return itinerary; }