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:org.pixmob.droidlink.sync.SyncAdapter.java

private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider,
        SyncResult syncResult, boolean fullSync) {
    // Prepare the query.
    final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?";
    final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE),
            String.valueOf(EventsContract.PENDING_DELETE_STATE) };

    // Get local data to sync.
    final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8);
    final Set<String> eventsToDelete = new HashSet<String>(4);
    Cursor c = null;// www. j  a  va  2  s.  c  o  m
    try {
        c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null);

        final int idIdx = c.getColumnIndexOrThrow(_ID);
        final int typeIdx = c.getColumnIndexOrThrow(TYPE);
        final int createdIdx = c.getColumnIndexOrThrow(CREATED);
        final int numberIdx = c.getColumnIndexOrThrow(NUMBER);
        final int nameIdx = c.getColumnIndexOrThrow(NAME);
        final int messageIdx = c.getColumnIndexOrThrow(MESSAGE);
        final int stateIdx = c.getColumnIndexOrThrow(STATE);

        while (c.moveToNext()) {
            final String eventId = c.getString(idIdx);
            final int eventState = c.getInt(stateIdx);

            if (EventsContract.PENDING_UPLOAD_STATE == eventState) {
                // This is a newly created event.
                final JSONObject event = new JSONObject();
                try {
                    event.put("deviceId", client.getDeviceId());
                    event.put("created", c.getLong(createdIdx));
                    event.put("type", c.getInt(typeIdx));
                    event.put("number", c.getString(numberIdx));
                    event.put("name", c.getString(nameIdx));
                    event.put("message", c.getString(messageIdx));
                } catch (JSONException e) {
                    Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e);
                    syncResult.stats.numSkippedEntries++;
                    continue;
                }
                eventsToUpload.put(eventId, event);
            } else if (EventsContract.PENDING_DELETE_STATE == eventState) {
                // The user wants this event to be deleted.
                eventsToDelete.add(eventId);
            }
        }
    } catch (RemoteException e) {
        Log.e(TAG, "Failed to get events: cannot sync", e);
        syncResult.stats.numIoExceptions++;
    } finally {
        if (c != null) {
            c.close();
            c = null;
        }
    }

    final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32);
    final ContentValues values = new ContentValues(8);

    if (eventsToDelete.isEmpty()) {
        Log.i(TAG, "No events to delete");
    } else {
        Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete");
    }

    // Delete events on the remote server.
    for (final String eventId : eventsToDelete) {
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Deleting event: " + eventId);
        }

        try {
            client.delete("/events/" + eventId);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        } catch (IOException e) {
            Log.e(TAG, "Event deletion error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    if (fullSync) {
        // Get all events from the remote server.
        final JSONArray events;
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Fetching events from the remote server");
        }
        try {
            events = client.getAsArray("/events");
        } catch (IOException e) {
            Log.e(TAG, "Event listing error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }

        final int eventsLen = events != null ? events.length() : 0;
        if (eventsLen == 0) {
            Log.i(TAG, "No events from the remote server");
        } else {
            Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server");
        }

        // Build a collection with local event identifiers.
        // This collection will be used to identify which events have
        // been deleted on the remote server.
        final Set<String> localEventIds;
        try {
            c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?",
                    new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null);
            localEventIds = new HashSet<String>(c.getCount());

            final int idIdx = c.getColumnIndexOrThrow(_ID);
            while (c.moveToNext()) {
                final String eventId = c.getString(idIdx);
                localEventIds.add(eventId);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Failed to get events from local database", e);
            syncResult.stats.numIoExceptions++;
            return;
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        String newEventId = null;
        int newEventCount = 0;

        // Reconcile remote events with local events.
        for (int i = 0; i < eventsLen; ++i) {
            String eventId = null;
            try {
                final JSONObject event = events.getJSONObject(i);
                eventId = event.getString("id");

                // Check if this event exists in the local database.
                if (localEventIds.contains(eventId)) {
                    // Found the event: update it.
                    values.clear();
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Updating event in local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withExpectedCount(1).withValues(values).build());
                    syncResult.stats.numUpdates++;
                } else {
                    // The event was not found: insert it.
                    values.clear();
                    values.put(_ID, eventId);
                    values.put(DEVICE_ID, event.getString("deviceId"));
                    values.put(CREATED, event.getLong("created"));
                    values.put(TYPE, event.getInt("type"));
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));
                    values.put(STATE, EventsContract.UPLOADED_STATE);

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Adding event to local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withValues(values).build());
                    syncResult.stats.numInserts++;

                    ++newEventCount;
                    if (newEventId == null) {
                        newEventId = eventId;
                    }
                }

                // This event now exists in the local database:
                // remove its identifier from this collection as we
                // don't want to delete it.
                localEventIds.remove(eventId);
            } catch (JSONException e) {
                Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e);
                syncResult.stats.numSkippedEntries++;
                continue;
            }
        }

        // The remaining event identifiers was removed on the remote
        // server: there are still present in the local database. These
        // events are now being deleted.
        for (final String eventId : localEventIds) {
            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        }

        try {
            provider.applyBatch(batch);
        } catch (Exception e) {
            Log.e(TAG, "Database error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
        batch.clear();

        if (newEventCount > 1) {
            newEventId = null;
        }
        if (newEventCount != 0) {
            startSyncNotificationService(newEventCount, newEventId);
        }
    }

    final int numEventsToUpload = eventsToUpload.size();
    if (numEventsToUpload == 0) {
        Log.i(TAG, "No events to upload");
    } else {
        Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload");
    }

    // Send local events to the remote server.
    for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) {
        final String eventId = entry.getKey();

        if (DEVELOPER_MODE) {
            Log.d(TAG, "Uploading event: " + eventId);
        }

        final JSONObject event = entry.getValue();
        try {
            client.put("/events/" + eventId, event);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Updating event state to UPLOADED: " + eventId);
            }
            values.clear();
            values.put(STATE, EventsContract.UPLOADED_STATE);
            batch.add(ContentProviderOperation
                    .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values)
                    .withExpectedCount(1).build());
            syncResult.stats.numUpdates++;

            Log.i(TAG, "Event upload successful: " + eventId);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                Log.e(TAG, "Device not found: cannot sync", e);
                registerDevice();
            } else {
                Log.e(TAG, "Network error: cannot sync", e);
            }
            syncResult.stats.numIoExceptions++;
            return;
        } catch (IOException e) {
            Log.e(TAG, "Event upload error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    final SharedPreferences.Editor prefsEditor = prefs.edit();
    final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty();
    if (syncRequired) {
        // Generate an unique sync token: the server will send this token to
        // every devices. If this token is received on this device, the sync
        // will not start.
        final String syncToken = UUID.randomUUID().toString();
        prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken);
        Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);

        // Sync user devices.
        try {
            final JSONObject data = new JSONObject();
            data.put("token", syncToken);
            client.post("/devices/" + client.getDeviceId() + "/sync", data);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                registerDevice();
            }
        } catch (IOException e) {
            Log.e(TAG, "Device sync error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        } catch (JSONException e) {
            Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
    }

    // Store sync time.
    prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis());
    Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);
}

