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.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

/**
 * Parse the JSON formatted data, process it, then store it locally.
 *
 * @param newsJsonStr//from   w w  w  . j a v a2 s .  c  o m
 *         JSON formatted string to parse and process
 * @return number of news items processed
 *
 * @see <a href="http://blizzard.github.io/api-wow-docs/">WOW API Documentation</a>
 */
@SuppressWarnings("ConstantConditions")
private int processJsonNews(String newsJsonStr) {

    int actualInsertCount = 0;
    // check to see if there is anything to do
    if (newsJsonStr == null)
        return 0;

    // These are the item keys that we want to extra from the JSON object

    // Guild data keys
    final String WOW_GUILD_LAST_MODIFIED = "lastModified";
    final String WOW_GUILD_NAME = "name";
    final String WOW_GUILD_REALM = "realm";
    final String WOW_GUILD_NEWS = "news";

    // News Item data keys
    final String WOW_NEWS_TYPE = "type";
    final String WOW_NEWS_TIMESTAMP = "timestamp";
    final String WOW_NEWS_CHARACTER = "character";
    final String WOW_NEWS_ITEM_ID = "itemId";
    final String WOW_NEWS_ACHIEVEMENT = "achievement";

    //Achievement data keys
    final String WOW_ACHIEVEMENT_DESCRIPTION = "description";
    final String WOW_ACHIEVEMENT_ICON = "icon";
    final String WOW_ACHIEVEMENT_TITLE = "title";

    // store the last sync timestamp and use it to keep the processing time to a minimum
    long mSavedTimestamp;

    // keep track of if we sent out a favorite character notification
    // this round... it will just send one and only the first one
    boolean isNotified = false;

    // keep track of if we sent a new record notification this round
    boolean alreadyNotified = false;

    // the region is not returned in the JSON data
    // so we use the same preference data that was used to get the JSON
    String region = Utility.getRegion(mContext);
    try {

        // create JSON object for the string
        JSONObject newsJson = new JSONObject(newsJsonStr);

        // create a news Item object to hold the relevant data from the JSON object
        GuildViewerNewsItem currentNews = new GuildViewerNewsItem();

        // setup the guild object
        GuildViewerGuild guild = new GuildViewerGuild();
        currentNews.setGuild(guild);
        guild.setName(newsJson.getString(WOW_GUILD_NAME));
        guild.setRegion(region);
        guild.setRealm(newsJson.getString(WOW_GUILD_REALM));

        // setup data used for notifications
        guild.setLastModified(newsJson.getLong(WOW_GUILD_LAST_MODIFIED));
        mSavedTimestamp = guild.getLastModified(); // default to WOW's modified date
        //Log.v(LOG_TAG, guild.toString());

        // now process the array of news items
        JSONArray newsArray = newsJson.getJSONArray(WOW_GUILD_NEWS);
        //Log.v(LOG_TAG, "Number of News Items in JSON:" + Integer.toString(newsArray.length()));

        // get the timestamps for both the last sync and for the furthest date that
        // we will process the news ... this allows us to only  process relevant news items
        //long lastNotificationTimestamp = Utility.getPreferenceForLastNotificationDate(mContext);
        long oldestNewsTimestamp = Utility
                .getTimestampForDaysFromNow(Utility.getPreferenceForDaysToKeepNews(mContext));

        // Insert the new news items into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(newsArray.length());
        for (int i = 0; i < newsArray.length(); i++) {

            // get the news item object from the JSON object
            JSONObject jsonNewsItem = newsArray.getJSONObject(i);

            // The only guaranteed fields from Blizzard are type and timestamp
            currentNews.setTimestamp(jsonNewsItem.getLong(WOW_NEWS_TIMESTAMP));

            // we can quit if we find one that is less than our last timestamp
            // because we know that we get the news items in date descending order
            // this will save us a lot of processing time and effort
            if (currentNews.getTimestamp() < oldestNewsTimestamp) {
                //Log.v(LOG_TAG, "Stop processing. Current News is complete.");
                break;
            }

            // format the dateTime string
            currentNews.setListFormattedDate(Utility.getReadableDateString(mContext, currentNews.getTimestamp(),
                    R.string.format_timestamp_list_view));

            // get the news item type because we need to know this to process correctly
            currentNews.setType(jsonNewsItem.getString(WOW_NEWS_TYPE));

            // character name may or may not be available in JSON object
            try {
                currentNews.setCharacter(jsonNewsItem.getString(WOW_NEWS_CHARACTER));
            } catch (JSONException e) {
                // This isn't a real exception because the character name is optional
                // so catch it and keep it and reset the character name to be stored
                currentNews.setCharacter("");
            }

            // item id may or may not be available in JSON object
            GuildViewerItem actualItem;
            try {
                // try storage first
                actualItem = checkForItemInStorage(jsonNewsItem.getLong(WOW_NEWS_ITEM_ID));
                // if not found then got to the API to get it and store it
                if (actualItem == null) {
                    actualItem = getItemFromAPI(jsonNewsItem.getLong(WOW_NEWS_ITEM_ID));
                }
                currentNews.setItem(actualItem);
            } catch (JSONException e) {
                // We really can keep moving with this exception
                // because the item id is optional so catch it and keep it
                // if its a JSONException then its already been error level logged
            }

            // if the news type is an achievement then we look for the details
            // otherwise we can skip this processing
            if (Utility.containsAchievement(currentNews.getType())) {
                GuildViewerAchievement achievement = new GuildViewerAchievement();
                JSONObject achievementObj = jsonNewsItem.getJSONObject(WOW_NEWS_ACHIEVEMENT);
                achievement.setDescription(achievementObj.getString(WOW_ACHIEVEMENT_DESCRIPTION));
                achievement.setTitle(achievementObj.getString(WOW_ACHIEVEMENT_TITLE));
                achievement.setIcon(achievementObj.getString(WOW_ACHIEVEMENT_ICON));
                currentNews.setAchievement(achievement);
            }

            // all the relevant data is extracted so create a ContentValues object
            // to store it and add it to the array of objects to process later
            ContentValues newsListValues = createValuesObject(currentNews);
            cVVector.add(newsListValues);

            // we know the first entry is the newest of all the news so use this
            // to save us some processing and time.
            if (!alreadyNotified && cVVector.size() == 1) {
                mSavedTimestamp = currentNews.getTimestamp();
                // only notify on the action bar for the very first entry aka newest entry
                notifyNews(mContext, currentNews, GUILD_VIEWER_NOTIFICATION_ID);
                alreadyNotified = true;
            }
            // send a notification if the news is about a favorite character
            // but only send the very first one encountered in the news list
            // this will override the newest news notification
            else if (!isNotified && currentNews.getCharacter().toLowerCase()
                    .equals(Utility.getCharacter(mContext).toLowerCase())) {
                notifyNews(mContext, currentNews, GUILD_VIEWER_FAVORITE_CHARACTER_NOTIFICATION);
                isNotified = true;
            }
            //Log.v(LOG_TAG, currentNews.toString());

            //write out news in small groups to keep from list view from
            // looking like its loading forever and forever on large news lists
            if (cVVector.size() == Constants.MIN_NEWS_ITEMS_TO_LOAD) {
                actualInsertCount += insertNews(cVVector);
            }
        }
        // We are done processing the JSON object
        // store any new and unique news records that were found and not yet stored
        actualInsertCount += insertNews(cVVector);

        // see if we need to update the latest timestamp information in the preference storage
        if (Utility.getPreferenceForLastNotificationDate(mContext) < mSavedTimestamp) {
            Utility.setPreferenceForLastNotificationDate(mContext, mSavedTimestamp);
        }
    } catch (JSONException e) {
        // if any JSON errors occurred log them and
        // for this app it is appropriate to just keep moving along... don't crash it!
        e.printStackTrace();
    }
    return actualInsertCount;
}

