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.citruspay.mobile.payment.client.rest.JSONUtils.java

public static Date getDate(JSONObject json, String name) throws JSONException {
    return new Date(json.getLong(name));
}

From source file:com.kakao.http.KakaoAsyncHandler.java

public Void onCompleted(final Response response) throws Exception {
    final URI requestUri = response.getUri();
    try {/*from   www  .  j  a  va  2 s . com*/
        if (!response.hasResponseStatus()) {
            sendError(response, "the response didn't have a response status");
            return null;
        }

        final int httpStatusCode = response.getStatusCode();
        if (httpStatusCode != HttpStatus.SC_OK) {
            return handleFailureHttpStatus(response, requestUri, httpStatusCode);
        } else {
            if (returnType.equals(Void.class)) {
                httpResponseHandler
                        .sendMessage(Message.obtain(httpResponseHandler, HttpRequestTask.SUCCESS, 0, 0));
            } else {
                Object result = null;
                if (checkResponseBody(response))
                    return null;
                if (APIErrorResult.class.equals(returnType)) {
                    JSONObject json = new JSONObject(response.getResponseBody());
                    result = new APIErrorResult(json.getInt("code"), json.getString("msg"));
                } else if (User.class.equals(returnType)) {
                    JSONObject json = new JSONObject(response.getResponseBody());
                    result = new User(json.getLong("id"));
                } else if (KakaoTalkProfile.class.equals(returnType)) {
                    JSONObject json = new JSONObject(response.getResponseBody());
                    result = new KakaoTalkProfile(json.getString("nickName"), json.getString("profileImageURL"),
                            json.getString("thumbnailURL"), json.getString("countryISO"));
                } else if (KakaoStoryUpload.class.equals(returnType)) {
                    JSONObject json = new JSONObject(response.getResponseBody());
                    result = new KakaoStoryUpload(json.getString("url"));
                } else if (KakaoStoryProfile.class.equals(returnType)) {
                    JSONObject json = new JSONObject(response.getResponseBody());

                    result = new KakaoStoryProfile(json.getString("nickName"),
                            json.getString("profileImageURL"), json.getString("thumbnailURL"),
                            json.getString("bgImageURL"), json.getString("birthday"),
                            "+".equals(json.getString("birthdayType")) ? KakaoStoryProfile.BirthdayType.SOLAR
                                    : KakaoStoryProfile.BirthdayType.LUNAR);
                } else if (Map.class.equals(returnType)) {
                    JSONObject json = new JSONObject(response.getResponseBody());
                    result = JsonHelper.MapFromJson(json);
                } else if (List.class.equals(returnType)) {
                    JSONArray json = new JSONArray(response.getResponseBody());
                    result = JsonHelper.ListFromJson(json);
                } else {
                    throw new IllegalStateException("unknown result type " + returnType);
                }
                httpResponseHandler.sendMessage(
                        Message.obtain(httpResponseHandler, HttpRequestTask.SUCCESS, 0, 0, result));
            }
            return null;
        }
    } catch (Exception e) {
        sendError(response, e.toString());
        return null;
    }
}

From source file:fi.helsinki.cs.iot.hub.IotHubHTTPDTest.java

