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.webpagebytes.cms.engine.JSONToFromObjectConverter.java

private <T> Object fieldFromJSON(org.json.JSONObject json, String fieldName, Class<T> fieldClass) {
    try {//ww w  . j  a v a  2s  .c  om
        if (fieldClass.getName().compareTo(STRING_CLASS_NAME) == 0) {
            return json.getString(fieldName);
        } else if (fieldClass.getName().compareTo(LONG_CLASS_NAME) == 0) {
            return json.getLong(fieldName);
        } else if (fieldClass.getName().compareTo(LNG_CLASS_NAME) == 0) {
            return json.getLong(fieldName);
        } else if (fieldClass.getName().compareTo(INTEGER_CLASS_NAME) == 0) {
            return json.getInt(fieldName);
        } else if (fieldClass.getName().compareTo(INT_CLASS_NAME) == 0) {
            return json.getInt(fieldName);
        } else if (fieldClass.getName().compareTo(DATE_CLASS_NAME) == 0) {
            return new Date(json.getLong(fieldName));
        }
    } catch (org.json.JSONException e) {
        return null;
    }
    return null;
}

From source file:org.emergent.android.weave.syncadapter.SyncAssistant.java

private Date getLastModified(UserWeave userWeave, String name) throws WeaveException {
    try {/* w w w .  java2  s .c om*/
        JSONObject infoCol = userWeave.getNode(HashNode.INFO_COLLECTIONS).getValue();
        Log.d(TAG, "infoCol (" + name + ") : " + infoCol.toString(2));
        if (infoCol.has(name)) {
            long modLong = infoCol.getLong(name);
            //        Log.w(TAG, "modLong (" + name + ") : " + modLong);
            return new Date(modLong * 1000);
            //          double lastMod = infoCol.getDouble(name);
            //          return WeaveUtil.toModifiedTimeDate(lastMod);
        }
        return null;
    } catch (JSONException e) {
        throw new WeaveException(e);
    }
}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

/**
 * return top festival results matching the search criteria. If the
 * number of found festival is lesser than the requested number of festivals all found
 * festivals are returned//from www  .ja v  a2 s. c  o m
 *
 * @param num      number of festivals to return
 * @param official official to filter the results by, <code>null</code> to ignore
 * @param name     name to filter the results by, <code>null</code> to ignore
 * @param country  country to filter the results by, <code>null</code> to ignore
 * @param city     city to filter the results by, <code>null</code> to ignore
 * @param genre    genre to filter the results by, <code>null</code> to ignore
 * @param minPrice minimum price to filter the results by, <code>null</code> to ignore
 * @param maxPrice maximum price to filter the results by, <code>null</code> to ignore
 * @param artist   artist performing in a concert hosted by the festival
 *                 to filter the results by, <code>null</code> to ignore
 * @return resulting festivals
 */
public Festival[] readMultipleFestivals(int num, Boolean official, String name, String country, String city,
        String genre, String minPrice, String maxPrice, String artist)
        throws ClientDoesNotHavePermissionException {
    try {
        URL url = new URL(ExternalDatabaseHelper.getReadMultipleFestivals());
        Map<String, String> parameters = new HashMap<>();
        parameters.put(ExternalDatabaseDefinitions.PARAMETER_NUMBER, String.valueOf(num));
        if (official != null)
            parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OFFICIAL,
                    String.valueOf(official));
        if (name != null)
            parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_NAME, name);
        if (country != null)
            parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_COUNTRY, country);
        if (city != null)
            parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_CITY, city);
        if (genre != null)
            parameters.put(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_GENRE, genre);
        if (minPrice != null)
            parameters.put(ExternalDatabaseDefinitions.PARAMETER_MIN_PRICE, minPrice);
        if (maxPrice != null)
            parameters.put(ExternalDatabaseDefinitions.PARAMETER_MAX_PRICE, maxPrice);
        if (artist != null)
            parameters.put(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_ARTIST, artist);
        String response = getRemoteData(url, parameters);
        JSONArray json = new JSONArray(response);
        Festival[] result = new Festival[json.length()];
        for (int i = 0; i < json.length(); i++) {
            JSONObject current = json.getJSONObject(i);
            result[i] = new Festival(-1L,
                    current.getLong(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ID),
                    current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_NAME),
                    current.getString(
                            ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_DESCRIPTION),
                    current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_COUNTRY),
                    current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_CITY),
                    current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ADDRESS),
                    current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_GENRE),
                    current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_PRICES),
                    current.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OWNER),
                    current.getBoolean(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OFFICIAL),
                    current.getInt(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_VOTES));
        }
        return result;
    } catch (JSONException | MalformedURLException ignore) {
        return null;
    }
}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