From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

/**
 * Parse the item information and store it if it is new and has not already been processed.
 *
 * @param wowItemJsonStr//from w w  w  . j a  v a 2  s .c  om
 *         JSON formatted string
 * @return GuildViewerItem Object with the Item information parsed from the JSON string
 *
 * @throws JSONException
 *         if any JSON object parsing fails
 * @see <a href="http://blizzard.github.io/api-wow-docs/">WOW API Documentation</a>
 */
private GuildViewerItem processItemDataFromJson(String wowItemJsonStr) throws JSONException {
    if (wowItemJsonStr == null)
        return null;

    // Item key values to parse from JSON string for Items
    final String WOW_ITEM_ID = "id";
    final String WOW_ITEM_NAME = "name";
    final String WOW_ITEM_ICON = "icon";
    final String WOW_ITEM_DESCRIPTION = "description";

    GuildViewerItem item = new GuildViewerItem();

    JSONObject itemJson = new JSONObject(wowItemJsonStr);
    item.setId(itemJson.getLong(WOW_ITEM_ID));
    item.setDescription(itemJson.getString(WOW_ITEM_DESCRIPTION));
    item.setName(itemJson.getString(WOW_ITEM_NAME));
    item.setIcon(itemJson.getString(WOW_ITEM_ICON));
    //Log.v(LOG_TAG, item.toString());

    // store this item locally
    return addItem(item);
}