@Test
public void testEnablerAPI() {
    String res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
            "http://127.0.0.1:" + port + "/enablers/", null);
    assertEquals("[]", res.trim());

    //Now I want to create a javascript plugin to attach to my enabler
    String pluginName = "MyPlugin";
    //now I want to had a javascript plugin
    File pluginFile = makePluginFile(pluginName);
    JSONObject jsonObject = makeJsonObjectForPlugin(pluginName, null, Type.JAVASCRIPT, pluginFile, false);
    assertNotNull(jsonObject);/*from ww  w.  j a va2  s . c om*/
    String myPluginString = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
            "http://127.0.0.1:" + port + "/plugins/", jsonObject.toString());
    JSONObject jPlugin = null;
    try {
        jPlugin = new JSONObject(myPluginString);
        long pluginId = jPlugin.getLong("id");
        String name = "MyEnabler";
        String metadata = "A freshly created enabler";
        JSONObject jEnabler = new JSONObject();
        jEnabler.put("plugin", pluginId);
        jEnabler.put("name", "fakeName");
        jEnabler.put("metadata", metadata);

        // I should get an enable with no features as it is not configured
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
                "http://127.0.0.1:" + port + "/enablers/", jEnabler.toString());
        JSONObject jexpectedEnabler = new JSONObject();
        jexpectedEnabler.put("id", 1);
        jexpectedEnabler.put("name", "fakeName");
        jexpectedEnabler.put("metadata", metadata);
        jexpectedEnabler.put("plugin", jPlugin);
        JSONArray array = new JSONArray();
        jexpectedEnabler.put("features", array);
        assertEquals(jexpectedEnabler.toString(), res.trim());

        String featureName = "MyFeature";
        JSONObject config = new JSONObject();
        config.put("name", featureName);
        config.put("isSupported", true);
        config.put("isAvailable", true);
        config.put("isReadable", true);
        config.put("isWritable", true);
        config.put("getNumberOfFeatures", 1);
        config.put("getFeatureDescription", featureName);
        config.put("value", "Uksomatonta");
        JSONObject data = new JSONObject();
        data.put("configuration", config);

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/fakeName", data.toString());
        JSONObject expectedFeature = new JSONObject();
        expectedFeature.put("id", 1);
        expectedFeature.put("isSupported", true);
        expectedFeature.put("isAtomicFeed", false);
        expectedFeature.put("name", featureName);
        expectedFeature.put("isWritable", true);
        expectedFeature.put("isReadable", true);
        expectedFeature.put("type", "whatever");
        expectedFeature.put("isAvailable", true);
        array.put(expectedFeature);
        jexpectedEnabler.put("features", array);
        jexpectedEnabler.put("config", config.toString());
        assertEquals(jexpectedEnabler.toString().length(), res.trim().length());

        //Now just change quicky the configuration
        config.put("value", "Hard to believe");
        data.put("configuration", config);
        data.put("name", name);
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/fakeName", data.toString());
        jexpectedEnabler.put("name", name);
        jexpectedEnabler.put("config", config.toString());
        assertEquals(jexpectedEnabler.toString().length(), res.trim().length());

        //Now I want to change the feature as an atomic feed
        data = new JSONObject();
        data.put("enableAsAtomicFeed", true);
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/" + name + "/" + featureName, data.toString());
        expectedFeature.put("id", 2);
        expectedFeature.put("isAtomicFeed", true);
        assertEquals(expectedFeature.toString(), res.trim());

        //Now I will check for feeds
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/", null);
        JSONArray feedArray = new JSONArray(res);
        assertEquals(1, feedArray.length());
        JSONObject feed1 = feedArray.getJSONObject(0);
        String feedName = feed1.getString("name");
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, null);
        assertEquals("\"Hard to believe\"", res.trim());

        JSONObject toPostToFeed = new JSONObject("{\"test\": \"Unbelievable\"}");
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, toPostToFeed.toString());
        assertEquals(toPostToFeed.toString(), res.trim());

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, null);
        assertEquals(toPostToFeed.toString(), res.trim());

        data.put("enableAsAtomicFeed", false);
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/enablers/" + name + "/" + featureName, data.toString());
        expectedFeature.put("isAtomicFeed", false);
        assertEquals(expectedFeature.toString(), res.trim());

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/feeds/" + feedName, null);
        JSONObject jerror = new JSONObject(res);
        assertEquals("Error", jerror.getString("status"));

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:fi.helsinki.cs.iot.hub.IotHubHTTPDTest.java

@Test
public void testServiceAPI() {
    String res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
            "http://127.0.0.1:" + port + "/services/", null);
    assertEquals("[]", res.trim());

    //Now I want to create a javascript plugin to attach to my service
    String pluginName = "MyPlugin";
    //now I want to had a javascript plugin
    File pluginFile = makePluginFileForService(pluginName);
    JSONObject jsonObject = makeJsonObjectForPlugin(pluginName, null, Type.JAVASCRIPT, pluginFile, true);
    assertNotNull(jsonObject);//from  w ww .java2s  .  c  o m
    String myPluginString = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
            "http://127.0.0.1:" + port + "/plugins/", jsonObject.toString());
    JSONObject jPlugin = null;
    try {
        jPlugin = new JSONObject(myPluginString);
        long pluginId = jPlugin.getLong("id");
        String name = "MyService";
        String metadata = "A freshly created service";
        JSONObject jservice = new JSONObject();
        jservice.put("plugin", pluginId);
        jservice.put("name", name);
        jservice.put("metadata", metadata);
        jservice.put("bootAtStartup", false);

        // I should get an enable with no features as it is not configured
        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("POST",
                "http://127.0.0.1:" + port + "/services/", jservice.toString());
        JSONObject jexpectedService = new JSONObject();
        jexpectedService.put("id", 1);
        jexpectedService.put("name", name);
        jexpectedService.put("metadata", metadata);
        jexpectedService.put("plugin", jPlugin);
        jexpectedService.put("bootAtStartup", false);
        assertEquals(jexpectedService.toString(), res.trim());

        JSONObject data = new JSONObject();
        JSONObject config = new JSONObject();
        config.put("value", "Text to print");
        data.put("configuration", config);

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("PUT",
                "http://127.0.0.1:" + port + "/services/" + name, data.toString());
        jexpectedService.put("id", 1);
        jexpectedService.put("config", config.toString());
        assertEquals(jexpectedService.toString(), res.trim());

        res = DuktapeJavascriptEngineWrapper.performJavaHttpRequest("GET",
                "http://127.0.0.1:" + port + "/services/" + name + "/start", null);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            fail(e.getMessage());
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        fail(e.getMessage());
    }
}

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