From source file:com.asd.littleprincesbeauty.data.SqlNote.java

public boolean setContent(JSONObject js) {
    try {//from ww  w.ja v  a 2  s.c  o m
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            Log.w(TAG, "cannot set system folder");
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            // for folder we can only update the snnipet and type
            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
            JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
            long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
            if (mIsCreate || mId != id) {
                mDiffNoteValues.put(NoteColumns.ID, id);
            }
            mId = id;

            long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
            if (mIsCreate || mAlertDate != alertDate) {
                mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
            }
            mAlertDate = alertDate;

            int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID)
                    : ResourceParser.getDefaultBgId(mContext);
            if (mIsCreate || mBgColorId != bgColorId) {
                mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
            }
            mBgColorId = bgColorId;

            long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mCreatedDate != createDate) {
                mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
            }
            mCreatedDate = createDate;

            int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT)
                    : 0;
            if (mIsCreate || mHasAttachment != hasAttachment) {
                mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
            }
            mHasAttachment = hasAttachment;

            long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mModifiedDate != modifiedDate) {
                mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
            }
            mModifiedDate = modifiedDate;

            long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0;
            if (mIsCreate || mParentId != parentId) {
                mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
            }
            mParentId = parentId;

            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;

            int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
                    : AppWidgetManager.INVALID_APPWIDGET_ID;
            if (mIsCreate || mWidgetId != widgetId) {
                mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
            }
            mWidgetId = widgetId;

            int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE)
                    : Notes.TYPE_WIDGET_INVALIDE;
            if (mIsCreate || mWidgetType != widgetType) {
                mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
            }
            mWidgetType = widgetType;

            long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID)
                    ? note.getLong(NoteColumns.ORIGIN_PARENT_ID)
                    : 0;
            if (mIsCreate || mOriginParent != originParent) {
                mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
            }
            mOriginParent = originParent;

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                SqlData sqlData = null;
                if (data.has(DataColumns.ID)) {
                    long dataId = data.getLong(DataColumns.ID);
                    for (SqlData temp : mDataList) {
                        if (dataId == temp.getId()) {
                            sqlData = temp;
                        }
                    }
                }

                if (sqlData == null) {
                    sqlData = new SqlData(mContext);
                    mDataList.add(sqlData);
                }

                sqlData.setContent(data);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:drusy.ui.panels.SwitchStatePanel.java