From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

private int processGuildMembers(String guildJsonStr) {

    int actualInsertCount = 0;
    // check to see if there is anything to do
    if (guildJsonStr == null)
        return 0;

    // These are the item keys that we want to extra from the JSON object

    // Guild data keys
    final String WOW_GUILD_LAST_MODIFIED = "lastModified";
    final String WOW_GUILD_NAME = "name";
    final String WOW_GUILD_REALM = "realm";
    final String WOW_GUILD_BATTLEGROUP = "battlegroup";
    final String WOW_GUILD_LEVEL = "level";
    final String WOW_GUILD_SIDE = "side";
    final String WOW_GUILD_POINTS = "achievementPoints";
    final String WOW_GUILD_MEMBERS = "members";

    // Member data keys
    final String WOW_MEMBER_CHARACTER = "character";
    final String WOW_MEMBER_RANK = "rank";

    // Member character data keys
    final String WOW_MEMBER_NAME = "name";
    final String WOW_MEMBER_CLASS = "class";
    final String WOW_MEMBER_RACE = "race";
    final String WOW_MEMBER_GENDER = "gender";
    final String WOW_MEMBER_LEVEL = "level";
    final String WOW_MEMBER_POINTS = "achievementPoints";
    final String WOW_MEMBER_THUMBNAIL = "thumbnail";

    // store the last guild update and use it to keep the processing time to a minimum
    long mSavedTimestamp = Utility.getPreferenceForLastGuildMemberUpdate(mContext);

    // the region is not returned in the JSON data
    // so we use the same preference data that was used to get the JSON
    String region = Utility.getRegion(mContext);
    try {// w w w . ja v a2 s .co  m

        // create JSON object for the string
        JSONObject guildJson = new JSONObject(guildJsonStr);

        long modifiedTimestamp = guildJson.getLong(WOW_GUILD_LAST_MODIFIED);
        if (modifiedTimestamp <= mSavedTimestamp) {
            // we can stop processing now because nothing has changes since we
            // last checked. Save some processing power
            return actualInsertCount;
        }
        // create a guild object to hold the relevant data from the JSON object
        GuildViewerGuild currentGuild = new GuildViewerGuild();

        // do a timestamp check to keep processing to minimum
        currentGuild.setLastModified(modifiedTimestamp);

        // save this time for the next round
        mSavedTimestamp = modifiedTimestamp; // default to WOW's modified date

        // setup the guild object
        currentGuild.setName(guildJson.getString(WOW_GUILD_NAME));
        currentGuild.setRegion(region);
        currentGuild.setRealm(guildJson.getString(WOW_GUILD_REALM));
        currentGuild.setBattlegroup(guildJson.getString(WOW_GUILD_BATTLEGROUP));
        currentGuild.setLevel(guildJson.getInt(WOW_GUILD_LEVEL));
        int side = guildJson.getInt(WOW_GUILD_SIDE);
        currentGuild.setSide(Utility.getGuildSide(mContext, side));
        currentGuild.setAchievementPoints(guildJson.getInt(WOW_GUILD_POINTS));

        //Add this to the database so that I know what to set the guild ID to in the members
        // But first delete the one that is in the database!!
        int deleted = mContext.getContentResolver().delete(GuildEntry.CONTENT_URI, null, null);
        //Log.v(LOG_TAG, "Deleted " + Integer.toString(deleted) + " Guilds from Database.");

        ContentValues currentGuildValues = createValuesObject(currentGuild);
        Uri guildUri = mContext.getContentResolver().insert(GuildEntry.CONTENT_URI, currentGuildValues);
        int guildId = GuildEntry.getGuildIdFromUri(guildUri);
        //Log.v(LOG_TAG, "New Guild Id is " + Integer.toString(guildId) );

        // now process the array of guild members
        JSONArray membersArray = guildJson.getJSONArray(WOW_GUILD_MEMBERS);
        //Log.v(LOG_TAG, "Number of Guild Members Found in JSON:" + Integer.toString(membersArray.length()));

        // Insert the new members into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(membersArray.length());
        for (int i = 0; i < membersArray.length(); i++) {

            GuildViewerMember currentMember = new GuildViewerMember();

            // get the member object from the JSON object
            JSONObject jsonMember = membersArray.getJSONObject(i);
            // get the character object from the member object
            JSONObject characterJson = jsonMember.getJSONObject(WOW_MEMBER_CHARACTER);

            currentMember.setName(characterJson.getString(WOW_MEMBER_NAME));
            currentMember.setGuildId(guildId);
            currentMember.setLevel(characterJson.getInt(WOW_MEMBER_LEVEL));
            currentMember.setGender(Utility.getGender(mContext, characterJson.getInt(WOW_MEMBER_GENDER)));
            int raceId = characterJson.getInt(WOW_MEMBER_RACE);
            currentMember.setRace(Utility.getRace(mContext, raceId));
            currentMember.setCharacterClass(Utility.getClass(mContext, characterJson.getInt(WOW_MEMBER_CLASS)));
            currentMember.setSide(Utility.getSide(mContext, raceId));
            currentMember.setRank(jsonMember.getInt(WOW_MEMBER_RANK));
            currentMember.setAchievementPoints(characterJson.getInt(WOW_MEMBER_POINTS));
            currentMember.setThumbnail(characterJson.getString(WOW_MEMBER_THUMBNAIL));

            // all the relevant data is extracted so create a ContentValues object
            // to store it and add it to the array of objects to process later
            ContentValues memberListValues = createValuesObject(currentMember);
            cVVector.add(memberListValues);

            //Log.v(LOG_TAG, currentMember.toString());
        }

        // We are done processing the JSON object
        // store the new and unique news records that were found
        if (cVVector.size() > 0) {
            // convert to an array for the bulk insert to work with
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            // inserts into the storage
            actualInsertCount = mContext.getContentResolver().bulkInsert(MemberEntry.CONTENT_URI, cvArray);
        }

        // see if we need to update the latest timestamp information in the preference storage
        if (Utility.getPreferenceForLastGuildMemberUpdate(mContext) < mSavedTimestamp) {
            Utility.setPreferenceForLastGuildMemberUpdate(mContext, mSavedTimestamp);
        }
    } catch (JSONException e) {
        // if any JSON errors occurred log them and
        // for this app it is appropriate to just keep moving along... don't crash it!
    }
    return actualInsertCount;
}