/**
 * @param festival festival object to return concerts for
 * @return an array of the concerts hosted by the festival or null on wrong input
 * @throws ClientDoesNotHavePermissionException
 *///from w  w w.j  av  a2s .  com
public Concert[] readFestivalConcerts(@NonNull Festival festival) throws ClientDoesNotHavePermissionException {
    try {
        URL url = new URL(ExternalDatabaseHelper.getReadMultipleConcerts());
        Map<String, String> parameters = new HashMap<>();
        parameters.put(ExternalDatabaseDefinitions.PARAMETER_ID, String.valueOf(festival.getId()));
        String content = getRemoteData(url, parameters);
        if (content == null)
            return null;
        if (content.equals(ExternalDatabaseDefinitions.RESPONSE_INVALID_FESTIVAL_ID))
            return null;
        JSONArray json = new JSONArray(content);
        Concert[] result = new Concert[json.length()];
        for (int i = 0; i < json.length(); i++) {
            JSONObject current = json.getJSONObject(i);
            result[i] = new Concert(null,
                    current.getLong(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_EXTERNAL_ID),
                    festival,
                    current.getString(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_ARTIST),
                    current.getInt(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_SCENE),
                    current.getInt(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_DAY),
                    new Date(current.getInt(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_START)),
                    new Date(current.getInt(ExternalDatabaseDefinitions.ConcertContext.RESULT_PARAMETER_END)),
                    false);
        }
        return result;
    } catch (MalformedURLException | JSONException ignore) {
        return null;
    }
}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

/**
 * @param festivalID external id of the festival
 * @return festival object or null/*from  w  ww .ja va  2  s. co  m*/
 * @throws ClientDoesNotHavePermissionException
 */
public Festival readFestivalInfo(long festivalID) throws ClientDoesNotHavePermissionException {
    if (festivalID < 0)
        return null;
    try {
        URL url = new URL(ExternalDatabaseHelper.getReadFestivalInfo());
        Map<String, String> parameters = new HashMap<>();
        parameters.put(ExternalDatabaseDefinitions.PARAMETER_ID, String.valueOf(festivalID));
        String response = getRemoteData(url, parameters);
        if (response == null)
            return null;
        if (response.equals(ExternalDatabaseDefinitions.RESPONSE_INVALID_FESTIVAL_ID))
            return null;
        JSONObject json = new JSONObject(response);
        return new Festival(-1L, json.getLong(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ID),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_NAME),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_DESCRIPTION),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_COUNTRY),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_CITY),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_ADDRESS),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_GENRE),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_PRICES),
                json.getString(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OWNER),
                json.getBoolean(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_OFFICIAL),
                json.getInt(ExternalDatabaseDefinitions.FestivalsContext.RESULT_PARAMETER_VOTES)

        );
    } catch (MalformedURLException | JSONException ignore) {
        return null;
    }
}

From source file:controllers.core.TimesheetController.java

/**
 * Save the weekly timesheet.//w  w  w.  j  a v a2  s .  c om
 */