public void addUsersForSwitchIdAndHostname(int id, final String hostname) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_SWITCH_ID.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting Switch information",
            false);//from   ww  w .j av a2 s.c o m

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONObject result = obj.getJSONObject("result");
                long txBytes = result.getLong("tx_bytes_rate");
                long rxBytes = result.getLong("rx_bytes_rate");

                addUser("", hostname, txBytes, rxBytes);
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Switch information", msg);
            }

            setVisible(true);
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Switch information", ex.getMessage());
        }
    });
}

From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

private void createFilteredDeck(JSONArray delays, Object[] terms, Boolean resched) {
    JSONObject dyn;/*from  w ww . j ava  2  s  .c o m*/
    if (AnkiDroidApp.colIsOpen()) {
        Collection col = AnkiDroidApp.getCol();
        try {
            String deckName = col.getDecks().current().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) {
                    StyledDialog.Builder builder = new StyledDialog.Builder(getActivity());
                    builder.setMessage(R.string.custom_study_deck_exists);
                    builder.setNegativeButton(getResources().getString(R.string.cancel), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //
                        }
                    });
                    builder.create().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 did = col.getDecks().newDyn(customStudyDeck);
                dyn = col.getDecks().get(did);
            }
            // and then set various options
            dyn.put("delays", delays);
            JSONArray ar = dyn.getJSONArray("terms");
            ar.getJSONArray(0).put(0,
                    new StringBuilder("deck:\"").append(deckName).append("\" ").append(terms[0]).toString());
            ar.getJSONArray(0).put(1, terms[1]);
            ar.getJSONArray(0).put(2, terms[2]);
            dyn.put("resched", resched);

            if (mFragmented) {
                Bundle config = new Bundle();
                config.putString("searchSuffix", "'deck:" + dyn.getString("name") + "'");
                initAllContentViews(getLayoutInflater(config));
                finishCongrats();
            } else {
                // Load a new fragment with the filtered deck view. The config passed is null, so it uses the
                // current deck. The deck we just created is internally set as the current deck.
                ((StudyOptionsActivity) getActivity()).loadContent(false, null);
            }

            // Initial rebuild
            mProgressDialog = StyledProgressDialog.show(getActivity(), "",
                    getResources().getString(R.string.rebuild_custom_study_deck), true);
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REBUILD_CRAM, mRebuildCustomStudyListener,
                    new DeckTask.TaskData(AnkiDroidApp.getCol(), AnkiDroidApp.getCol().getDecks().selected(),
                            mFragmented));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.jennifer.ui.chart.grid.DateGrid.java