From source file:edu.cwru.apo.Directory.java

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.phone) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    SharedPreferences.Editor editor = getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)
                            .edit();//w  w w.  ja  v  a  2s.  c o  m
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");
                    JSONArray caseID = result.getJSONArray("caseID");
                    JSONArray first = result.getJSONArray("first");
                    JSONArray last = result.getJSONArray("last");
                    JSONArray phone = result.getJSONArray("phone");
                    JSONArray family = result.getJSONArray("family");
                    ContentValues values;
                    for (int i = 0; i < numbros; i++) {
                        values = new ContentValues();
                        values.put("_id", caseID.getString(i));
                        values.put("first", first.getString(i));
                        values.put("last", last.getString(i));
                        values.put("phone", phone.getString(i));
                        values.put("family", family.getString(i));
                        database.replace("phoneDB", null, values);
                    }
                    loadTable();
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(this, "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Auth.loggedIn = false;
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                    finish();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:pe.chalk.takoyaki.target.NamuWiki.java

public NamuWiki(JSONObject properties) {
    super(properties.getString("prefix"), properties.getLong("interval"));
    this.getFilters().add(new StatusFilter(this));

    this.setName(this.getName() + " ()");
    this.staff = new Staff(this.getLogger(), properties.getInt("timeout"), "UTF-8");
}

From source file:com.soundcloud.playerapi.Token.java

/**
 * Construct a new token from a JSON response
 * @param json the json response/*w  w  w. j av  a 2s  .  c  o  m*/
 * @throws IOException JSON format error
 */
public Token(JSONObject json) throws IOException {
    try {
        for (Iterator it = json.keys(); it.hasNext();) {
            final String key = it.next().toString();
            if (ACCESS_TOKEN.equals(key)) {
                access = json.getString(key);
            } else if (REFRESH_TOKEN.equals(key)) {
                // refresh token won't be set if we don't expire
                refresh = json.getString(key);
            } else if (EXPIRES_IN.equals(key)) {
                expiresIn = System.currentTimeMillis() + json.getLong(key) * 1000;
            } else if (SCOPE.equals(key)) {
                scope = json.getString(key);
            } else {
                // custom parameter
                customParameters.put(key, json.get(key).toString());
            }
        }
    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.foxykeep.datadroidpoc.data.factory.PhoneAddEditFactory.java

public static Phone parseResult(String wsResponse) throws DataException {
    Phone phone = new Phone();

    try {/*from   w w w .j av a 2 s. co m*/
        JSONObject parser = new JSONObject(wsResponse);
        JSONObject jsonPhone = parser.getJSONObject(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_PHONE);

        phone.serverId = jsonPhone.getLong(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_ID);
        phone.name = jsonPhone.getString(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_NAME);
        phone.manufacturer = jsonPhone.getString(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_MANUFACTURER);
        phone.androidVersion = jsonPhone.getString(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_ANDROID_VERSION);
        phone.screenSize = jsonPhone.getDouble(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_SCREEN_SIZE);
        phone.price = jsonPhone.getInt(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_PRICE);
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
        throw new DataException(e);
    }

    return phone;
}

From source file:jatoo.weather.openweathermap.AbstractJaTooWeatherOpenWeatherMap.java

@Override
protected final JaTooWeather getWeatherImpl(final String city) throws Throwable {

    JSONObject json = new JSONObject(getJSONResponse(city));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(json.toString(2));/*  w  w  w  .j a  v a2s .c om*/
    }

    JSONObject jsonWeather = json.getJSONArray("weather").getJSONObject(0);
    JSONObject jsonMain = json.getJSONObject("main");
    JSONObject jsonWind = json.getJSONObject("wind");
    JSONObject jsonClouds = json.getJSONObject("clouds");
    JSONObject jsonSys = json.getJSONObject("sys");

    JaTooWeather weather = new JaTooWeather(this);

    weather.setCity(json.getString("name"));

    weather.setDescription(jsonWeather.getString("description"));

    weather.setTemperature(jsonMain.getDouble("temp"));
    weather.setTemperatureUnit(JaTooWeather.TEMPERATURE_UNIT.CELSIUS);

    weather.setHumidity(jsonMain.getInt("humidity"));
    weather.setHumidityUnit(JaTooWeather.HUMIDITY_UNIT.PERCENT);

    weather.setPressure(jsonMain.getDouble("pressure"));
    weather.setPressureUnit(JaTooWeather.PRESSURE_UNIT.HPA);

    weather.setWind(jsonWind.getDouble("speed"));
    weather.setWindUnit(JaTooWeather.WIND_UNIT.METER_PER_SEC);

    weather.setWindDirection(jsonWind.getDouble("deg"));
    weather.setWindDirectionUnit(JaTooWeather.WIND_DIRECTION_UNIT.DEGREES_METEOROLOGICAL);

    weather.setClouds(jsonClouds.getInt("all"));
    weather.setCloudsUnit(JaTooWeather.CLOUDS_UNIT.PERCENT);

    weather.setSunrise(TimeUnit.SECONDS.toMillis(jsonSys.getLong("sunrise")));
    weather.setSunset(TimeUnit.SECONDS.toMillis(jsonSys.getLong("sunset")));

    return weather;
}

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

/**
 * Make remote request to get all calls stored in Cozy
 *///www  .j a v  a2  s .c  o  m
public String getRemoteCalls() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        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) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                Call.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE,
                            "Reading calls on Cozy " + i + "/" + jsonArray.length() + "..."));
                    JSONObject callJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Call call = Call.getByRemoteId(callJson.get("_id").toString());
                    if (call == null) {
                        call = new Call(callJson);
                    } else {
                        call.setRemoteId(callJson.getString("_id"));
                        call.setCallerId(callJson.getString("callerId"));
                        call.setCallerNumber(callJson.getString("callerNumber"));
                        call.setDuration(callJson.getLong("duration"));
                        call.setDateAndTime(callJson.getString("dateAndTime"));
                        call.setType(callJson.getInt("type"));
                    }

                    call.save();

                    allCalls.add(call);
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, errorMessage));
        }

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

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

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

public void sendChangesToCozy() {
    List<Call> unSyncedCalls = Call.getAllUnsynced();
    int i = 0;//  w  w w.  j  ava  2  s . c  o m
    for (Call call : unSyncedCalls) {
        URL urlO = null;
        try {
            JSONObject jsonObject = call.toJsonObject();
            mBuilder.setProgress(unSyncedCalls.size(), i, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new CallSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_calls_send_changes)));
            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");
                call.setRemoteId(result);
                call.save();
            }

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

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