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.googlecode.flickrjandroid.commons.CommonsInterface.java

private Institution parseInstitution(JSONObject mElement) throws JSONException {
    Institution inst = new Institution();
    inst.setId(mElement.getString("nsid"));
    inst.setDateLaunch(mElement.getLong("date_launch"));
    inst.setName(mElement.getJSONObject("name").getString("_content"));
    JSONObject urlsElement = mElement.getJSONObject("urls");
    JSONArray urlNodes = urlsElement.getJSONArray("url");
    for (int i = 0; i < urlNodes.length(); i++) {
        JSONObject urlElement = urlNodes.getJSONObject(i);
        if (urlElement.getString("type").equals("site")) {
            inst.setSiteUrl(urlElement.getString("_content"));
        } else if (urlElement.getString("type").equals("license")) {
            inst.setLicenseUrl(urlElement.getString("_content"));
        } else if (urlElement.getString("type").equals("flickr")) {
            inst.setFlickrUrl(urlElement.getString("_content"));
        }/* w  ww . j av  a  2  s  . co m*/
    }
    return inst;
}

From source file:org.uiautomation.ios.server.command.web.SetTimeoutHandler.java

/**
 * type - {string} The type of operation to set the timeout for. Valid values
 * are: "script" for script timeouts, "implicit" for modifying the implicit
 * wait timeout and "page load" for setting a page load timeout.
 *///from   w  w w .j  a va 2s.c  o m
@Override
public Response handle() throws Exception {
    JSONObject payload = getRequest().getPayload();
    String type = payload.optString("type");
    if ("page load".equals(type)) {
        long timeout = payload.getLong("ms");
        // meant for driver.get command
        CommandConfiguration conf = getSession().configure(WebDriverLikeCommand.URL);
        conf.set("page load", timeout);
    } else {
        throw new UnsupportedCommandException("timeout " + payload + " NI");
    }
    Response res = new Response();
    res.setSessionId(getSession().getSessionId());
    res.setStatus(0);
    res.setValue(new JSONObject());
    return res;
}

From source file:org.loklak.android.client.SuggestClient.java

public static ResultList<QueryEntry> suggest(final String protocolhostportstub, final String q,
        final String source, final int count, final String order, final String orderby,
        final int timezoneOffset, final String since, final String until, final String selectby,
        final int random) {
    ResultList<QueryEntry> rl = new ResultList<QueryEntry>();
    String urlstring = "";
    try {/*from ww  w .  ja v  a2s  .c  o  m*/
        urlstring = protocolhostportstub + "/api/suggest.json?q="
                + URLEncoder.encode(q.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset
                + "&count=" + count + "&source=" + (source == null ? "all" : source)
                + (order == null ? "" : ("&order=" + order)) + (orderby == null ? "" : ("&orderby=" + orderby))
                + (since == null ? "" : ("&since=" + since)) + (until == null ? "" : ("&until=" + until))
                + (selectby == null ? "" : ("&selectby=" + selectby))
                + (random < 0 ? "" : ("&random=" + random)) + "&minified=true";
        JSONObject json = JsonIO.loadJson(urlstring);
        if (json == null || json.length() == 0)
            return rl;
        JSONArray queries = json.getJSONArray("queries");
        if (queries != null) {
            for (int i = 0; i < queries.length(); i++) {
                JSONObject query = queries.getJSONObject(i);
                if (query == null)
                    continue;
                QueryEntry qe = new QueryEntry(query);
                rl.add(qe);
            }
        }

        JSONObject metadata = json.getJSONObject("search_metadata");
        if (metadata != null) {
            long hits = metadata.getLong("hits");
            rl.setHits(hits);
        }
    } catch (Throwable e) {
        Log.e("SuggestClient", e.getMessage(), e);
    }
    return rl;
}

From source file:com.dedipower.portal.android.InvoiceLanding.java

public void onCreate(Bundle savedInstanceState) {
    API.SessionID = getIntent().getStringExtra("sessionid");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoicelanding);
    final ListView list = (ListView) findViewById(R.id.InvoiceList);

    final ProgressDialog dialog = ProgressDialog.show(this, "DediPortal", "Please wait: loading data....",
            true);/*  www  .  j  a v a2s  . c  o m*/
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
            if (Success.equals("true")) {
                UpdateErrorMessage(ErrorMessage);
                InvoiceAdaptor adapter = new InvoiceAdaptor(InvoiceLanding.this, listOfInvoices, API.SessionID);
                list.setAdapter(adapter);
            } else {
                UpdateErrorMessage(ErrorMessage);
            }
        }
    };

    Thread dataPreload = new Thread() {
        public void run() {
            try {
                InvoiceAPIReturn = API.PortalQueryHack("invoices", "", "");
                Success = InvoiceAPIReturn.getString("success");
            } catch (JSONException e) {
                ErrorMessage = "An unrecoverable JSON Exception occured.";
                Success = "false";
            }

            if (Success.equals("false")) {
                Log.i("API", "Success was false");
                try {
                    ErrorMessage = InvoiceAPIReturn.getJSONObject("hackReturn").getString("msg");
                } catch (JSONException e) {
                    ErrorMessage = "A JSON parsing error prevented an exact error message to be determined.";
                }
            } else {
                int InvoiceCount = 0;
                Log.i("APIFuncs", InvoiceAPIReturn.toString());
                try {
                    Invoices = InvoiceAPIReturn.getJSONObject("hackReturn").getJSONArray("data");
                    InvoiceCount = Invoices.length();
                    ErrorMessage = "";
                } catch (JSONException e) {
                    ErrorMessage = "There don't appear to be any invoices for your account.....";
                    InvoiceCount = 0;
                    Log.e("API", "There was an eror parsing the array");
                    Log.e("API", e.getMessage());
                }

                //OK lets actually do something useful

                if (InvoiceCount == 0) {
                    Success = "false";
                    ErrorMessage = "There are no invoices for your account.";
                    handler.sendEmptyMessage(0);
                    return;
                }

                for (int i = 0; i < InvoiceCount; i++) {
                    JSONObject CurrentInvoice = null;
                    try {
                        CurrentInvoice = Invoices.getJSONObject(i);
                    } catch (JSONException e1) {
                        Log.e("APIFuncs", e1.getMessage());
                    }
                    try {
                        if (CurrentInvoice.getString("type").equals("invoice"))
                            listOfInvoices.add(new Invoices(CurrentInvoice.getString("ref"),
                                    CurrentInvoice.getDouble("amount"), CurrentInvoice.getString("details"),
                                    CurrentInvoice.getLong("date")));
                    } catch (JSONException e) {
                        Log.e("APIFuncs", e.getMessage());
                    }
                }
            }

            handler.sendEmptyMessage(0);
        }
    };

    dataPreload.start();
}