private void initDomain() {

    if (has("target") && !has("domain")) {

        if (options.get("target") instanceof String) {
            JSONArray list = new JSONArray();
            list.put(options.getString("target"));
            options.put("target", list);
        }//  w w w.j  a  v a 2  s .  co  m

        JSONArray target = (JSONArray) options.getJSONArray("target");
        JSONArray domain = new JSONArray();
        JSONArray data = chart.data();

        long min = 0;
        long max = 0;

        boolean hasMin = options.has("min");
        boolean hasMax = options.has("max");

        for (int i = 0, len = target.length(); i < len; i++) {
            String key = target.getString(i);

            for (int index = 0, dataLength = data.length(); index < dataLength; index++) {
                JSONObject row = data.getJSONObject(index);

                long value = 0;

                if (row.get(key) instanceof Date) {
                    value = ((Date) row.get(key)).getTime();
                } else {
                    value = row.getLong(key);
                }

                if (!hasMin) {
                    min = value;
                    hasMin = true;
                } else if (min > value)
                    min = value;

                if (!hasMax) {
                    max = value;
                    hasMax = true;
                } else if (max < value)
                    max = value;
            }

        }

        options.put("max", max);
        options.put("min", min);

        domain.put(min).put(max);

        if (options.optBoolean("reverse", false)) {
            JSONUtil.reverse(domain);
        }

        options.put("domain", domain);

    }

}

From source file:com.github.koraktor.steamcondenser.community.AppNews.java

/**
 * Creates a new instance of an AppNews news item with the given data
 *
 * @param appId The unique Steam Application ID of the game (e.g.
 *        <code>440</code> for Team Fortress 2). See
 *        http://developer.valvesoftware.com/wiki/Steam_Application_IDs for
 *        all application IDs//from  ww  w  . j  a  v  a 2 s. com
 * @param newsData The news data extracted from JSON
 * @throws WebApiException if the JSON data cannot be parsed
 */