@Restrict({ @Group(IMafConstants.TIMESHEET_ENTRY_PERMISSION) })
public Result weeklySave() {

    String[] dataString = request().body().asFormUrlEncoded().get("data");

    try {
        JSONObject dataJson = new JSONObject(dataString[0]);

        // get the report
        Long reportId = dataJson.getLong("reportId");
        TimesheetReport report = TimesheetDao.getTimesheetReportById(reportId);

        // create the date format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // get the actor
        Actor actor = getCurrentActor();

        // check the report belongs to the sign-in user
        if (!report.actor.id.equals(actor.id)) {
            return forbidden(views.html.error.access_forbidden.render(""));
        }

        // check the report is editable
        if (!report.isEditable()) {
            Utilities.sendErrorFlashMessage(Msg.get("core.timesheet.fill.save.error.non_editable"));
            return redirect(
                    controllers.core.routes.TimesheetController.weeklyFill(sdf.format(report.startDate)));
        }

        Ebean.beginTransaction();

        try {

            // get the entries
            JSONArray entriesJson = dataJson.getJSONArray("entries");

            for (int i = 0; i < entriesJson.length(); i++) {

                JSONObject entryJson;
                try {
                    entryJson = entriesJson.getJSONObject(i);
                } catch (JSONException e) {
                    entryJson = null;
                }

                if (entryJson != null) {

                    // get the attributes
                    boolean inDB = entryJson.getBoolean("inDB");

                    Boolean toRemove;
                    try {
                        toRemove = entryJson.getBoolean("toRemove");
                    } catch (JSONException e) {
                        toRemove = null;
                    }

                    Long entryId;
                    try {
                        entryId = entryJson.getLong("entryId");
                    } catch (JSONException e) {
                        entryId = null;
                    }

                    Long portfolioEntryId;
                    try {
                        portfolioEntryId = entryJson.getLong("portfolioEntryId");
                    } catch (JSONException e) {
                        portfolioEntryId = null;
                    }

                    Long packageId;
                    try {
                        packageId = entryJson.getLong("packageId");
                    } catch (JSONException e) {
                        packageId = null;
                    }

                    Long activityId;
                    try {
                        activityId = entryJson.getLong("activityId");
                    } catch (JSONException e) {
                        activityId = null;
                    }

                    // get the logs
                    JSONArray logsJson = entryJson.getJSONArray("logs");

                    if (logsJson.length() == 7) {

                        TimesheetEntry entry = null;
                        if (inDB) {
                            entry = TimesheetDao.getTimesheetEntryById(entryId);
                        } else {
                            entry = new TimesheetEntry();
                            entry.timesheetReport = report;
                        }

                        if (inDB && toRemove) {
                            entry.doDelete();
                        } else {

                            entry.portfolioEntry = null;
                            entry.portfolioEntryPlanningPackage = null;
                            entry.timesheetActivity = null;

                            if (portfolioEntryId != null) { // initiative
                                entry.portfolioEntry = PortfolioEntryDao.getPEById(portfolioEntryId);
                                if (packageId != null) {
                                    entry.portfolioEntryPlanningPackage = PortfolioEntryPlanningPackageDao
                                            .getPEPlanningPackageById(packageId);
                                }
                            } else { // activity
                                entry.timesheetActivity = TimesheetDao.getTimesheetActivityById(activityId);
                            }

                            entry.save();

                            for (int j = 0; j < logsJson.length(); j++) {

                                JSONObject logJson = logsJson.getJSONObject(j);

                                // get the attributes
                                double hours = logJson.getDouble("hours");

                                Long logId;
                                try {
                                    logId = logJson.getLong("logId");
                                } catch (JSONException e) {
                                    logId = null;
                                }

                                TimesheetLog log = null;
                                if (inDB) {
                                    log = TimesheetDao.getTimesheetLogById(logId);
                                } else {
                                    log = new TimesheetLog();
                                    log.timesheetEntry = entry;

                                    Calendar cal = Calendar.getInstance();
                                    cal.setTime(report.startDate);
                                    cal.add(Calendar.DAY_OF_YEAR, j);
                                    log.logDate = cal.getTime();
                                }

                                log.hours = hours;

                                log.save();

                            }
                        }

                    }

                }

            }

            Ebean.commitTransaction();

        } catch (Exception e) {
            Ebean.rollbackTransaction();
            return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(),
                    getI18nMessagesPlugin());
        }

        Utilities.sendSuccessFlashMessage(Msg.get("core.timesheet.fill.save.successful"));

        return redirect(controllers.core.routes.TimesheetController.weeklyFill(sdf.format(report.startDate)));

    } catch (Exception e) {
        return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(),
                getI18nMessagesPlugin());
    }

}

From source file:de.badaix.snapcast.control.RemoteControl.java

