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.qualisys.parkassist.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>//from   www .  ja  v a  2s  . co  m
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_DATETIME = "dt";
    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
    String cityName = cityJson.getString(OWM_CITY_NAME);
    JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getLong(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getLong(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());
    String[] resultStrs = new String[numDays];

    for (int i = 0; i < weatherArray.length(); i++) {
        // These are the values that will be collected.

        long dateTime;
        double pressure;
        int humidity;
        double windSpeed;
        double windDirection;

        double high;
        double low;

        String description;
        int weatherId;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        pressure = dayForecast.getDouble(OWM_PRESSURE);
        humidity = dayForecast.getInt(OWM_HUMIDITY);
        windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
        windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

        // Description is in a child array called "weather", which is 1 element long.
        // That element also contains a weather code.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);
        weatherId = weatherObject.getInt(OWM_WEATHER_ID);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);

        ContentValues weatherValues = new ContentValues();
        /*
                    weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID);
                    weatherValues.put(WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
                    weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
                    weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
                    weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
                    weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
                    weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
                    weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
                    weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
                    weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);
        */
        cVVector.add(weatherValues);

        String highAndLow = formatHighLows(high, low);
        String day = getReadableDateString(dateTime);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    ContentValues[] contentValuesToBulkInsert = new ContentValues[cVVector.size()];
    cVVector.toArray(contentValuesToBulkInsert);
    /*
    mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, contentValuesToBulkInsert);
    */
    return resultStrs;
}

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

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiNoteService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // delete all local notes
    new Delete().from(Note.class).execute();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/request/note/cosiall/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();// w  w w .  j a  va2  s  .com

    if (isNetworkAvailable()) {
        try {
            URL urlO = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // read the response
            int status = conn.getResponseCode();
            InputStream in = null;

            if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                in = conn.getErrorStream();
            } else {
                in = conn.getInputStream();
            }

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

            JSONArray jsonArray = new JSONArray(result);

            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Note note = Note.getByRemoteId(noteJson.get("_id").toString());

                    if (note == null) {
                        note = new Note(noteJson);
                    } else {
                        boolean versionIncremented = note.getVersion() < Integer
                                .valueOf(noteJson.getString("version"));

                        int modifiedOnServer = DateUtils.compareDateStrings(
                                Long.valueOf(note.getLastModificationValueOf()),
                                noteJson.getLong("lastModificationValueOf"));

                        if (versionIncremented || modifiedOnServer == -1) {
                            note.setTitle(noteJson.getString("title"));
                            note.setContent(noteJson.getString("content"));
                            note.setCreationDate(noteJson.getString("creationDate"));
                            note.setLastModificationDate(noteJson.getString("lastModificationDate"));
                            note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf"));
                            note.setParentId(noteJson.getString("parent_id"));
                            // TODO: 10/3/16
                            // handle note paths
                            note.setPath(noteJson.getString("path"));
                            note.setVersion(Integer.valueOf(version));
                        }

                    }

                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mBuilder.setContentText("Getting note : " + note.getTitle());
                    mNotifyManager.notify(notification_id, mBuilder.build());

                    EventBus.getDefault()
                            .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle()));
                    note.save();
                }
            } else {
                EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            }

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

            mNotifyManager.cancel(notification_id);
            EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK"));
        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP0706xxDataImpl.java

public static EEP0706xxDataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP0706xxDataImpl(Float.MIN_VALUE, -1, null);

    try {//from   www.j a v a2  s . c o  m
        float supplyVoltage = (float) lastKnownData.getDouble("supplyVoltage");
        int illumination = lastKnownData.getInt("illumination");
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP0706xxDataImpl(supplyVoltage, illumination, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP0706xxDataImpl(Float.MIN_VALUE, -1, null);
    }
}

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