private AppNews(int appId, JSONObject newsData) throws WebApiException {
    try {
        this.appId = appId;
        this.author = newsData.getString("author");
        this.contents = newsData.getString("contents").trim();
        this.date = new Date(newsData.getLong("date"));
        this.external = newsData.getBoolean("is_external_url");
        this.feedLabel = newsData.getString("feedlabel");
        this.feedName = newsData.getString("feedname");
        this.gid = newsData.getLong("gid");
        this.title = newsData.getString("title");
        this.url = newsData.getString("url");
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}

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

@Override
protected Long handleInternally(JSONObject content) {
    final long channelId = content.getLong("channel_id");
    MessageChannel channel = api.getTextChannelMap().get(channelId);
    if (channel == null)
        channel = api.getPrivateChannelMap().get(channelId);
    if (channel == null)
        channel = api.getFakePrivateChannelMap().get(channelId);
    if (channel == null && api.getAccountType() == AccountType.CLIENT)
        channel = api.asClient().getGroupById(channelId);
    if (channel == null)
        return null; //We don't have the channel cached yet. We chose not to cache this event
                     // because that happen very often and could easily fill up the EventCache if
                     // we, for some reason, never get the channel. Especially in an active channel.

    if (channel instanceof TextChannel) {
        final long guildId = ((TextChannel) channel).getGuild().getIdLong();
        if (api.getGuildLock().isLocked(guildId))
            return guildId;
    }//from  w  w w  . j  a v a  2s. c  o  m

    final long userId = content.getLong("user_id");
    User user;
    if (channel instanceof PrivateChannel)
        user = ((PrivateChannel) channel).getUser();
    else if (channel instanceof Group)
        user = ((GroupImpl) channel).getUserMap().get(userId);
    else
        user = api.getUserMap().get(userId);

    if (user == null)
        return null; //Just like in the comment above, if for some reason we don't have the user for some reason
                     // then we will just throw the event away.

    OffsetDateTime timestamp = Instant.ofEpochSecond(content.getInt("timestamp")).atOffset(ZoneOffset.UTC);
    api.getEventManager().handle(new UserTypingEvent(api, responseNumber, user, channel, timestamp));
    return null;
}

From source file:com.example.android.samplesync.client.RawContact.java

/**
 * Creates and returns an instance of the RawContact from the provided JSON data.
 *
 * @param user The JSONObject containing user data
 * @return user The new instance of Sample RawContact created from the JSON data.
 *//*from w w  w  .ja va2  s . c  om*/
public static RawContact valueOf(JSONObject contact) {

    try {
        final String userName = !contact.isNull("u") ? contact.getString("u") : null;
        final int serverContactId = !contact.isNull("i") ? contact.getInt("i") : -1;
        // If we didn't get either a username or serverId for the contact, then
        // we can't do anything with it locally...
        if ((userName == null) && (serverContactId <= 0)) {
            throw new JSONException("JSON contact missing required 'u' or 'i' fields");
        }

        final int rawContactId = !contact.isNull("c") ? contact.getInt("c") : -1;
        final String firstName = !contact.isNull("f") ? contact.getString("f") : null;
        final String lastName = !contact.isNull("l") ? contact.getString("l") : null;
        final String cellPhone = !contact.isNull("m") ? contact.getString("m") : null;
        final String officePhone = !contact.isNull("o") ? contact.getString("o") : null;
        final String homePhone = !contact.isNull("h") ? contact.getString("h") : null;
        final String email = !contact.isNull("e") ? contact.getString("e") : null;
        final String status = !contact.isNull("s") ? contact.getString("s") : null;
        final String avatarUrl = !contact.isNull("a") ? contact.getString("a") : null;
        final boolean deleted = !contact.isNull("d") ? contact.getBoolean("d") : false;
        final long syncState = !contact.isNull("x") ? contact.getLong("x") : 0;
        return new RawContact(userName, null, firstName, lastName, cellPhone, officePhone, homePhone, email,
                status, avatarUrl, deleted, serverContactId, rawContactId, syncState, false);
    } catch (final Exception ex) {
        Log.i(TAG, "Error parsing JSON contact object" + ex.toString());
    }
    return null;
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

private void saveUserData(JSONObject user) throws JSONException {

    userId = user.getLong("id_user");

    OpencrxUtilities.INSTANCE.setDefaultAssignedUser(userId);

}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/** Create a task container for the given RtmTaskSeries
 * @throws JSONException/*from   w w w . j  a va  2 s  . co  m*/
 * @throws IOException
 * @throws ApiServiceException */
private OpencrxTaskContainer parseRemoteTask(JSONObject remoteTask)
        throws JSONException, ApiServiceException, IOException {

    String resourceId = Preferences.getStringValue(OpencrxUtilities.PREF_RESOURCE_ID);

    String crxId = remoteTask.getString("repeating_value");

    JSONArray labels = invoker.resourcesShowForTask(crxId);

    int secondsSpentOnTask = invoker.getSecondsSpentOnTask(crxId, resourceId);

    Task task = new Task();
    ArrayList<Metadata> metadata = new ArrayList<Metadata>();

    if (remoteTask.has("task"))
        remoteTask = remoteTask.getJSONObject("task");

    task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title")));
    task.setValue(Task.NOTES, remoteTask.getString("detailedDescription"));
    task.setValue(Task.CREATION_DATE,
            ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0));
    task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.ELAPSED_SECONDS, secondsSpentOnTask);
    task.setValue(Task.MODIFICATION_DATE, remoteTask.getLong("modifiedAt"));

    long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0);
    if (remoteTask.optInt("all_day", 0) == 1)
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate));
    else
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate));
    task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star"));

    for (int i = 0; i < labels.length(); i++) {
        JSONObject label = labels.getJSONObject(i);

        Metadata tagData = new Metadata();
        tagData.setValue(Metadata.KEY, OpencrxDataService.TAG_KEY);
        tagData.setValue(OpencrxDataService.TAG, label.getString("name"));
        metadata.add(tagData);
    }

    OpencrxTaskContainer container = new OpencrxTaskContainer(task, metadata, remoteTask);

    return container;
}