@Override
public void onMessageReceived(TcpClient tcpClient, String message) {
    //        Log.d(TAG, "Msg received: " + message);
    try {//from   w w  w.ja v a2  s  . c om
        JSONObject json = new JSONObject(message);
        if (json.has("id")) {
            //                Log.d(TAG, "ID: " + json.getString("id"));
            long id = json.getLong("id");
            String request = "";
            synchronized (pendingRequests) {
                if (pendingRequests.containsKey(id)) {
                    request = pendingRequests.get(id);
                    //                        Log.d(TAG, "Response to: " + request);
                    pendingRequests.remove(id);
                }
            }
            if (json.has("error")) {
                JSONObject error = json.getJSONObject("error");
                Log.e(TAG, "error " + error.getInt("code") + ": " + error.getString("message"));
            } else if (!TextUtils.isEmpty(request)) {
                if (request.equals("Server.GetStatus")) {
                    serverStatus.fromJson(json.getJSONObject("result"));
                    if (listener != null)
                        listener.onServerStatus(this, serverStatus);
                }
            }
        } else {
            String method = json.getString("method");
            //                Log.d(TAG, "Notification: " + method);
            if (method.contains("Client.On")) {
                final Client client = new Client(json.getJSONObject("params").getJSONObject("data"));
                //                    serverStatus.addClient(client);
                if (listener != null) {
                    ClientEvent event;
                    if (method.equals("Client.OnUpdate"))
                        listener.onClientEvent(this, client, ClientEvent.updated);
                    else if (method.equals("Client.OnConnect"))
                        listener.onClientEvent(this, client, ClientEvent.connected);
                    else if (method.equals("Client.OnDisconnect"))
                        listener.onClientEvent(this, client, ClientEvent.disconnected);
                    else if (method.equals("Client.OnDelete")) {
                        listener.onClientEvent(this, client, ClientEvent.deleted);
                    }
                }
            } else if (method.equals("Stream.OnUpdate")) {
                Stream stream = new Stream(json.getJSONObject("params").getJSONObject("data"));
                listener.onStreamUpdate(this, stream);
                Log.d(TAG, stream.toString());
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

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

@SuppressWarnings("nls")
public StoreObject updateCreator(JSONObject remote, boolean reinitCache) throws JSONException {
    if (reinitCache)
        readCreators();/*from w ww. ja  v  a2s .c o  m*/
    long id = remote.getLong("id_dashboard");
    StoreObject local = null;
    for (int i = 0; i < creators.length; ++i) {
        if (creators[i].getValue(OpencrxActivityCreator.REMOTE_ID).equals(id)) {
            local = creators[i];
            creatorExists[i] = true;
            break;
        }
    }

    if (local == null)
        local = new StoreObject();

    local.setValue(StoreObject.TYPE, OpencrxActivityCreator.TYPE);
    local.setValue(OpencrxActivityCreator.REMOTE_ID, id);
    local.setValue(OpencrxActivityCreator.NAME, ApiUtilities.decode(remote.getString("title")));
    local.setValue(OpencrxActivityCreator.CRX_ID, remote.getString("crx_id"));

    storeObjectDao.save(local);
    if (reinitCache)
        creators = null;
    return local;
}

From source file:com.jellymold.boss.NewsSearch.java

protected void parseResults(JSONObject jobj) throws JSONException {

    if (jobj != null) {

        setResponseCode(jobj.getInt("responsecode"));
        if (jobj.has("nextpage"))
            setNextPage(jobj.getString("nextpage"));
        if (jobj.has("prevpage"))
            setPrevPage(jobj.getString("prevpage"));
        setTotalResults(jobj.getLong("totalhits"));
        final long count = jobj.getLong("count");
        setPagerCount(count);// w  w  w . j av  a2 s. co  m
        setPagerStart(jobj.getLong("start"));

        this.setResults(new ArrayList<NewsSearchResult>((int) count));

        if (jobj.has("resultset_news")) {

            JSONArray res = jobj.getJSONArray("resultset_news");

            for (int i = 0; i < res.length(); i++) {
                JSONObject thisResult = res.getJSONObject(i);
                NewsSearchResult newsSearchResult = new NewsSearchResult();
                newsSearchResult.setDescription(thisResult.getString("abstract"));
                newsSearchResult.setClickUrl(thisResult.getString("clickurl"));
                newsSearchResult.setUrl(thisResult.getString("url"));
                newsSearchResult.setLanguage(thisResult.getString("language"));
                newsSearchResult.setSource(thisResult.getString("source"));
                newsSearchResult.setSourceUrl(thisResult.getString("sourceurl"));
                newsSearchResult.setTime(thisResult.getString("time"));
                newsSearchResult.setTitle(thisResult.getString("title"));
                newsSearchResult.setDate(thisResult.getString("date"));
                this.getResults().add(newsSearchResult);
            }
        }

    }
}

From source file:g7.bluesky.launcher3.InstallShortcutReceiver.java

private static PendingInstallShortcutInfo decode(String encoded, Context context) {
    try {//from  ww  w .j  a v a  2s  .c o  m
        JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue();
        Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);

        if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) {
            // The is an internal launcher target shortcut.
            UserHandleCompat user = UserManagerCompat.getInstance(context)
                    .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY));
            if (user == null) {
                return null;
            }

            LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context)
                    .resolveActivity(launcherIntent, user);
            return info == null ? null : new PendingInstallShortcutInfo(info, context);
        }

        Intent data = new Intent();
        data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY));

        String iconBase64 = object.optString(ICON_KEY);
        String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
        String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
        if (iconBase64 != null && !iconBase64.isEmpty()) {
            byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
            Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
        } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
            Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
            iconResource.resourceName = iconResourceName;
            iconResource.packageName = iconResourcePackageName;
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
        }

        return new PendingInstallShortcutInfo(data, context);
    } catch (JSONException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    } catch (URISyntaxException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    }
    return null;
}