@Override
protected Long handleInternally(JSONObject content) {
    final long id = content.getLong("id");
    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);

    //If the event is attempting to mark the guild as unavailable, but it is already unavailable,
    // ignore the event
    if ((guild == null || !guild.isAvailable()) && content.has("unavailable")
            && content.getBoolean("unavailable"))
        return null;

    if (api.getGuildLock().isLocked(id))
        return id;

    if (content.has("unavailable") && content.getBoolean("unavailable")) {
        guild.setAvailable(false);/*  w w w.j  a  v a  2s  .  c  o  m*/
        api.getEventManager().handle(new GuildUnavailableEvent(api, responseNumber, guild));
        return null;
    }

    final TLongObjectMap<AudioManagerImpl> audioManagerMap = api.getAudioManagerMap();
    final AudioManagerImpl manager = audioManagerMap.remove(id); // remove manager from central map to avoid old guild references
    if (manager != null) // close existing audio connection if needed
        manager.closeAudioConnection(ConnectionStatus.DISCONNECTED_REMOVED_FROM_GUILD);

    //cleaning up all users that we do not share a guild with anymore
    // Anything left in memberIds will be removed from the main userMap
    //Use a new HashSet so that we don't actually modify the Member map so it doesn't affect Guild#getMembers for the leave event.
    TLongSet memberIds = new TLongHashSet(guild.getMembersMap().keySet());
    for (Guild guildI : api.getGuilds()) {
        GuildImpl g = (GuildImpl) guildI;
        if (g.equals(guild))
            continue;

        for (TLongIterator it = memberIds.iterator(); it.hasNext();) {

            if (g.getMembersMap().containsKey(it.next()))
                it.remove();
        }
    }

    //If we are a client account, be sure to not remove any users from the cache that are Friends.
    // Remember, everything left in memberIds is removed from the userMap
    if (api.getAccountType() == AccountType.CLIENT) {
        TLongObjectMap<Relationship> relationships = ((JDAClientImpl) api.asClient()).getRelationshipMap();
        for (TLongIterator it = memberIds.iterator(); it.hasNext();) {
            Relationship rel = relationships.get(it.next());
            if (rel != null && rel.getType() == RelationshipType.FRIEND)
                it.remove();
        }
    }

    long selfId = api.getSelfUser().getIdLong();
    memberIds.forEach(memberId -> {
        if (memberId == selfId)
            return true; // don't remove selfUser from cache
        UserImpl user = (UserImpl) api.getUserMap().remove(memberId);
        if (user.hasPrivateChannel()) {
            PrivateChannelImpl priv = (PrivateChannelImpl) user.getPrivateChannel();
            user.setFake(true);
            priv.setFake(true);
            api.getFakeUserMap().put(user.getIdLong(), user);
            api.getFakePrivateChannelMap().put(priv.getIdLong(), priv);
        } else if (api.getAccountType() == AccountType.CLIENT) {
            //While the user might not have a private channel, if this is a client account then the user
            // could be in a Group, and if so we need to change the User object to be fake and
            // place it in the FakeUserMap
            for (Group grp : api.asClient().getGroups()) {
                if (grp.getNonFriendUsers().contains(user)) {
                    user.setFake(true);
                    api.getFakeUserMap().put(user.getIdLong(), user);
                    break; //Breaks from groups loop, not memberIds loop
                }
            }
        }

        return true;
    });

    api.getGuildMap().remove(guild.getIdLong());
    guild.getTextChannels().forEach(chan -> api.getTextChannelMap().remove(chan.getIdLong()));
    guild.getVoiceChannels().forEach(chan -> api.getVoiceChannelMap().remove(chan.getIdLong()));
    api.getEventManager().handle(new GuildLeaveEvent(api, responseNumber, guild));
    return null;
}

From source file:org.tomdroid.sync.web.SnowySyncService.java