/**
 * Returns the number of decks using the options group of the current deck.
 *///  w  ww .j a va2s .co  m
private int getOptionsGroupCount() {
    int count = 0;
    try {
        long conf = mDeck.getLong("conf");
        for (JSONObject deck : mCol.getDecks().all()) {
            if (deck.getInt("dyn") == 1) {
                continue;
            }
            if (deck.getLong("conf") == conf) {
                count++;
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return count;
}

From source file:com.mongolduu.android.ng.misc.HttpConnector.java

protected static long getLong(JSONObject json, String key) {
    long value = -1;
    try {//from  www  .  j av a  2 s.c  o m
        value = json.getLong(key);
    } catch (JSONException e) {
        Log.e(IMongolduuConstants.LOG_TAG, "exception", e);
    }
    return value;
}

From source file:tritop.android.naturalselectionnews.StatsWorker.java

private boolean parseWarJSON(String json) {
    if (json != null) {
        try {/*from www.  j  av  a  2  s.c  o  m*/
            JSONArray jsonArray = new JSONArray(json);
            synchronized (dbHelper) {
                dbHelper.beginBulkWork();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    long date = obj.getLong(DBHelper.WAR_STATS_DATA_DATE);
                    String map = obj.getString(DBHelper.WAR_STATS_DATA_MAP);
                    double length = obj.getDouble(DBHelper.WAR_STATS_DATA_LENGTH);
                    int winner = obj.getInt(DBHelper.WAR_STATS_DATA_WINNER);
                    double version = obj.getDouble(DBHelper.WAR_STATS_DATA_VERSION);
                    dbHelper.insertBulkWarStatsValues(date, map, length, winner, version);
                }
                dbHelper.endBulkWork();
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}

From source file:net.dv8tion.jda.core.managers.GuildController.java

/**
 * Creates a new {@link net.dv8tion.jda.core.entities.Emote Emote} in this Guild.
 * <br>If one or more Roles are specified the new Emote will only be available to Members with any of the specified Roles (see {@link Member#canInteract(Emote)})
 * <br>For this to be successful, the logged in account has to have the {@link net.dv8tion.jda.core.Permission#MANAGE_EMOTES MANAGE_EMOTES} Permission.
 *
 * <p><b><u>Unicode emojis are not included as {@link net.dv8tion.jda.core.entities.Emote Emote}!</u></b>
 * <br>Roles may only be available for whitelisted accounts.
 *
 * <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} caused by
 * the returned {@link net.dv8tion.jda.core.requests.RestAction RestAction} include the following:
 * <ul>//from   www . j a  va2 s  .c  o  m
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>The emote could not be created due to a permission discrepancy</li>
 *
 *     <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>We were removed from the Guild before finishing the task</li>
 * </ul>
 *
 * @param  name
 *         The name for the new Emote
 * @param  icon
 *         The {@link net.dv8tion.jda.core.entities.Icon} for the new Emote
 * @param  roles
 *         The {@link net.dv8tion.jda.core.entities.Role Roles} the new Emote should be restricted to
 *         <br>If no roles are provided the Emote will be available to all Members of this Guild
 *
 * @throws net.dv8tion.jda.core.exceptions.PermissionException
 *         If the logged in account does not have the {@link net.dv8tion.jda.core.Permission#MANAGE_EMOTES MANAGE_EMOTES} Permission
 * @throws net.dv8tion.jda.core.exceptions.GuildUnavailableException
 *         If the guild is temporarily not {@link net.dv8tion.jda.core.entities.Guild#isAvailable() available}
 * @throws net.dv8tion.jda.core.exceptions.AccountTypeException
 *         If the logged in account is not from {@link net.dv8tion.jda.core.AccountType#CLIENT AccountType.CLIENT}
 *
 * @return {@link net.dv8tion.jda.core.requests.restaction.AuditableRestAction AuditableRestAction} - Type: {@link net.dv8tion.jda.core.entities.Emote Emote}
 *         <br>The newly created Emote
 */
@CheckReturnValue
public AuditableRestAction<Emote> createEmote(String name, Icon icon, Role... roles) {
    checkAvailable();
    checkPermission(Permission.MANAGE_EMOTES);
    Checks.notNull(name, "emote name");
    Checks.notNull(icon, "emote icon");

    if (getJDA().getAccountType() != AccountType.CLIENT)
        throw new AccountTypeException(AccountType.CLIENT);

    JSONObject body = new JSONObject();
    body.put("name", name);
    body.put("image", icon.getEncoding());
    if (roles.length > 0) // making sure none of the provided roles are null before mapping them to the snowflake id
        body.put("roles",
                Stream.of(roles).filter(Objects::nonNull).map(ISnowflake::getId).collect(Collectors.toSet()));

    Route.CompiledRoute route = Route.Emotes.CREATE_EMOTE.compile(guild.getId());
    return new AuditableRestAction<Emote>(getJDA(), route, body) {
        @Override
        protected void handleResponse(Response response, Request<Emote> request) {
            if (response.isOk()) {
                JSONObject obj = response.getObject();
                final long id = obj.getLong("id");
                String name = obj.getString("name");
                EmoteImpl emote = new EmoteImpl(id, guild).setName(name);
                // managed is false by default, should always be false for emotes created by client accounts.

                JSONArray rolesArr = obj.getJSONArray("roles");
                Set<Role> roleSet = emote.getRoleSet();
                for (int i = 0; i < rolesArr.length(); i++) {
                    roleSet.add(guild.getRoleById(rolesArr.getString(i)));
                }

                // put emote into cache
                ((GuildImpl) guild).getEmoteMap().put(id, emote);

                request.onSuccess(emote);
            } else
                request.onFailure(response);
        }
    };
}

From source file:com.facebook.login.DeviceAuthDialog.java

public void startLogin(final LoginClient.Request request) {
    Bundle parameters = new Bundle();
    parameters.putString("type", "device_code");
    parameters.putString("client_id", FacebookSdk.getApplicationId());
    parameters.putString("scope", TextUtils.join(",", request.getPermissions()));
    GraphRequest graphRequest = new GraphRequest(null, DEVICE_OUATH_ENDPOINT, parameters, HttpMethod.POST,
            new GraphRequest.Callback() {
                @Override// w w w  .  ja v a  2  s  .  c  o  m
                public void onCompleted(GraphResponse response) {
                    if (response.getError() != null) {
                        onError(response.getError().getException());
                        return;
                    }

                    JSONObject jsonObject = response.getJSONObject();
                    RequestState requestState = new RequestState();
                    try {
                        requestState.setUserCode(jsonObject.getString("user_code"));
                        requestState.setRequestCode(jsonObject.getString("code"));
                        requestState.setInterval(jsonObject.getLong("interval"));
                    } catch (JSONException ex) {
                        onError(new FacebookException(ex));
                        return;
                    }

                    setCurrentRequestState(requestState);
                }
            });
    graphRequest.executeAsync();
}

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

@Override
protected Long handleInternally(JSONObject content) {
    JSONObject emoji = content.getJSONObject("emoji");

    final long userId = content.getLong("user_id");
    final long messageId = content.getLong("message_id");
    final long channelId = content.getLong("channel_id");

    final Long emojiId = emoji.isNull("id") ? null : emoji.getLong("id");
    String emojiName = emoji.isNull("name") ? null : emoji.getString("name");

    if (emojiId == null && emojiName == null) {
        WebSocketClient.LOG.debug(//from   www  . j a va 2s  .  c o m
                "Received a reaction " + (add ? "add" : "remove") + " with no name nor id. json: " + content);
        return null;
    }

    User user = api.getUserById(userId);
    if (user == null)
        user = api.getFakeUserMap().get(userId);
    if (user == null) {
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("Received a reaction for a user that JDA does not currently have cached");
        return null;
    }

    MessageChannel channel = api.getTextChannelById(channelId);
    if (channel == null) {
        channel = api.getPrivateChannelById(channelId);
    }
    if (channel == null && api.getAccountType() == AccountType.CLIENT) {
        channel = api.asClient().getGroupById(channelId);
    }
    if (channel == null) {
        channel = api.getFakePrivateChannelMap().get(channelId);
    }
    if (channel == null) {
        api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("Received a reaction for a channel that JDA does not currently have cached");
        return null;
    }

    MessageReaction.ReactionEmote rEmote;
    if (emojiId != null) {
        Emote emote = api.getEmoteById(emojiId);
        if (emote == null) {
            if (emojiName != null) {
                emote = new EmoteImpl(emojiId, api).setName(emojiName);
            } else {
                WebSocketClient.LOG.debug("Received a reaction " + (add ? "add" : "remove")
                        + " with a null name. json: " + content);
                return null;
            }
        }
        rEmote = new MessageReaction.ReactionEmote(emote);
    } else {
        rEmote = new MessageReaction.ReactionEmote(emojiName, null, api);
    }
    MessageReaction reaction = new MessageReaction(channel, rEmote, messageId, user.equals(api.getSelfUser()),
            -1);

    if (add)
        onAdd(reaction, user);
    else
        onRemove(reaction, user);
    return null;
}