From source file:cn.code.notes.gtask.data.Task.java

public void setContentByRemoteJSON(JSONObject js) {
    if (js != null) {
        try {/*ww  w.jav  a 2  s  .co  m*/
            // id
            if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
                setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
            }

            // last_modified
            if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
                setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
            }

            // name
            if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
                setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
            }

            // notes
            if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
                setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
            }

            // deleted
            if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
                setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
            }

            // completed
            if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
                setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
            }
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
            throw new ActionFailureException("fail to get task content from jsonobject");
        }
    }
}

From source file:cn.code.notes.gtask.data.Task.java

public int getSyncAction(Cursor c) {
    try {//from   w ww . j ava 2 s.  c  o  m
        JSONObject noteInfo = null;
        if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
            noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        }

        if (noteInfo == null) {
            Log.w(TAG, "it seems that note meta has been deleted");
            return SYNC_ACTION_UPDATE_REMOTE;
        }

        if (!noteInfo.has(NoteColumns.ID)) {
            Log.w(TAG, "remote note id seems to be deleted");
            return SYNC_ACTION_UPDATE_LOCAL;
        }

        // validate the note id now
        if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
            Log.w(TAG, "note id doesn't match");
            return SYNC_ACTION_UPDATE_LOCAL;
        }

        if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
            // there is no local update
            if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                // no update both side
                return SYNC_ACTION_NONE;
            } else {
                // apply remote to local
                return SYNC_ACTION_UPDATE_LOCAL;
            }
        } else {
            // validate gtask id
            if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
                Log.e(TAG, "gtask id doesn't match");
                return SYNC_ACTION_ERROR;
            }
            if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                // local modification only
                return SYNC_ACTION_UPDATE_REMOTE;
            } else {
                return SYNC_ACTION_UPDATE_CONFLICT;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

    return SYNC_ACTION_ERROR;
}

From source file:curso.android.DAO.PerguntaDAO.java

public static void insertLista(JSONArray jArray) {
    Pergunta ask = null;//from  ww w.ja v a 2 s.c  o  m
    JSONObject json = null;
    try {
        for (int i = 0; i < jArray.length(); i++) {
            json = jArray.getJSONObject(i);
            ask = new Pergunta();
            ask.setAsk_id(json.getLong("id"));
            ask.setUser_id(json.getLong("user"));
            ask.setAsk_pergunta(json.getString("pergunta"));
            ask.setUser_name(json.getString("user_name"));
            ask.setStatus(json.getString("status").equals("true"));
            insert(ask);
            json = null;
            ask = null;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:net.dv8tion.jda.core.handle.MessageBulkDeleteHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long channelId = content.getLong("channel_id");

    if (api.isBulkDeleteSplittingEnabled()) {
        SocketHandler handler = api.getClient().getHandler("MESSAGE_DELETE");
        content.getJSONArray("ids").forEach(id -> {
            handler.handle(responseNumber, new JSONObject().put("d",
                    new JSONObject().put("channel_id", Long.toUnsignedString(channelId)).put("id", id)));
        });//  www  .  ja v a2  s . com
    } else {
        TextChannel channel = api.getTextChannelMap().get(channelId);
        if (channel == null) {
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug("Received a Bulk Message Delete for a TextChannel that is not yet cached.");
            return null;
        }

        if (api.getGuildLock().isLocked(channel.getGuild().getIdLong())) {
            return channel.getGuild().getIdLong();
        }

        LinkedList<String> msgIds = new LinkedList<>();
        content.getJSONArray("ids").forEach(id -> msgIds.add((String) id));
        api.getEventManager().handle(new MessageBulkDeleteEvent(api, responseNumber, channel, msgIds));
    }
    return null;
}

From source file:eu.codeplumbers.cosi.services.CosiContactService.java

public void sendChangesToCozy() {
    List<Contact> unSyncedContacts = Contact.getAllUnsynced();
    int i = 0;/*from www .ja  v  a2  s. co  m*/
    for (Contact contact : unSyncedContacts) {
        URL urlO = null;
        try {
            JSONObject jsonObject = contact.toJsonObject();

            System.out.println(jsonObject.toString());

            mBuilder.setProgress(unSyncedContacts.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new ContactSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_contacts_ongoing_sync)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                contact.setRemoteId(result);
                contact.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        } catch (IOException e) {
            e.printStackTrace();
            EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            stopSelf();
        }
        i++;
    }
}

From source file:com.newtifry.android.database.NewtifrySource.java

public void fromJSONObject(JSONObject source) throws JSONException {
    this.changeTimestamp = source.getString("updated");
    this.title = source.getString("title");
    this.serverEnabled = source.getBoolean("enabled");
    this.sourceKey = source.getString("key");
    this.serverId = source.getLong("id");
}