@Override
protected void getNotesForSync(final boolean push) {
    this.push = push;

    // start loading snowy notes
    setSyncProgress(0);/*w  ww  .  ja  va2  s  .  c om*/
    this.lastGUID = null;

    TLog.v(TAG, "Loading Snowy notes");

    final String userRef = Preferences.getString(Preferences.Key.SYNC_SERVER_USER_API);

    syncInThread(new Runnable() {

        public void run() {

            OAuthConnection auth = getAuthConnection();
            latestRemoteRevision = (int) Preferences.getLong(Preferences.Key.LATEST_SYNC_REVISION);

            try {
                TLog.v(TAG, "contacting " + userRef);
                String rawResponse = auth.get(userRef);
                if (cancelled) {
                    doCancel();
                    return;
                }
                if (rawResponse == null) {
                    sendMessage(CONNECTING_FAILED);
                    setSyncProgress(100);
                    return;
                }

                setSyncProgress(30);

                try {
                    JSONObject response = new JSONObject(rawResponse);

                    // get notes list without content, to check for revision

                    String notesUrl = response.getJSONObject("notes-ref").getString("api-ref");
                    rawResponse = auth.get(notesUrl);
                    response = new JSONObject(rawResponse);

                    latestLocalRevision = (Long) Preferences.getLong(Preferences.Key.LATEST_SYNC_REVISION);

                    setSyncProgress(35);

                    latestRemoteRevision = response.getLong("latest-sync-revision");
                    sendMessage(LATEST_REVISION, (int) latestRemoteRevision, 0);
                    TLog.d(TAG, "old latest sync revision: {0}, remote latest sync revision: {1}",
                            latestLocalRevision, latestRemoteRevision);

                    Cursor newLocalNotes = NoteManager.getNewNotes(activity);

                    if (latestRemoteRevision <= latestLocalRevision && newLocalNotes.getCount() == 0) { // same sync revision + no new local notes = no need to sync
                        TLog.v(TAG, "old sync revision on server, cancelling");
                        finishSync(true);
                        return;
                    }

                    // don't get notes if older revision - only pushing notes

                    if (push && latestRemoteRevision <= latestLocalRevision) {
                        TLog.v(TAG, "old sync revision on server, pushing new notes");

                        JSONArray notes = response.getJSONArray("notes");
                        List<String> notesList = new ArrayList<String>();
                        for (int i = 0; i < notes.length(); i++)
                            notesList.add(notes.getJSONObject(i).optString("guid"));
                        prepareSyncableNotes(newLocalNotes);
                        setSyncProgress(50);
                        return;
                    }

                    // get notes list with content to find changes

                    TLog.v(TAG, "contacting " + notesUrl);
                    sendMessage(SYNC_CONNECTED);
                    rawResponse = auth.get(notesUrl + "?include_notes=true");
                    if (cancelled) {
                        doCancel();
                        return;
                    }
                    response = new JSONObject(rawResponse);
                    latestRemoteRevision = response.getLong("latest-sync-revision");
                    sendMessage(LATEST_REVISION, (int) latestRemoteRevision, 0);

                    JSONArray notes = response.getJSONArray("notes");
                    setSyncProgress(50);

                    TLog.v(TAG, "number of notes: {0}", notes.length());

                    ArrayList<Note> notesList = new ArrayList<Note>();

                    for (int i = 0; i < notes.length(); i++)
                        notesList.add(new Note(notes.getJSONObject(i)));

                    if (cancelled) {
                        doCancel();
                        return;
                    }

                    // close cursor
                    newLocalNotes.close();
                    prepareSyncableNotes(notesList);

                } catch (JSONException e) {
                    TLog.e(TAG, e, "Problem parsing the server response");
                    sendMessage(PARSING_FAILED,
                            ErrorList.createErrorWithContents("JSON parsing", "json", e, rawResponse));
                    setSyncProgress(100);
                    return;
                }
            } catch (java.net.UnknownHostException e) {
                TLog.e(TAG, "Internet connection not available");
                sendMessage(NO_INTERNET);
                setSyncProgress(100);
                return;
            }
            if (cancelled) {
                doCancel();
                return;
            }
            if (isSyncable())
                finishSync(true);
        }
    });
}

From source file:org.tomdroid.sync.web.SnowySyncService.java

@Override
public void pushNotes(final ArrayList<Note> notes) {
    if (notes.size() == 0)
        return;//from w  w  w  .  j  a  v  a2s  .co  m
    if (cancelled) {
        doCancel();
        return;
    }
    final String userRef = Preferences.getString(Preferences.Key.SYNC_SERVER_USER_API);

    final long newRevision = Preferences.getLong(Preferences.Key.LATEST_SYNC_REVISION) + 1;

    syncInThread(new Runnable() {
        public void run() {
            OAuthConnection auth = getAuthConnection();
            try {
                TLog.v(TAG, "pushing {0} notes to remote service, sending rev #{1}", notes.size(), newRevision);
                String rawResponse = auth.get(userRef);
                if (cancelled) {
                    doCancel();
                    return;
                }
                try {
                    TLog.v(TAG, "creating JSON");

                    JSONObject data = new JSONObject();
                    data.put("latest-sync-revision", newRevision);
                    JSONArray Jnotes = new JSONArray();
                    for (Note note : notes) {
                        JSONObject Jnote = new JSONObject();
                        Jnote.put("guid", note.getGuid());

                        if (note.getTags().contains("system:deleted")) // deleted note
                            Jnote.put("command", "delete");
                        else { // changed note
                            Jnote.put("title", note.getTitle());
                            Jnote.put("note-content", note.getXmlContent());
                            Jnote.put("note-content-version", "0.1");
                            Jnote.put("last-change-date", note.toTomboyFormat(note.getLastChangeDate()));
                            Jnote.put("create-date", note.toTomboyFormat(note.getCreateDate()));
                            Jnote.put("last-metadata-change-date",
                                    note.toTomboyFormat(note.getLastChangeDate())); // TODO: is this different?
                        }
                        Jnotes.put(Jnote);
                    }
                    data.put("note-changes", Jnotes);

                    JSONObject response = new JSONObject(rawResponse);
                    if (cancelled) {
                        doCancel();
                        return;
                    }
                    String notesUrl = response.getJSONObject("notes-ref").getString("api-ref");

                    TLog.v(TAG, "put url: {0}", notesUrl);

                    if (cancelled) {
                        doCancel();
                        return;
                    }

                    TLog.v(TAG, "pushing data to remote service: {0}", data.toString());
                    response = new JSONObject(auth.put(notesUrl, data.toString()));

                    TLog.v(TAG, "put response: {0}", response.toString());
                    latestRemoteRevision = response.getLong("latest-sync-revision");
                    sendMessage(LATEST_REVISION, (int) latestRemoteRevision, 0);

                } catch (JSONException e) {
                    TLog.e(TAG, e, "Problem parsing the server response");
                    sendMessage(NOTE_PUSH_ERROR,
                            ErrorList.createErrorWithContents("JSON parsing", "json", e, rawResponse));
                    return;
                }
            } catch (java.net.UnknownHostException e) {
                TLog.e(TAG, "Internet connection not available");
                sendMessage(NO_INTERNET);
                return;
            }
            // success, finish sync
            finishSync(true);
        }

    });
}

From source file:org.tomdroid.sync.web.SnowySyncService.java

public void deleteAllNotes() {

    TLog.v(TAG, "Deleting Snowy notes");

    final String userRef = Preferences.getString(Preferences.Key.SYNC_SERVER_USER_API);

    final long newRevision;

    if (latestLocalRevision > latestRemoteRevision)
        newRevision = latestLocalRevision + 1;
    else/*from www .j  av  a 2  s.com*/
        newRevision = latestRemoteRevision + 1;

    syncInThread(new Runnable() {

        public void run() {

            OAuthConnection auth = getAuthConnection();

            try {
                TLog.v(TAG, "contacting " + userRef);
                String rawResponse = auth.get(userRef);
                if (rawResponse == null) {
                    return;
                }
                try {
                    JSONObject response = new JSONObject(rawResponse);
                    String notesUrl = response.getJSONObject("notes-ref").getString("api-ref");

                    TLog.v(TAG, "contacting " + notesUrl);
                    response = new JSONObject(auth.get(notesUrl));

                    JSONArray notes = response.getJSONArray("notes");
                    setSyncProgress(50);

                    TLog.v(TAG, "number of notes: {0}", notes.length());

                    ArrayList<String> guidList = new ArrayList<String>();

                    for (int i = 0; i < notes.length(); i++) {
                        JSONObject ajnote = notes.getJSONObject(i);
                        guidList.add(ajnote.getString("guid"));
                    }

                    TLog.v(TAG, "creating JSON");

                    JSONObject data = new JSONObject();
                    data.put("latest-sync-revision", newRevision);
                    JSONArray Jnotes = new JSONArray();
                    for (String guid : guidList) {
                        JSONObject Jnote = new JSONObject();
                        Jnote.put("guid", guid);
                        Jnote.put("command", "delete");
                        Jnotes.put(Jnote);
                    }
                    data.put("note-changes", Jnotes);

                    response = new JSONObject(auth.put(notesUrl, data.toString()));

                    TLog.v(TAG, "delete response: {0}", response.toString());

                    // reset latest sync date so we can push our notes again

                    latestRemoteRevision = (int) response.getLong("latest-sync-revision");
                    Preferences.putLong(Preferences.Key.LATEST_SYNC_REVISION, latestRemoteRevision);
                    Preferences.putString(Preferences.Key.LATEST_SYNC_DATE, new Time().format3339(false));

                } catch (JSONException e) {
                    TLog.e(TAG, e, "Problem parsing the server response");
                    sendMessage(PARSING_FAILED,
                            ErrorList.createErrorWithContents("JSON parsing", "json", e, rawResponse));
                    setSyncProgress(100);
                    return;
                }
            } catch (java.net.UnknownHostException e) {
                TLog.e(TAG, "Internet connection not available");
                sendMessage(NO_INTERNET);
                setSyncProgress(100);
                return;
            }
            sendMessage(REMOTE_NOTES_DELETED);
        }
    });
}

From source file:net.netheos.pcsapi.credentials.OAuth2Credentials.java

/**
 * Calculate expiration timestamp, if not defined.
 * /*from w  w  w  .j  a  v a  2s.c  o  m*/
 * Several cases: absolute expiration time exists in json, or only relative, or no expiration.
 * 
 * @param jsonObj
 * @return expiration date, or null if none.
 */
private static Date calculateExpiresAt(JSONObject jsonObj) {
    long expiresAt_s = jsonObj.optLong(OAuth2Credentials.EXPIRES_AT, -1);
    // If nothing specified in json, check if expires_in is present:
    // this happens when token is received from oauth server
    if (expiresAt_s < 0 && jsonObj.has(OAuth2Credentials.EXPIRES_IN)) {
        long expiresIn_s = jsonObj.getLong(OAuth2Credentials.EXPIRES_IN);
        // We take a margin to be safe: it appears that some providers do NOT take any margin
        // so token will not be early refreshed
        if (expiresIn_s > 6 * 60) { // should be always true
            expiresIn_s -= 5 * 60; // 5 minutes to be safe
        }
        expiresAt_s = System.currentTimeMillis() / 1000 + expiresIn_s;
    }

    if (expiresAt_s < 0) {
        return null;
    }
    return new Date(expiresAt_s * 1000);
}

From source file:com.ichi2.anki2.StudyOptionsFragment.java

private void createFilteredDeck(JSONArray delays, Object[] terms, Boolean resched) {
    JSONObject dyn;//from w  w w .j  av a2 s  . c om
    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);
            // generate cards
            finishCongrats();
            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:edu.cens.loci.classes.LociWifiFingerprint.java

@SuppressWarnings("unchecked")
public LociWifiFingerprint(String json) throws JSONException {
    JSONObject jObj = new JSONObject(json);
    this.mEnter = jObj.getLong("enter");
    this.mExit = jObj.getLong("exit");
    this.mScanCount = jObj.getInt("count");
    JSONObject jObjAPs = jObj.getJSONObject("aps");

    Iterator<String> keys = jObjAPs.keys();
    mAPs = new HashMap<String, APInfoMapItem>();
    while (keys.hasNext()) {
        String bssid = keys.next();
        mAPs.put(bssid, new APInfoMapItem(jObjAPs.getJSONObject(bssid)));
    }//from  w ww.  java2 s . c  om

    //Log.d(TAG, "constructing from json : " + this.toString());
}